aboutsummaryrefslogtreecommitdiff
path: root/lib/mix/tasks/pleroma/config.ex
blob: 41b2871637338ea1221645119ae1cf78a5da3f43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# Pleroma: A lightweight social networking server
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Mix.Tasks.Pleroma.Config do
  use Mix.Task

  import Ecto.Query
  import Mix.Pleroma

  alias Pleroma.ConfigDB
  alias Pleroma.Repo

  @shortdoc "Manages the location of the config"
  @moduledoc File.read!("docs/administration/CLI_tasks/config.md")

  def run(["migrate_to_db" | options]) do
    check_configdb(fn ->
      start_pleroma()

      {opts, _} = OptionParser.parse!(options, strict: [config: :string])

      migrate_to_db(opts)
    end)
  end

  def run(["migrate_from_db" | options]) do
    check_configdb(fn ->
      start_pleroma()

      {opts, _} =
        OptionParser.parse!(options,
          strict: [env: :string, delete: :boolean, path: :string],
          aliases: [d: :delete]
        )

      migrate_from_db(opts)
    end)
  end

  def run(["dump"]) do
    check_configdb(fn ->
      start_pleroma()

      settings =
        ConfigDB
        |> Repo.all()
        |> Enum.sort()

      unless settings == [] do
        shell_info("#{Pleroma.Config.Loader.config_header()}")

        Enum.each(settings, &dump(&1))
      else
        shell_error("No settings in ConfigDB.")
      end
    end)
  end

  def run(["dump", group, key]) do
    check_configdb(fn ->
      start_pleroma()

      group = maybe_atomize(group)
      key = maybe_atomize(key)

      group
      |> ConfigDB.get_by_group_and_key(key)
      |> dump()
    end)
  end

  def run(["dump", group]) do
    check_configdb(fn ->
      start_pleroma()

      group
      |> maybe_atomize()
      |> ConfigDB.get_all_by_group()
      |> Enum.each(&dump/1)
    end)
  end

  def run(["groups"]) do
    check_configdb(fn ->
      start_pleroma()

      groups =
        ConfigDB
        |> distinct([c], true)
        |> select([c], c.group)
        |> Repo.all()

      if length(groups) > 0 do
        shell_info("The following configuration groups are set in ConfigDB:\r\n")
        groups |> Enum.each(fn x -> shell_info("-  #{x}") end)
        shell_info("\r\n")
      end
    end)
  end

  def run(["reset" | opts]) do
    check_configdb(fn ->
      start_pleroma()

      {opts, []} = OptionParser.parse!(opts, strict: [force: :boolean])

      shell_info("The following settings will be permanently removed:")

      ConfigDB
      |> Repo.all()
      |> Enum.sort()
      |> Enum.each(&dump(&1))

      shell_error("\nTHIS CANNOT BE UNDONE!")

      if opts[:force] or shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
        Pleroma.Config.Versioning.reset()

        shell_info("The ConfigDB settings have been removed from the database.")
      else
        shell_error("No changes made.")
      end
    end)
  end

  def run(["delete", group]), do: delete(group, force: false)
  def run(["delete", "--force", group]), do: delete(group, force: true)

  def run(["delete", group, key]), do: delete(group, key, force: false)
  def run(["delete", "--force", group, key]), do: delete(group, key, force: true)

  def run(["rollback" | options]) do
    check_configdb(fn ->
      start_pleroma()
      {opts, _} = OptionParser.parse!(options, strict: [steps: :integer], aliases: [s: :steps])

      do_rollback(opts)
    end)
  end

  defp delete(group, opts) do
    start_pleroma()

    group = maybe_atomize(group)

    configs = ConfigDB.get_all_by_group(group)

    if configs != [] do
      shell_info("The following settings will be removed from ConfigDB:\n")
      Enum.each(configs, &dump/1)

      if opts[:force] or shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
        Enum.each(configs, fn config ->
          Pleroma.Config.Versioning.new_version(%{
            group: config.group,
            key: config.key,
            delete: true
          })
        end)
      else
        shell_error("No changes made.")
      end
    else
      shell_error("No settings in ConfigDB for #{inspect(group)}. Aborting.")
    end
  end

  defp delete(group, key, opts) do
    start_pleroma()

    group = maybe_atomize(group)
    key = maybe_atomize(key)

    with %ConfigDB{} = config <- ConfigDB.get_by_group_and_key(group, key) do
      shell_info("The following settings will be removed from ConfigDB:\n")

      dump(config)

      if opts[:force] or shell_prompt("Are you sure you want to continue?", "n") in ~w(Yn Y y) do
        Pleroma.Config.Versioning.new_version(%{
          group: config.group,
          key: config.key,
          delete: true
        })
      else
        shell_error("No changes made.")
      end
    else
      _ ->
        shell_error("No settings in ConfigDB for #{inspect(group)}, #{inspect(key)}. Aborting.")
    end
  end

  defp do_rollback(opts) do
    steps = opts[:steps] || 1

    case Pleroma.Config.Versioning.rollback(steps) do
      {:ok, _} ->
        shell_info("Success rollback")

      {:error, :no_current_version} ->
        shell_error("No version to rollback")

      {:error, :rollback_not_possible} ->
        shell_error("Rollback not possible. Incorrect steps value.")

      {:error, _, _, _} ->
        shell_error("Problem with backup. Rollback not possible.")

      error ->
        shell_error("error occuried: #{inspect(error)}")
    end
  end

  defp migrate_to_db(opts) do
    with :ok <- Pleroma.Config.DeprecationWarnings.warn() do
      config_file = opts[:config] || Pleroma.Application.config_path()

      if File.exists?(config_file) do
        do_migrate_to_db(config_file)
      else
        shell_info("To migrate settings, you must define custom settings in #{config_file}.")
      end
    else
      _ ->
        shell_error("Migration is not allowed until all deprecation warnings have been resolved.")
    end
  end

  defp do_migrate_to_db(config_file) do
    shell_info("Migrating settings from file: #{Path.expand(config_file)}")
    {:ok, _} = Pleroma.Config.Versioning.migrate(config_file)
    shell_info("Settings migrated.")
  end

  defp migrate_from_db(opts) do
    env = opts[:env] || Pleroma.Config.get(:env)

    filename = "#{env}.exported_from_db.secret.exs"

    config_path =
      cond do
        opts[:path] ->
          opts[:path]

        Pleroma.Config.get(:release) ->
          :config_path
          |> Pleroma.Config.get()
          |> Path.dirname()

        true ->
          "config"
      end
      |> Path.join(filename)

    with {:ok, file} <- File.open(config_path, [:write, :utf8]) do
      write_config(file, config_path, opts)
      shell_info("Database configuration settings have been exported to #{config_path}")
    else
      _ ->
        shell_error("Impossible to save settings to this directory #{Path.dirname(config_path)}")
        tmp_config_path = Path.join(System.tmp_dir!(), filename)
        file = File.open!(tmp_config_path)

        shell_info(
          "Saving database configuration settings to #{tmp_config_path}. Copy it to the #{
            Path.dirname(config_path)
          } manually."
        )

        write_config(file, tmp_config_path, opts)
    end
  end

  defp write_config(file, path, opts) do
    IO.write(file, Pleroma.Config.Loader.config_header())

    changes =
      ConfigDB
      |> Repo.all()
      |> Enum.reduce([], fn %{group: group} = config, acc ->
        group_str = inspect(group)
        value = inspect(config.value, limit: :infinity)

        msg =
          if group in ConfigDB.groups_without_keys() do
            IO.write(file, "config #{group_str}, #{value}\r\n\r\n")
            "config #{group_str} was deleted."
          else
            key_str = inspect(config.key)
            IO.write(file, "config #{group_str}, #{key_str}, #{value}\r\n\r\n")
            "config #{group_str}, #{key_str} was deleted."
          end

        if opts[:delete] do
          shell_info(msg)

          change =
            config
            |> Map.take([:group, :key])
            |> Map.put(:delete, true)

          [change | acc]
        else
          acc
        end
      end)

    if Keyword.get(opts, :delete, false) and changes != [] do
      Pleroma.Config.Versioning.new_version(changes)
    end

    :ok = File.close(file)
    System.cmd("mix", ["format", path])
  end

  defp dump(%ConfigDB{} = config) do
    value = inspect(config.value, limit: :infinity)

    shell_info("config #{inspect(config.group)}, #{inspect(config.key)}, #{value}\r\n\r\n")
  end

  defp dump(_), do: :noop

  defp maybe_atomize(arg) when is_atom(arg), do: arg

  defp maybe_atomize(":" <> arg), do: maybe_atomize(arg)

  defp maybe_atomize(arg) when is_binary(arg) do
    if Pleroma.Config.Converter.module_name?(arg) do
      String.to_existing_atom("Elixir." <> arg)
    else
      String.to_atom(arg)
    end
  end

  defp check_configdb(callback) do
    with true <- Pleroma.Config.get([:configurable_from_database]) do
      callback.()
    else
      _ ->
        shell_error(
          "ConfigDB not enabled. Please check the value of :configurable_from_database in your configuration."
        )
    end
  end
end