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