Having Difficulty Adding a Node to mnesia

The following code might help you to set up Mnesia cluster,

start_phase(init_mnesia, _StartType, []) ->
    case nodes() of
        [] ->
            ok = setup_mnesia_initial_node();
        _ ->
            ok = join_mnesia_cluster()
    end.

setup_mnesia_initial_node() ->
    _ = mnesia:start(),
    _ = mnesia:create_schema([node()]),
    _ = mnesia:change_table_copy_type(schema, [node()], disc_copies),
    ok = create_table([node()]),
    ok = mnesia:wait_for_tables([?TABLE_NAME], 5000),
    ok.

join_mnesia_cluster() ->
    _ = mnesia:stop(),
    ok = mnesia:delete_schema([node()]),
    _ = mnesia:start(),
    {ok,[_]} = rpc:call(InitialNode, mnesia, change_config, [extra_db_nodes, [node()]]),
    {atomic,ok} = mnesia:change_table_copy_type(schema, node(), disc_copies),
    {atomic,ok} = mnesia:add_table_copy(?TABLE_NAME, node(), disc_copies),
    ok = mnesia:wait_for_tables([?TABLE_NAME], 5000),
    ok.
    
create_table(Nodes) ->
    TableOpts = [{attributes, record_info(fields, ?TABLE_NAME)},
                 {disc_copies, Nodes},
                 {record_name, ?TABLE_NAME},
                 {type, ordered_set}],

    case mnesia:create_table(?TABLE_NAME, TableOpts) of
        {atomic, ok} -> ok;
        {aborted, {already_exists, ?TABLE_NAME}} -> ok;
        {aborted, Reason} -> {error, Reason}
    end.
1 Like