1 |
|
-module(mongoose_collector). |
2 |
|
|
3 |
|
-include("mongoose_logger.hrl"). |
4 |
|
|
5 |
|
%% gen_server callbacks |
6 |
|
-behaviour(gen_server). |
7 |
|
-export([start_link/2, init/1, handle_call/3, handle_cast/2, handle_info/2]). |
8 |
|
|
9 |
|
-ignore_xref([start_link/2]). |
10 |
|
|
11 |
|
-record(watchdog, { |
12 |
|
host_type :: mongooseim:host_type(), |
13 |
|
action :: fun((mongooseim:host_type(), map()) -> term()), |
14 |
|
opts :: term(), |
15 |
|
interval :: pos_integer(), |
16 |
|
timer_ref :: undefined | reference() |
17 |
|
}). |
18 |
|
|
19 |
|
start_link(Name, Opts) -> |
20 |
3 |
gen_server:start_link({local, Name}, ?MODULE, Opts, []). |
21 |
|
|
22 |
|
init(#{host_type := HostType, |
23 |
|
action := Fun, |
24 |
|
opts := Opts, |
25 |
|
interval := Interval}) when is_function(Fun, 2) -> |
26 |
3 |
State = #watchdog{host_type = HostType, |
27 |
|
action = Fun, |
28 |
|
opts = Opts, |
29 |
|
interval = Interval, |
30 |
|
timer_ref = undefined}, |
31 |
3 |
{ok, schedule_check(State)}. |
32 |
|
|
33 |
|
handle_call(Msg, From, State) -> |
34 |
:-( |
?UNEXPECTED_CALL(Msg, From), |
35 |
:-( |
{reply, ok, State}. |
36 |
|
|
37 |
|
handle_cast(Msg, State) -> |
38 |
:-( |
?UNEXPECTED_CAST(Msg), |
39 |
:-( |
{noreply, State}. |
40 |
|
|
41 |
|
handle_info({timeout, Ref, run_action}, |
42 |
|
#watchdog{timer_ref = Ref} = State) -> |
43 |
1011 |
run_action(State), |
44 |
1011 |
{noreply, schedule_check(State)}; |
45 |
|
handle_info(Info, State) -> |
46 |
:-( |
?UNEXPECTED_INFO(Info), |
47 |
:-( |
{noreply, State}. |
48 |
|
|
49 |
|
schedule_check(State = #watchdog{interval = Interval}) -> |
50 |
1014 |
State#watchdog{timer_ref = erlang:start_timer(Interval, self(), run_action)}. |
51 |
|
|
52 |
|
run_action(#watchdog{host_type = HostType, action = Fun, opts = Opts}) -> |
53 |
1011 |
Fun(HostType, Opts). |