1 |
|
-module(mongoose_node_num_mnesia). |
2 |
|
|
3 |
|
-export([init/0]). |
4 |
|
|
5 |
|
-record(node_num, {name :: atom(), |
6 |
|
num :: mongoose_node_num:node_num() }). |
7 |
|
|
8 |
|
init() -> |
9 |
4 |
mongoose_mnesia:create_table(node_num, |
10 |
|
[{ram_copies, [node()]}, {type, set}, |
11 |
|
{attributes, record_info(fields, node_num)}]), |
12 |
4 |
mnesia:add_table_index(node_num, num), |
13 |
4 |
register_node(node()), |
14 |
4 |
[#node_num{num = Num}] = mnesia:dirty_read(node_num, node()), |
15 |
4 |
mongoose_node_num:set_node_num(Num), |
16 |
4 |
ok. |
17 |
|
|
18 |
|
-spec register_node(atom()) -> ok. |
19 |
|
register_node(NodeName) -> |
20 |
4 |
{atomic, _} = mnesia:transaction(fun() -> |
21 |
4 |
case mnesia:read(node_num, NodeName) of |
22 |
|
[] -> |
23 |
4 |
mnesia:write(#node_num{name = NodeName, num = next_node_num()}); |
24 |
:-( |
[_] -> ok |
25 |
|
end |
26 |
|
end), |
27 |
4 |
ok. |
28 |
|
|
29 |
|
-spec next_node_num() -> mongoose_node_num:node_num(). |
30 |
|
next_node_num() -> |
31 |
4 |
max_node_num() + 1. |
32 |
|
|
33 |
|
-spec max_node_num() -> mongoose_node_num:node_num(). |
34 |
|
max_node_num() -> |
35 |
4 |
mnesia:foldl(fun(#node_num{num = Num}, Max) -> max(Num, Max) end, 0, node_num). |