e70ca709a588827edf4a8ac3cd716aef7369f9ef
[akkoma] / lib / mix / tasks / pleroma / config.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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/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(["dump_to_file", group, key]) do
83 check_configdb(fn ->
84 start_pleroma()
85
86 group = maybe_atomize(group)
87 key = maybe_atomize(key)
88
89 config = ConfigDB.get_by_group_and_key(group, key)
90 json = %{
91 group: ConfigDB.to_json_types(config.group),
92 key: ConfigDB.to_json_types(config.key),
93 value: ConfigDB.to_json_types(config.value),
94 }
95 |> Jason.encode!()
96 |> Jason.Formatter.pretty_print()
97
98 File.write("#{group}_#{key}.json", json)
99 shell_info("Wrote #{group}_#{key}.json")
100 end)
101 end
102
103 def run(["load_from_file", fname]) do
104 check_configdb(fn ->
105 start_pleroma()
106
107 json = File.read!(fname)
108 config = Jason.decode!(json)
109 group = ConfigDB.to_elixir_types(config["group"])
110 key = ConfigDB.to_elixir_types(config["key"])
111 value = ConfigDB.to_elixir_types(config["value"])
112 params = %{group: group, key: key, value: value}
113
114 ConfigDB.update_or_create(params)
115 shell_info("Loaded #{config["group"]}, #{config["key"]}")
116 end)
117 end
118
119 def run(["groups"]) do
120 check_configdb(fn ->
121 start_pleroma()
122
123 groups =
124 ConfigDB
125 |> distinct([c], true)
126 |> select([c], c.group)
127 |> Repo.all()
128
129 if length(groups) > 0 do
130 shell_info("The following configuration groups are set in ConfigDB:\r\n")
131 groups |> Enum.each(fn x -> shell_info("- #{x}") end)
132 shell_info("\r\n")
133 end
134 end)
135 end
136
137 def run(["reset", "--force"]) do
138 check_configdb(fn ->
139 start_pleroma()
140 truncatedb()
141 shell_info("The ConfigDB settings have been removed from the database.")
142 end)
143 end
144
145 def run(["reset"]) do
146 check_configdb(fn ->
147 start_pleroma()
148
149 shell_info("The following settings will be permanently removed:")
150
151 ConfigDB
152 |> Repo.all()
153 |> Enum.sort()
154 |> Enum.each(&dump(&1))
155
156 shell_error("\nTHIS CANNOT BE UNDONE!")
157
158 if shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
159 truncatedb()
160
161 shell_info("The ConfigDB settings have been removed from the database.")
162 else
163 shell_error("No changes made.")
164 end
165 end)
166 end
167
168 def run(["delete", "--force", group, key]) do
169 start_pleroma()
170
171 group = maybe_atomize(group)
172 key = maybe_atomize(key)
173
174 with true <- key_exists?(group, key) do
175 shell_info("The following settings will be removed from ConfigDB:\n")
176
177 group
178 |> ConfigDB.get_by_group_and_key(key)
179 |> dump()
180
181 delete_key(group, key)
182 else
183 _ ->
184 shell_error("No settings in ConfigDB for #{inspect(group)}, #{inspect(key)}. Aborting.")
185 end
186 end
187
188 def run(["delete", "--force", group]) do
189 start_pleroma()
190
191 group = maybe_atomize(group)
192
193 with true <- group_exists?(group) do
194 shell_info("The following settings will be removed from ConfigDB:\n")
195 dump_group(group)
196 delete_group(group)
197 else
198 _ -> shell_error("No settings in ConfigDB for #{inspect(group)}. Aborting.")
199 end
200 end
201
202 def run(["delete", group, key]) do
203 start_pleroma()
204
205 group = maybe_atomize(group)
206 key = maybe_atomize(key)
207
208 with true <- key_exists?(group, key) do
209 shell_info("The following settings will be removed from ConfigDB:\n")
210
211 group
212 |> ConfigDB.get_by_group_and_key(key)
213 |> dump()
214
215 if shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
216 delete_key(group, key)
217 else
218 shell_error("No changes made.")
219 end
220 else
221 _ ->
222 shell_error("No settings in ConfigDB for #{inspect(group)}, #{inspect(key)}. Aborting.")
223 end
224 end
225
226 def run(["delete", group]) do
227 start_pleroma()
228
229 group = maybe_atomize(group)
230
231 with true <- group_exists?(group) do
232 shell_info("The following settings will be removed from ConfigDB:\n")
233 dump_group(group)
234
235 if shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
236 delete_group(group)
237 else
238 shell_error("No changes made.")
239 end
240 else
241 _ -> shell_error("No settings in ConfigDB for #{inspect(group)}. Aborting.")
242 end
243 end
244
245 @spec migrate_to_db(Path.t() | nil) :: any()
246 def migrate_to_db(file_path \\ nil) do
247 with :ok <- Pleroma.Config.DeprecationWarnings.warn() do
248 config_file =
249 if file_path do
250 file_path
251 else
252 if Pleroma.Config.get(:release) do
253 Pleroma.Config.get(:config_path)
254 else
255 "config/#{Pleroma.Config.get(:env)}.secret.exs"
256 end
257 end
258
259 do_migrate_to_db(config_file)
260 else
261 _ ->
262 shell_error("Migration is not allowed until all deprecation warnings have been resolved.")
263 end
264 end
265
266 defp do_migrate_to_db(config_file) do
267 if File.exists?(config_file) do
268 shell_info("Migrating settings from file: #{Path.expand(config_file)}")
269 truncatedb()
270
271 custom_config =
272 config_file
273 |> read_file()
274 |> elem(0)
275
276 custom_config
277 |> Keyword.keys()
278 |> Enum.each(&create(&1, custom_config))
279 else
280 shell_info("To migrate settings, you must define custom settings in #{config_file}.")
281 end
282 end
283
284 defp create(group, settings) do
285 group
286 |> Pleroma.Config.Loader.filter_group(settings)
287 |> Enum.each(fn {key, value} ->
288 {:ok, _} = ConfigDB.update_or_create(%{group: group, key: key, value: value})
289
290 shell_info("Settings for key #{key} migrated.")
291 end)
292
293 shell_info("Settings for group #{inspect(group)} migrated.")
294 end
295
296 defp migrate_from_db(opts) do
297 env = opts[:env] || Pleroma.Config.get(:env)
298
299 filename = "#{env}.exported_from_db.secret.exs"
300
301 config_path =
302 cond do
303 opts[:path] ->
304 opts[:path]
305
306 Pleroma.Config.get(:release) ->
307 :config_path
308 |> Pleroma.Config.get()
309 |> Path.dirname()
310
311 true ->
312 "config"
313 end
314 |> Path.join(filename)
315
316 with {:ok, file} <- File.open(config_path, [:write, :utf8]) do
317 write_config(file, config_path, opts)
318 shell_info("Database configuration settings have been exported to #{config_path}")
319 else
320 _ ->
321 shell_error("Impossible to save settings to this directory #{Path.dirname(config_path)}")
322 tmp_config_path = Path.join(System.tmp_dir!(), filename)
323 file = File.open!(tmp_config_path)
324
325 shell_info(
326 "Saving database configuration settings to #{tmp_config_path}. Copy it to the #{Path.dirname(config_path)} manually."
327 )
328
329 write_config(file, tmp_config_path, opts)
330 end
331 end
332
333 defp write_config(file, path, opts) do
334 IO.write(file, config_header())
335
336 ConfigDB
337 |> Repo.all()
338 |> Enum.each(&write_and_delete(&1, file, opts[:delete]))
339
340 :ok = File.close(file)
341 System.cmd("mix", ["format", path])
342 end
343
344 if Code.ensure_loaded?(Config.Reader) do
345 defp config_header, do: "import Config\r\n\r\n"
346 defp read_file(config_file), do: Config.Reader.read_imports!(config_file)
347 else
348 defp config_header, do: "use Mix.Config\r\n\r\n"
349 defp read_file(config_file), do: Mix.Config.eval!(config_file)
350 end
351
352 defp write_and_delete(config, file, delete?) do
353 config
354 |> write(file)
355 |> delete(delete?)
356 end
357
358 defp write(config, file) do
359 value = inspect(config.value, limit: :infinity)
360
361 IO.write(file, "config #{inspect(config.group)}, #{inspect(config.key)}, #{value}\r\n\r\n")
362
363 config
364 end
365
366 defp delete(config, true) do
367 {:ok, _} = Repo.delete(config)
368
369 shell_info(
370 "config #{inspect(config.group)}, #{inspect(config.key)} was deleted from the ConfigDB."
371 )
372 end
373
374 defp delete(_config, _), do: :ok
375
376 defp dump(%ConfigDB{} = config) do
377 value = inspect(config.value, limit: :infinity)
378
379 shell_info("config #{inspect(config.group)}, #{inspect(config.key)}, #{value}\r\n\r\n")
380 end
381
382 defp dump(_), do: :noop
383
384 defp dump_group(group) when is_atom(group) do
385 group
386 |> ConfigDB.get_all_by_group()
387 |> Enum.each(&dump/1)
388 end
389
390 defp group_exists?(group) do
391 group
392 |> ConfigDB.get_all_by_group()
393 |> Enum.any?()
394 end
395
396 defp key_exists?(group, key) do
397 group
398 |> ConfigDB.get_by_group_and_key(key)
399 |> is_nil
400 |> Kernel.!()
401 end
402
403 defp maybe_atomize(arg) when is_atom(arg), do: arg
404
405 defp maybe_atomize(":" <> arg), do: maybe_atomize(arg)
406
407 defp maybe_atomize(arg) when is_binary(arg) do
408 if ConfigDB.module_name?(arg) do
409 String.to_existing_atom("Elixir." <> arg)
410 else
411 String.to_atom(arg)
412 end
413 end
414
415 defp check_configdb(callback) do
416 with true <- Pleroma.Config.get([:configurable_from_database]) do
417 callback.()
418 else
419 _ ->
420 shell_error(
421 "ConfigDB not enabled. Please check the value of :configurable_from_database in your configuration."
422 )
423 end
424 end
425
426 defp delete_key(group, key) do
427 check_configdb(fn ->
428 ConfigDB.delete(%{group: group, key: key})
429 end)
430 end
431
432 defp delete_group(group) do
433 check_configdb(fn ->
434 group
435 |> ConfigDB.get_all_by_group()
436 |> Enum.each(&ConfigDB.delete/1)
437 end)
438 end
439
440 defp truncatedb do
441 Ecto.Adapters.SQL.query!(Repo, "TRUNCATE config;")
442 Ecto.Adapters.SQL.query!(Repo, "ALTER SEQUENCE config_id_seq RESTART;")
443 end
444 end