Release 2.4.1
[akkoma] / restarter / lib / pleroma.ex
1 defmodule Restarter.Pleroma do
2 use GenServer
3
4 require Logger
5
6 @init_state %{need_reboot: false, rebooted: false, after_boot: false}
7
8 def start_link(_) do
9 GenServer.start_link(__MODULE__, [], name: __MODULE__)
10 end
11
12 def init(_), do: {:ok, @init_state}
13
14 def rebooted? do
15 GenServer.call(__MODULE__, :rebooted?)
16 end
17
18 def rebooted do
19 GenServer.cast(__MODULE__, :rebooted)
20 end
21
22 def need_reboot? do
23 GenServer.call(__MODULE__, :need_reboot?)
24 end
25
26 def need_reboot do
27 GenServer.cast(__MODULE__, :need_reboot)
28 end
29
30 def refresh do
31 GenServer.cast(__MODULE__, :refresh)
32 end
33
34 def restart(env, delay) do
35 GenServer.cast(__MODULE__, {:restart, env, delay})
36 end
37
38 def restart_after_boot(env) do
39 GenServer.cast(__MODULE__, {:after_boot, env})
40 end
41
42 def handle_call(:rebooted?, _from, state) do
43 {:reply, state[:rebooted], state}
44 end
45
46 def handle_call(:need_reboot?, _from, state) do
47 {:reply, state[:need_reboot], state}
48 end
49
50 def handle_cast(:rebooted, state) do
51 {:noreply, Map.put(state, :rebooted, true)}
52 end
53
54 def handle_cast(:need_reboot, %{need_reboot: true} = state), do: {:noreply, state}
55
56 def handle_cast(:need_reboot, state) do
57 {:noreply, Map.put(state, :need_reboot, true)}
58 end
59
60 def handle_cast(:refresh, _state) do
61 {:noreply, @init_state}
62 end
63
64 def handle_cast({:restart, :test, _}, state) do
65 Logger.debug("pleroma manually restarted")
66 {:noreply, Map.put(state, :need_reboot, false)}
67 end
68
69 def handle_cast({:restart, _, delay}, state) do
70 Process.sleep(delay)
71 do_restart(:pleroma)
72 {:noreply, Map.put(state, :need_reboot, false)}
73 end
74
75 def handle_cast({:after_boot, _}, %{after_boot: true} = state), do: {:noreply, state}
76
77 def handle_cast({:after_boot, :test}, state) do
78 Logger.debug("pleroma restarted after boot")
79 state = %{state | after_boot: true, rebooted: true}
80 {:noreply, state}
81 end
82
83 def handle_cast({:after_boot, _}, state) do
84 do_restart(:pleroma)
85 state = %{state | after_boot: true, rebooted: true}
86 {:noreply, state}
87 end
88
89 defp do_restart(app) do
90 :ok = Application.ensure_started(app)
91 :ok = Application.stop(app)
92 :ok = Application.start(app)
93 end
94 end