full update for some subkeys
[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 if group != :phoenix and key != :serve_endpoints do
41 default = Pleroma.Config.Holder.config(group, key)
42
43 merged_value =
44 if can_be_merged?(default, value) do
45 ConfigDB.deep_merge(group, key, default, value)
46 else
47 value
48 end
49
50 :ok = Application.put_env(group, key, merged_value)
51
52 if group != :logger do
53 group
54 else
55 # change logger configuration in runtime, without restart
56 if Keyword.keyword?(merged_value) and
57 key not in [:compile_time_application, :backends, :compile_time_purge_matching] do
58 Logger.configure_backend(key, merged_value)
59 else
60 Logger.configure([{key, merged_value}])
61 end
62
63 nil
64 end
65 end
66 rescue
67 e ->
68 Logger.warn(
69 "updating env causes error, group: #{inspect(setting.group)}, key: #{
70 inspect(setting.key)
71 }, value: #{inspect(ConfigDB.from_binary(setting.value))}, error: #{inspect(e)}"
72 )
73
74 nil
75 end
76 end
77
78 defp restart(started_applications, app) do
79 with {^app, _, _} <- List.keyfind(started_applications, app, 0),
80 :ok <- Application.stop(app) do
81 :ok = Application.start(app)
82 else
83 nil -> Logger.warn("#{app} is not started.")
84 error -> Logger.warn(inspect(error))
85 end
86 end
87
88 defp can_be_merged?(val1, val2) when is_map(val1) and is_map(val2), do: true
89
90 defp can_be_merged?(val1, val2) when is_list(val1) and is_list(val2) do
91 Keyword.keyword?(val1) and Keyword.keyword?(val2)
92 end
93
94 defp can_be_merged?(_val1, _val2), do: false
95 end