Skip to main content

Replicated Mnesia

I'm still working on my expiring records module in Erlang (see here and here for my previous posts on this).
Previously, I had started using Mnesia, but only a RAM based table. I've now switched it over to a replicated disc based table. That was easy enough, but it took a while to figure out how to do, nonetheless.
I had assumed that simply adding
    {disc_copies, [node()]}
to the arguments to mnesia:create_table would be enough. This resulted in an error:
After some head-scratching and lots of Googling I realized that I was missing a call to mnesia:create_schema to allow it to create disc based tables.
My tests for this module are done with common_test so I set up a per suite initialization function like this:
init_per_suite(Config) ->

end_per_suite(Config) ->
With this change, my tests now pass, with a disc based table. Now I want to have the table replicated across multiple nodes.
Let's first set up a test environment. Using rebar3 shell is convenient as it automatically builds the module upon entering the Erlang shell and allows me to call the module functions from the command line.
Snorris-MBP-2:erl-expiring-records snorri$ rebar3 shell
===> Verifying dependencies...
===> Compiling expiring_records
Erlang/OTP 20 [erts-9.1.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:0] [hipe] [kernel-poll:false] [dtrace]

Eshell V9.1.1  (abort with ^G)
1> mnesia:create_schema([node()]).
2> mnesia:start().
3> expiring_records:start().
4> expiring_records:store("bingo", "bongo", erlang:system_time(seconds)+300).
5> expiring_records:fetch("bingo").
Note that I have to manually initialize Mnesia as I'm not running the test framework. A proper application will have to do this setup somewhere once at startup - it doesn't make sense to do it in the module.
Anyway, this is still just one node. Let's shut this one down and start two new ones - this time I start it up with an extra argument to give it a name.
Snorris-MBP-2:erl-expiring-records snorri$ rebar3 shell --sname=bilbo
===> Verifying dependencies...
===> Compiling expiring_records
Erlang/OTP 20 [erts-9.1.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:0] [hipe] [kernel-poll:false] [dtrace]

Eshell V9.1.1  (abort with ^G)
And the second one:
Snorris-MacBook-Pro-2:erl-expiring-records snorri$ rebar3 shell --sname=gandalf
===> Verifying dependencies...
===> Compiling expiring_records
Erlang/OTP 20 [erts-9.1.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:0] [hipe] [kernel-poll:false] [dtrace]

Eshell V9.1.1  (abort with ^G)
Note that the prompt changes to show you the name of the node - very convenient. In one of the nodes, I have to tell Mnesia to create a schema that includes both nodes:
(gandalf@Snorris-MBP-2)1> mnesia:create_schema(['bilbo@Snorris-MBP-2', 'gandalf@Snorris-MBP-2']).
Note that this has to happen before the mnesia:start() call, and that both nodes have to be up and running. This isn't really clear in the Mnesia documentation. I really recommend a better overview of Mnesia - use the official documentation for a detailed reference.
That change to the create_table arguments also needs tweaking - I want the table to have a disc copy on all nodes:
prepare_table() ->
    DbNodes = mnesia:system_info(db_nodes),
    case catch mnesia:table_info(expiring_records, attributes) of
        {'EXIT', _} ->
            %% Table does not exist - create it
            {atomic, ok} = mnesia:create_table(
                expiring_records, [
                    {attributes, record_info(fields, record)},
                    {record_name, record},
                    {disc_copies, DbNodes}
        _Attributes ->
    mnesia:wait_for_tables([expiring_records], infinite).
Anyway, let's fire up Mnesia on both nodes, as well as the module:
(gandalf@Snorris-MBP-2)2> mnesia:start().
(gandalf@Snorris-MBP-2)3> expiring_records:start().


(bilbo@Snorris-MBP-2)1> mnesia:start().
(bilbo@Snorris-MBP-2)2> expiring_records:start().
Now I should be able to store a record in one node and fetch it on the other:
(bilbo@Snorris-MBP-2)3> expiring_records:store("bingo", "bongo", erlang:system_time(seconds)+60).  


(gandalf@Snorris-MBP-2)4> expiring_records:fetch("bingo").
This feels like a big victory! I know I haven't really done much here myself - I'm really just wrapping basic functionality from Erlang, the OTP and Mnesia, but these are really powerful tools.
Alright, that's all for now - next, I'll look at trimming expired values. That'll give me a chance to do a simple query in Mnesia.

Popular posts from this blog

Mnesia queries

I've added search and trim to my expiring records module in Erlang. This started out as an in-memory key/value store, that I then migrated over to using Mnesia and eventually to a replicated Mnesia table. The fetch/1 function is already doing a simple query, with match_object. Result=mnesia:match_object(expiring_records, #record{key=Key, value='_', expires_at='_'}, read) The three parameters there are the name of the table - expiring_records, the matching pattern and the lock type (read lock). The fetch/1 function looks up the key as it was added to the table with store/3. If the key is a tuple, we can also do a partial match: Result=mnesia:match_object(expiring_records, #record{key= {'_', "bongo"}, value='_', expires_at='_'}, read) I've added a search/1 function the module that takes in a matching pattern and returns a list of items where the key matches the pattern. Here's the test for the search/1 function: search_partial_…

Waiting for an answer

I want to describe my first iteration of exsim, the core server for the large scale simulation I described in my last blog post. A Listener module opens a socket for listening to incoming connections. Once a connection is made, a process is spawned for handling the login and the listener continues listening for new connections. Once logged in, a Player is created, and a Solarsystem is started (if it hasn't already). The solar system also starts a PhysicsProxy, and the player starts a Ship. These are all GenServer processes. The source for this is up on GitHub: Player The player takes ownership of the TCP connection and handles communication with the game client (or bot). Incoming messages are parsed in handle_info/2 and handled by the player or routed to the ship, as appropriate. The player creates the ship in its init/1 function. The state for the player holds the ship and the name of the player. Ship The ship holds the state of the ship - …