Created
May 21, 2014 11:47
-
-
Save redink/cf997ad5c5fb840996a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(session_manager). | |
-behaviour(gen_server). | |
%% API | |
-export([start_link/0]). | |
-export([set/1, get/1]). | |
%% gen_server callbacks | |
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, | |
terminate/2, code_change/3]). | |
-define(SERVER, ?MODULE). | |
-record(state, {}). | |
-record(user, {userid, pid}). | |
set({UserID, Pid, Node}) -> | |
mnesia:dirty_write(#user{userid = UserID, | |
pid = {Pid, Node}}). | |
get({UserID}) -> | |
mnesia:dirty_read({user, UserID}). | |
start_link() -> | |
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). | |
init([]) -> | |
mnesia:create_table(user, | |
[ | |
{ram_copies, [node()]}, | |
{attributes, record_info(fields, user)} | |
]), | |
mnesia:subscribe({table, user, simple}), | |
{ok, #state{}}. | |
handle_call(_Request, _From, State) -> | |
Reply = ok, | |
{reply, Reply, State}. | |
handle_cast(_Msg, State) -> | |
{noreply, State}. | |
handle_info({mnesia_table_event, {write, #user{pid = {_, Node}}, _}}, State) -> | |
erlang:monitor_node(Node, true), | |
{noreply, State}; | |
handle_info({nodedown, Node}, State) -> | |
F = fun() -> | |
ES = mnesia:select(user, | |
[{#user{userid = '_',pid = {'_','$1'}}, | |
[{'==','$1',Node}], | |
['$_']}]), | |
[mnesia:delete({user, U1#user.userid}) || U1 <- ES] | |
end, | |
mnesia:async_dirty(F), | |
{noreply, State}; | |
handle_info(_Info, State) -> | |
{noreply, State}. | |
terminate(_Reason, _State) -> | |
ok. | |
code_change(_OldVsn, State, _Extra) -> | |
{ok, State}. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment