]> review.fuel-infra Code Review - packages/trusty/rabbitmq-server.git/blob
816b126ad2a64a1651ff71f7953efb69e764b00d
[packages/trusty/rabbitmq-server.git] /
1 %% Copyright (c) 2011-2012 Basho Technologies, Inc.  All Rights Reserved.
2 %%
3 %% This file is provided to you under the Apache License,
4 %% Version 2.0 (the "License"); you may not use this file
5 %% except in compliance with the License.  You may obtain
6 %% a copy of the License at
7 %%
8 %%   http://www.apache.org/licenses/LICENSE-2.0
9 %%
10 %% Unless required by applicable law or agreed to in writing,
11 %% software distributed under the License is distributed on an
12 %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
13 %% KIND, either express or implied.  See the License for the
14 %% specific language governing permissions and limitations
15 %% under the License.
16
17 %% @doc A process that does a gen_event:add_sup_handler and attempts to re-add
18 %% event handlers when they exit.
19
20 %% @private
21
22 -module(webmachine_logger_watcher).
23
24 -behaviour(gen_server).
25
26 -ifdef(TEST).
27 -include_lib("eunit/include/eunit.hrl").
28 -endif.
29
30 %% callbacks
31 -export([init/1,
32          handle_call/3,
33          handle_cast/2,
34          handle_info/2,
35          terminate/2,
36          code_change/3]).
37
38 -export([start_link/3,
39          start/3]).
40
41 -record(state, {module, config, event}).
42
43 start_link(Event, Module, Config) ->
44     gen_server:start_link(?MODULE, [Event, Module, Config], []).
45
46 start(Event, Module, Config) ->
47     gen_server:start(?MODULE, [Event, Module, Config], []).
48
49 init([Event, Module, Config]) ->
50     install_handler(Event, Module, Config),
51     {ok, #state{event=Event, module=Module, config=Config}}.
52
53 handle_call(_Call, _From, State) ->
54     {reply, ok, State}.
55
56 handle_cast(_Request, State) ->
57     {noreply, State}.
58
59 handle_info({gen_event_EXIT, Module, normal}, #state{module=Module} = State) ->
60     {stop, normal, State};
61 handle_info({gen_event_EXIT, Module, shutdown}, #state{module=Module} = State) ->
62     {stop, normal, State};
63 handle_info({gen_event_EXIT, Module, _Reason}, #state{module=Module,
64         config=Config, event=Event} = State) ->
65     install_handler(Event, Module, Config),
66     {noreply, State};
67 handle_info(reinstall_handler, #state{module=Module, config=Config, event=Event} = State) ->
68     install_handler(Event, Module, Config),
69     {noreply, State};
70 handle_info(_Info, State) ->
71     {noreply, State}.
72
73 terminate(_Reason, _State) ->
74     ok.
75
76 code_change(_OldVsn, State, _Extra) ->
77     {ok, State}.
78
79 %% internal
80
81 install_handler(Event, Module, Config) ->
82     case gen_event:add_sup_handler(Event, Module, Config) of
83         ok ->
84             ok;
85         _Error ->
86             erlang:send_after(5000, self(), reinstall_handler),
87             ok
88     end.