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