diff --git a/apps/efka/src/efka_agent.erl b/apps/efka/src/efka_agent.erl index 33c94e3..46ba3d7 100644 --- a/apps/efka/src/efka_agent.erl +++ b/apps/efka/src/efka_agent.erl @@ -20,7 +20,9 @@ -define(SERVER, ?MODULE). -record(state, { - + host :: string(), + port :: integer(), + socket }). %%%=================================================================== @@ -43,7 +45,13 @@ start_link() -> {ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} | {stop, Reason :: term()} | ignore). init([]) -> - {ok, #state{}}. + {ok, Props} = application:get_env(efka, tls_server), + Host = proplists:get_value(host, Props), + Port = proplists:get_value(port, Props), + + erlang:start_timer(0, self(), create_connection), + + {ok, #state{host = Host, port = Port}}. %% @private %% @doc Handling call messages @@ -73,6 +81,30 @@ handle_cast(_Request, State = #state{}) -> {noreply, NewState :: #state{}} | {noreply, NewState :: #state{}, timeout() | hibernate} | {stop, Reason :: term(), NewState :: #state{}}). +handle_info({timeout, _, create_connection}, State = #state{host = Host, port = Port}) -> + case connect(Host, Port) of + {ok, Socket} -> + {noreply, State#state{socket = Socket}}; + {error, Reason} -> + lager:debug("[efka_agent] create_connection get error: ~p", [Reason]), + retry_connect(), + {noreply, State#state{socket = undefined}} + end; + +handle_info({ssl, Socket, Data}, State = #state{socket = Socket}) -> + lager:debug("[efka_agent] socket get message: ~p", [Data]), + retry_connect(), + {noreply, State#state{socket = undefined}}; + +handle_info({ssl_error, Socket, Reason}, State = #state{socket = Socket}) -> + lager:warning("[efka_agent] socket close with reason: ~p", [Reason]), + retry_connect(), + {noreply, State#state{socket = undefined}}; +handle_info({ssl_closed, Socket}, State = #state{socket = Socket}) -> + lager:warning("[efka_agent] socket closed"), + retry_connect(), + {noreply, State#state{socket = undefined}}; + handle_info(_Info, State = #state{}) -> {noreply, State}. @@ -97,3 +129,13 @@ code_change(_OldVsn, State = #state{}, _Extra) -> %%%=================================================================== %%% Internal functions %%%=================================================================== + +retry_connect() -> + erlang:start_timer(5000, self(), create_connection). + +connect(Host, Port) when is_list(Host), is_integer(Port) -> + SslOptions = [ + {verify, verify_none}, + {active, true} + ], + ssl:connect(Host, Port, SslOptions, 5000). \ No newline at end of file diff --git a/config/sys.config b/config/sys.config index 3a14d74..2429acb 100644 --- a/config/sys.config +++ b/config/sys.config @@ -2,7 +2,7 @@ {efka, [ {root_dir, "/tmp/efka/"}, - {wss_server, [ + {tls_server, [ {host, "localhost"}, {port, 18080} ]}