3a2ea44f80277d93d34853fc5eea206d7f72d78a
[anni] / lib / mix / tasks / pleroma / config.ex
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
5 defmodule Mix.Tasks.Pleroma.Config do
6   use Mix.Task
7
8   import Ecto.Query
9   import Mix.Pleroma
10
11   alias Pleroma.ConfigDB
12   alias Pleroma.Repo
13
14   @shortdoc "Manages the location of the config"
15   @moduledoc File.read!("docs/administration/CLI_tasks/config.md")
16
17   def run(["migrate_to_db"]) do
18     check_configdb(fn ->
19       start_pleroma()
20       migrate_to_db()
21     end)
22   end
23
24   def run(["migrate_from_db" | options]) do
25     check_configdb(fn ->
26       start_pleroma()
27
28       {opts, _} =
29         OptionParser.parse!(options,
30           strict: [env: :string, delete: :boolean, path: :string],
31           aliases: [d: :delete]
32         )
33
34       migrate_from_db(opts)
35     end)
36   end
37
38   def run(["dump"]) do
39     check_configdb(fn ->
40       start_pleroma()
41
42       header = config_header()
43
44       settings =
45         ConfigDB
46         |> Repo.all()
47         |> Enum.sort()
48
49       unless settings == [] do
50         shell_info("#{header}")
51
52         Enum.each(settings, &dump(&1))
53       else
54         shell_error("No settings in ConfigDB.")
55       end
56     end)
57   end
58
59   def run(["dump", group, key]) do
60     check_configdb(fn ->
61       start_pleroma()
62
63       group = maybe_atomize(group)
64       key = maybe_atomize(key)
65
66       group
67       |> ConfigDB.get_by_group_and_key(key)
68       |> dump()
69     end)
70   end
71
72   def run(["dump", group]) do
73     check_configdb(fn ->
74       start_pleroma()
75
76       group = maybe_atomize(group)
77
78       dump_group(group)
79     end)
80   end
81
82   def run(["groups"]) do
83     check_configdb(fn ->
84       start_pleroma()
85
86       groups =
87         ConfigDB
88         |> distinct([c], true)
89         |> select([c], c.group)
90         |> Repo.all()
91
92       if length(groups) > 0 do
93         shell_info("The following configuration groups are set in ConfigDB:\r\n")
94         groups |> Enum.each(fn x -> shell_info("-  #{x}") end)
95         shell_info("\r\n")
96       end
97     end)
98   end
99
100   def run(["reset", "--force"]) do
101     check_configdb(fn ->
102       start_pleroma()
103       truncatedb()
104       shell_info("The ConfigDB settings have been removed from the database.")
105     end)
106   end
107
108   def run(["reset"]) do
109     check_configdb(fn ->
110       start_pleroma()
111
112       shell_info("The following settings will be permanently removed:")
113
114       ConfigDB
115       |> Repo.all()
116       |> Enum.sort()
117       |> Enum.each(&dump(&1))
118
119       shell_error("\nTHIS CANNOT BE UNDONE!")
120
121       if shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
122         truncatedb()
123
124         shell_info("The ConfigDB settings have been removed from the database.")
125       else
126         shell_error("No changes made.")
127       end
128     end)
129   end
130
131   def run(["delete", "--force", group, key]) do
132     start_pleroma()
133
134     group = maybe_atomize(group)
135     key = maybe_atomize(key)
136
137     with true <- key_exists?(group, key) do
138       shell_info("The following settings will be removed from ConfigDB:\n")
139
140       group
141       |> ConfigDB.get_by_group_and_key(key)
142       |> dump()
143
144       delete_key(group, key)
145     else
146       _ ->
147         shell_error("No settings in ConfigDB for #{inspect(group)}, #{inspect(key)}. Aborting.")
148     end
149   end
150
151   def run(["delete", "--force", group]) do
152     start_pleroma()
153
154     group = maybe_atomize(group)
155
156     with true <- group_exists?(group) do
157       shell_info("The following settings will be removed from ConfigDB:\n")
158       dump_group(group)
159       delete_group(group)
160     else
161       _ -> shell_error("No settings in ConfigDB for #{inspect(group)}. Aborting.")
162     end
163   end
164
165   def run(["delete", group, key]) do
166     start_pleroma()
167
168     group = maybe_atomize(group)
169     key = maybe_atomize(key)
170
171     with true <- key_exists?(group, key) do
172       shell_info("The following settings will be removed from ConfigDB:\n")
173
174       group
175       |> ConfigDB.get_by_group_and_key(key)
176       |> dump()
177
178       if shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
179         delete_key(group, key)
180       else
181         shell_error("No changes made.")
182       end
183     else
184       _ ->
185         shell_error("No settings in ConfigDB for #{inspect(group)}, #{inspect(key)}. Aborting.")
186     end
187   end
188
189   def run(["delete", group]) do
190     start_pleroma()
191
192     group = maybe_atomize(group)
193
194     with true <- group_exists?(group) do
195       shell_info("The following settings will be removed from ConfigDB:\n")
196       dump_group(group)
197
198       if shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
199         delete_group(group)
200       else
201         shell_error("No changes made.")
202       end
203     else
204       _ -> shell_error("No settings in ConfigDB for #{inspect(group)}. Aborting.")
205     end
206   end
207
208   @spec migrate_to_db(Path.t() | nil) :: any()
209   def migrate_to_db(file_path \\ nil) do
210     with :ok <- Pleroma.Config.DeprecationWarnings.warn() do
211       config_file =
212         if file_path do
213           file_path
214         else
215           if Pleroma.Config.get(:release) do
216             Pleroma.Config.get(:config_path)
217           else
218             "config/#{Pleroma.Config.get(:env)}.secret.exs"
219           end
220         end
221
222       do_migrate_to_db(config_file)
223     else
224       _ ->
225         shell_error("Migration is not allowed until all deprecation warnings have been resolved.")
226     end
227   end
228
229   defp do_migrate_to_db(config_file) do
230     if File.exists?(config_file) do
231       shell_info("Migrating settings from file: #{Path.expand(config_file)}")
232       truncatedb()
233
234       custom_config =
235         config_file
236         |> read_file()
237         |> elem(0)
238
239       custom_config
240       |> Keyword.keys()
241       |> Enum.each(&create(&1, custom_config))
242     else
243       shell_info("To migrate settings, you must define custom settings in #{config_file}.")
244     end
245   end
246
247   defp create(group, settings) do
248     group
249     |> Pleroma.Config.Loader.filter_group(settings)
250     |> Enum.each(fn {key, value} ->
251       {:ok, _} = ConfigDB.update_or_create(%{group: group, key: key, value: value})
252
253       shell_info("Settings for key #{key} migrated.")
254     end)
255
256     shell_info("Settings for group #{inspect(group)} migrated.")
257   end
258
259   defp migrate_from_db(opts) do
260     env = opts[:env] || Pleroma.Config.get(:env)
261
262     filename = "#{env}.exported_from_db.secret.exs"
263
264     config_path =
265       cond do
266         opts[:path] ->
267           opts[:path]
268
269         Pleroma.Config.get(:release) ->
270           :config_path
271           |> Pleroma.Config.get()
272           |> Path.dirname()
273
274         true ->
275           "config"
276       end
277       |> Path.join(filename)
278
279     with {:ok, file} <- File.open(config_path, [:write, :utf8]) do
280       write_config(file, config_path, opts)
281       shell_info("Database configuration settings have been exported to #{config_path}")
282     else
283       _ ->
284         shell_error("Impossible to save settings to this directory #{Path.dirname(config_path)}")
285         tmp_config_path = Path.join(System.tmp_dir!(), filename)
286         file = File.open!(tmp_config_path)
287
288         shell_info(
289           "Saving database configuration settings to #{tmp_config_path}. Copy it to the #{Path.dirname(config_path)} manually."
290         )
291
292         write_config(file, tmp_config_path, opts)
293     end
294   end
295
296   defp write_config(file, path, opts) do
297     IO.write(file, config_header())
298
299     ConfigDB
300     |> Repo.all()
301     |> Enum.each(&write_and_delete(&1, file, opts[:delete]))
302
303     :ok = File.close(file)
304     System.cmd("mix", ["format", path])
305   end
306
307   defp config_header, do: "import Config\r\n\r\n"
308   defp read_file(config_file), do: Config.Reader.read_imports!(config_file)
309
310   defp write_and_delete(config, file, delete?) do
311     config
312     |> write(file)
313     |> delete(delete?)
314   end
315
316   defp write(config, file) do
317     value = inspect(config.value, limit: :infinity)
318
319     IO.write(file, "config #{inspect(config.group)}, #{inspect(config.key)}, #{value}\r\n\r\n")
320
321     config
322   end
323
324   defp delete(config, true) do
325     {:ok, _} = Repo.delete(config)
326
327     shell_info(
328       "config #{inspect(config.group)}, #{inspect(config.key)} was deleted from the ConfigDB."
329     )
330   end
331
332   defp delete(_config, _), do: :ok
333
334   defp dump(%ConfigDB{} = config) do
335     value = inspect(config.value, limit: :infinity)
336
337     shell_info("config #{inspect(config.group)}, #{inspect(config.key)}, #{value}\r\n\r\n")
338   end
339
340   defp dump(_), do: :noop
341
342   defp dump_group(group) when is_atom(group) do
343     group
344     |> ConfigDB.get_all_by_group()
345     |> Enum.each(&dump/1)
346   end
347
348   defp group_exists?(group) do
349     group
350     |> ConfigDB.get_all_by_group()
351     |> Enum.any?()
352   end
353
354   defp key_exists?(group, key) do
355     group
356     |> ConfigDB.get_by_group_and_key(key)
357     |> is_nil
358     |> Kernel.!()
359   end
360
361   defp maybe_atomize(arg) when is_atom(arg), do: arg
362
363   defp maybe_atomize(":" <> arg), do: maybe_atomize(arg)
364
365   defp maybe_atomize(arg) when is_binary(arg) do
366     if ConfigDB.module_name?(arg) do
367       String.to_existing_atom("Elixir." <> arg)
368     else
369       String.to_atom(arg)
370     end
371   end
372
373   defp check_configdb(callback) do
374     with true <- Pleroma.Config.get([:configurable_from_database]) do
375       callback.()
376     else
377       _ ->
378         shell_error(
379           "ConfigDB not enabled. Please check the value of :configurable_from_database in your configuration."
380         )
381     end
382   end
383
384   defp delete_key(group, key) do
385     check_configdb(fn ->
386       ConfigDB.delete(%{group: group, key: key})
387     end)
388   end
389
390   defp delete_group(group) do
391     check_configdb(fn ->
392       group
393       |> ConfigDB.get_all_by_group()
394       |> Enum.each(&ConfigDB.delete/1)
395     end)
396   end
397
398   defp truncatedb do
399     Ecto.Adapters.SQL.query!(Repo, "TRUNCATE config;")
400     Ecto.Adapters.SQL.query!(Repo, "ALTER SEQUENCE config_id_seq RESTART;")
401   end
402 end