summaryrefslogtreecommitdiff
path: root/p11p-daemon/src/p11p_remote_manager.erl
blob: d2bbd1170ad549e2b995142eb44f8358f5e7cb1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
%% A remote manager is a gen_server for coordination of remotes for
%% all tokens.

%% Spawn one remote per configured p11p module per configured virtual
%% token. Provide a lookup service for servers that need a remote to
%% send a request to, by keeping track of which module is current for
%% a given vtoken.

-module(p11p_remote_manager).

-behaviour(gen_server).

%% API.
-export([start_link/0]).
-export([remote_for_token/1, client_change/2]).	% For servers.
-export([server_change/2]).			% For remotes.

%% Genserver callbacks.
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
         code_change/3]).

%% Records and types.
-record(remote, {
	  tokname :: string(),
	  servid :: atom(),
	  modpath :: string(),			% FIXME: filename
	  pid = undefined :: pid() | undefined
	 }).

-record(token, {
	  remotes :: [#remote{}],	      % Active remote in hd().
	  replay = <<>> :: binary()
	 }).

-record(state, {
	  tokens :: #{string() => #token{}}
	 }).

%% API implementation.
-spec start_link() -> {ok, pid()} | {error, term()}.
start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

-spec remote_for_token(string()) -> pid().
remote_for_token(TokName) ->
    gen_server:call(?MODULE, {remote_for_token, TokName}).
client_change(Change, Args) ->
    gen_server:call(?MODULE, {client_change, Change, Args}).

server_change(Change, Args) ->
    gen_server:call(?MODULE, {server_change, Change, Args}).

%% Genserver callbacks.
init([]) ->
    {ok, #state{tokens = init_tokens(p11p_config:tokens())}}.

handle_call({remote_for_token, TokName}, _From, #state{tokens = Tokens} = State) ->
    #{TokName := Token} = Tokens,
    Remotes = Token#token.remotes,
    #remote{tokname = TokName, servid = ServId, modpath = ModPath, pid = Pid} = Remote = hd(Remotes),
    case Pid of
	undefined ->
	    {ok, NewPid} = p11p_remote:start_link(ServId, TokName, ModPath),
	    NewRemote = Remote#remote{pid = NewPid},
	    NewToken = Token#token{remotes = [NewRemote | tl(Remotes)]},
	    NewState = State#state{tokens = Tokens#{TokName := NewToken}},
	    {reply, NewPid, NewState};
	_ ->
	    {reply, Pid, State}
    end;
handle_call({server_change, timeout, [TokName]}, _From, #state{tokens = Tokens} = State) ->
    lager:debug("~p: ~s: timed out", [self(), TokName]),
    %% TODO: do some code dedup with remote_for_token?
    #{TokName := Token} = Tokens,
    Remotes = Token#token.remotes,
    Remote = hd(Remotes),
    NewRemote = Remote#remote{pid = undefined},
    NewToken = Token#token{remotes = tl(Remotes) ++ [NewRemote]},
    NewState = State#state{tokens = Tokens#{TokName := NewToken}},
    lager:debug("~p: ~s: updated token: ~p", [self(), TokName, NewToken]),
    {reply, ok, NewState};
handle_call({client_change, client_gone, [TokName, Pid]}, From, #state{tokens = Tokens} = State) ->
    lager:debug("~p: killing off remote ~p on request from ~p", [self(), Pid, From]),
    gen_server:stop(Pid),
    #{TokName := Token} = Tokens,
    Remotes = Token#token.remotes,
    NewRemotes = lists:map(fun(E) -> % TODO: any risk of losing list order?
				   case E#remote.pid of
				       Pid -> E#remote{pid = undefined};
				       _ -> E
				   end end, Remotes),
    NewToken = Token#token{remotes = NewRemotes},
    NewState = State#state{tokens = Tokens#{TokName := NewToken}},
    {reply, ok, NewState};
handle_call(Call, _From, State) ->
    lager:debug("Unhandled call: ~p~n", [Call]),
    {reply, unhandled, State}.

handle_cast(Cast, State) ->
    lager:debug("Unhandled cast: ~p~n", [Cast]),
    {noreply, State}.

handle_info({Port, {exit_status, Status}}, State) ->
    lager:info("~p: process exited with ~p", [Port, Status]),
    {stop, child_exit, State};
handle_info(Info, State) ->
    lager:debug("~p: Unhandled info: ~p~n", [self(), Info]),
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVersion, State, _Extra) ->
    {ok, State}.

%% Private functions
-spec init_tokens([p11p_config:token()]) -> #{string() => #token{}}.
init_tokens(ConfTokens) ->
    init_tokens(ConfTokens, #{}).
init_tokens([], Acc)->
    lager:debug("~p: created tokens from config: ~p", [self(), Acc]),
    Acc;
init_tokens([H|T], Acc)->
    TokName = p11p_config:nameof(H),
    init_tokens(T, Acc#{TokName => new_token(TokName, H)}).

new_token(TokName, ConfToken) ->
    #token{remotes = remotes(TokName, p11p_config:modules_for_token(p11p_config:nameof(ConfToken)))}.

remotes(TokName, ConfModules) ->
    remotes(TokName, ConfModules, []).
remotes(_, [], Acc) ->
    Acc;
remotes(TokName, [H|T], Acc) ->
    ModName = p11p_config:nameof(H),
    ServName = "p11p_remote:" ++ TokName ++ ":" ++ ModName,
    ModPath = p11p_config:module_path(H),
    remotes(TokName, T, [#remote{
			    tokname = TokName,
			    servid = list_to_atom(ServName),
			    modpath = ModPath,
			    pid = undefined
			   } | Acc]).