Merge branch 'develop' into issue/1975
[akkoma] / lib / pleroma / application.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Application do
6 use Application
7
8 import Cachex.Spec
9
10 alias Pleroma.Config
11
12 require Logger
13
14 @name Mix.Project.config()[:name]
15 @version Mix.Project.config()[:version]
16 @repository Mix.Project.config()[:source_url]
17 @env Mix.env()
18
19 def name, do: @name
20 def version, do: @version
21 def named_version, do: @name <> " " <> @version
22 def repository, do: @repository
23
24 def user_agent do
25 if Process.whereis(Pleroma.Web.Endpoint) do
26 case Config.get([:http, :user_agent], :default) do
27 :default ->
28 info = "#{Pleroma.Web.base_url()} <#{Config.get([:instance, :email], "")}>"
29 named_version() <> "; " <> info
30
31 custom ->
32 custom
33 end
34 else
35 # fallback, if endpoint is not started yet
36 "Pleroma Data Loader"
37 end
38 end
39
40 # See http://elixir-lang.org/docs/stable/elixir/Application.html
41 # for more information on OTP Applications
42 def start(_type, _args) do
43 # Scrubbers are compiled at runtime and therefore will cause a conflict
44 # every time the application is restarted, so we disable module
45 # conflicts at runtime
46 Code.compiler_options(ignore_module_conflict: true)
47 # Disable warnings_as_errors at runtime, it breaks Phoenix live reload
48 # due to protocol consolidation warnings
49 Code.compiler_options(warnings_as_errors: false)
50 Pleroma.Telemetry.Logger.attach()
51 Config.Holder.save_default()
52 Pleroma.HTML.compile_scrubbers()
53 Pleroma.Config.Oban.warn()
54 Config.DeprecationWarnings.warn()
55 Pleroma.Plugs.HTTPSecurityPlug.warn_if_disabled()
56 Pleroma.ApplicationRequirements.verify!()
57 setup_instrumenters()
58 load_custom_modules()
59 check_system_commands()
60 Pleroma.Docs.JSON.compile()
61
62 adapter = Application.get_env(:tesla, :adapter)
63
64 if adapter == Tesla.Adapter.Gun do
65 if version = Pleroma.OTPVersion.version() do
66 [major, minor] =
67 version
68 |> String.split(".")
69 |> Enum.map(&String.to_integer/1)
70 |> Enum.take(2)
71
72 if (major == 22 and minor < 2) or major < 22 do
73 raise "
74 !!!OTP VERSION WARNING!!!
75 You are using gun adapter with OTP version #{version}, which doesn't support correct handling of unordered certificates chains. Please update your Erlang/OTP to at least 22.2.
76 "
77 end
78 else
79 raise "
80 !!!OTP VERSION WARNING!!!
81 To support correct handling of unordered certificates chains - OTP version must be > 22.2.
82 "
83 end
84 end
85
86 # Define workers and child supervisors to be supervised
87 children =
88 [
89 Pleroma.Repo,
90 Config.TransferTask,
91 Pleroma.Emoji,
92 Pleroma.Plugs.RateLimiter.Supervisor
93 ] ++
94 cachex_children() ++
95 http_children(adapter, @env) ++
96 [
97 Pleroma.Stats,
98 Pleroma.JobQueueMonitor,
99 {Oban, Config.get(Oban)}
100 ] ++
101 task_children(@env) ++
102 dont_run_in_test(@env) ++
103 chat_child(@env, chat_enabled?()) ++
104 [
105 Pleroma.Web.Endpoint,
106 Pleroma.Gopher.Server
107 ]
108
109 # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
110 # for other strategies and supported options
111 opts = [strategy: :one_for_one, name: Pleroma.Supervisor]
112 Supervisor.start_link(children, opts)
113 end
114
115 def load_custom_modules do
116 dir = Config.get([:modules, :runtime_dir])
117
118 if dir && File.exists?(dir) do
119 dir
120 |> Pleroma.Utils.compile_dir()
121 |> case do
122 {:error, _errors, _warnings} ->
123 raise "Invalid custom modules"
124
125 {:ok, modules, _warnings} ->
126 if @env != :test do
127 Enum.each(modules, fn mod ->
128 Logger.info("Custom module loaded: #{inspect(mod)}")
129 end)
130 end
131
132 :ok
133 end
134 end
135 end
136
137 defp setup_instrumenters do
138 require Prometheus.Registry
139
140 if Application.get_env(:prometheus, Pleroma.Repo.Instrumenter) do
141 :ok =
142 :telemetry.attach(
143 "prometheus-ecto",
144 [:pleroma, :repo, :query],
145 &Pleroma.Repo.Instrumenter.handle_event/4,
146 %{}
147 )
148
149 Pleroma.Repo.Instrumenter.setup()
150 end
151
152 Pleroma.Web.Endpoint.MetricsExporter.setup()
153 Pleroma.Web.Endpoint.PipelineInstrumenter.setup()
154 Pleroma.Web.Endpoint.Instrumenter.setup()
155 end
156
157 defp cachex_children do
158 [
159 build_cachex("used_captcha", ttl_interval: seconds_valid_interval()),
160 build_cachex("user", default_ttl: 25_000, ttl_interval: 1000, limit: 2500),
161 build_cachex("object", default_ttl: 25_000, ttl_interval: 1000, limit: 2500),
162 build_cachex("rich_media", default_ttl: :timer.minutes(120), limit: 5000),
163 build_cachex("scrubber", limit: 2500),
164 build_cachex("idempotency", expiration: idempotency_expiration(), limit: 2500),
165 build_cachex("web_resp", limit: 2500),
166 build_cachex("emoji_packs", expiration: emoji_packs_expiration(), limit: 10),
167 build_cachex("failed_proxy_url", limit: 2500),
168 build_cachex("banned_urls", default_ttl: :timer.hours(24 * 30), limit: 5_000)
169 ]
170 end
171
172 defp emoji_packs_expiration,
173 do: expiration(default: :timer.seconds(5 * 60), interval: :timer.seconds(60))
174
175 defp idempotency_expiration,
176 do: expiration(default: :timer.seconds(6 * 60 * 60), interval: :timer.seconds(60))
177
178 defp seconds_valid_interval,
179 do: :timer.seconds(Config.get!([Pleroma.Captcha, :seconds_valid]))
180
181 @spec build_cachex(String.t(), keyword()) :: map()
182 def build_cachex(type, opts),
183 do: %{
184 id: String.to_atom("cachex_" <> type),
185 start: {Cachex, :start_link, [String.to_atom(type <> "_cache"), opts]},
186 type: :worker
187 }
188
189 defp chat_enabled?, do: Config.get([:chat, :enabled])
190
191 defp dont_run_in_test(env) when env in [:test, :benchmark], do: []
192
193 defp dont_run_in_test(_) do
194 [
195 {Registry,
196 [
197 name: Pleroma.Web.Streamer.registry(),
198 keys: :duplicate,
199 partitions: System.schedulers_online()
200 ]},
201 Pleroma.Web.FedSockets.Supervisor
202 ]
203 end
204
205 defp chat_child(_env, true) do
206 [Pleroma.Web.ChatChannel.ChatChannelState]
207 end
208
209 defp chat_child(_, _), do: []
210
211 defp task_children(:test) do
212 [
213 %{
214 id: :web_push_init,
215 start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
216 restart: :temporary
217 }
218 ]
219 end
220
221 defp task_children(_) do
222 [
223 %{
224 id: :web_push_init,
225 start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
226 restart: :temporary
227 },
228 %{
229 id: :internal_fetch_init,
230 start: {Task, :start_link, [&Pleroma.Web.ActivityPub.InternalFetchActor.init/0]},
231 restart: :temporary
232 }
233 ]
234 end
235
236 # start hackney and gun pools in tests
237 defp http_children(_, :test) do
238 http_children(Tesla.Adapter.Hackney, nil) ++ http_children(Tesla.Adapter.Gun, nil)
239 end
240
241 defp http_children(Tesla.Adapter.Hackney, _) do
242 pools = [:federation, :media]
243
244 pools =
245 if Config.get([Pleroma.Upload, :proxy_remote]) do
246 [:upload | pools]
247 else
248 pools
249 end
250
251 for pool <- pools do
252 options = Config.get([:hackney_pools, pool])
253 :hackney_pool.child_spec(pool, options)
254 end
255 end
256
257 defp http_children(Tesla.Adapter.Gun, _) do
258 Pleroma.Gun.ConnectionPool.children() ++
259 [{Task, &Pleroma.HTTP.AdapterHelper.Gun.limiter_setup/0}]
260 end
261
262 defp http_children(_, _), do: []
263
264 defp check_system_commands do
265 filters = Config.get([Pleroma.Upload, :filters])
266
267 check_filter = fn filter, command_required ->
268 with true <- filter in filters,
269 false <- Pleroma.Utils.command_available?(command_required) do
270 Logger.error(
271 "#{filter} is specified in list of Pleroma.Upload filters, but the #{command_required} command is not found"
272 )
273 end
274 end
275
276 check_filter.(Pleroma.Upload.Filters.Exiftool, "exiftool")
277 check_filter.(Pleroma.Upload.Filters.Mogrify, "mogrify")
278 check_filter.(Pleroma.Upload.Filters.Mogrifun, "mogrify")
279 end
280 end