mnesia
Clause's mnesia application exports the OTP 29 interface of mnesia (mnesia-4.27) and
mnesia_frag_hash. In detail:
- Tables and dirty access:
- starting and stopping, and the configuration parameters;
- the RAM schema:
create_table/2with OTP's checks,delete_table/1,table_info/2,system_info/1,schema/0,1,wait_for_tables/2anderror_description/1; - dirty access to
set,ordered_setandbagtables; - indexes.
- Transactions:
- transactions, nested or not, with OTP's results, abort terms and restarts;
- locks and their queue;
- activities and access modules;
- schema changes as schema transactions.
- Schema changes: the other schema changes:
clear_table/1,transform_table/3,4, table copies and their storage types, user properties, access mode, load order and majority; master nodes,force_load_table/1,change_config/2andset_debug_level/1. - Disc storage: disc storage:
create_schema/1,2anddelete_schema/1, the disc schema,disc_copiesanddisc_only_copiestables, the transaction log withdump_log/0,sync_log/0and its thresholds,dump_tables/1, and storage type changes of tables and of the schema. - Events, text files and reports:
- events:
subscribe/1,unsubscribe/1andreport_event/1, the event handler's reports and the debug levels; - text files:
load_textfile/1anddump_to_textfile/1; - query tables:
table/1,2; - the report of
info/0andsystem_info/0, andlkill/0,kill/0andms/0.
- events:
- Checkpoints and backups: checkpoints, backups through the default backup module
mnesia_backup, traversals, restores and fallbacks. - Fragmented tables: fragmented tables with
mnesia_frag_hashand the access modulemnesia_frag, and SNMP indexes. - Declined:
add_backend_type/2, which needs external storage backends (mnesia_backend_typemodules); Clause keeps tables inetsanddetsonly. It raises{not_implemented, add_backend_type, 2}. - Several nodes: over distribution, Clause and OTP nodes in one database. The same files as OTP's in mnesia's directory, so that OTP and Clause nodes take turns on one directory. Schema transactions logged as OTP's operations. OTP's process names and the queries other nodes make. Connecting nodes. Merging schemas. Dirty access to tables held on another node. Locks on other nodes. Commits over several nodes. Table copies and loads over several nodes. Disc nodes created and started together. Master nodes, majority and copies between disc nodes. Partitions of disc nodes and adopted orphans. Checkpoints and backups over nodes. Restores and fallbacks over nodes. Events and fragmented tables over nodes. What OTP writes and sends is recorded in mnesia's files and protocol.
Every other documented function works. See the function inventory and differences.
Design
mnesia is written in Erlang over ets, dets and disk_log, in its own structure. Where programs can observe
something, it keeps OTP's shape:
- Tables: each
ram_copiesanddisc_copiestable is a public namedetstable withkeypos2, which code may read directly; eachdisc_only_copiestable is adetstable of the same name. - Files: the files of mnesia's directory have OTP's names and terms.
- Results and errors: results and
{aborted, Reason}terms are OTP's, and so are the exits ofabort/1and of dirty functions ({aborted, Reason}). - Table definitions: the
cstructrecord oftable_info(Tab, cstruct)and of the schema table's records has OTP's fields, and so do the cookies and versions. - Registered names: the processes Clause has use OTP's names.
The design keeps OTP's formats, so that a later step can add more nodes.
Processes
application:start(mnesia), or mnesia:start/0,1, starts this tree (clause_mnesia_app):
mnesia_sup:mnesia_event, thegen_eventmanager for system events, with theevent_moduleparameter's handler. The default handler (clause_mnesia_event) reports them as OTP's does (see events);mnesia_ext_sup, for backend processes;mnesia_kernel_sup:mnesia_monitor(clause_mnesia_monitor);mnesia_subscr, which keeps the event subscriptions (clause_mnesia_subscr);mnesia_locker, the lock manager (clause_mnesia_locker);mnesia_recover(clause_mnesia_recover), which connects to other nodes' mnesia (see connecting nodes);mnesia_tm, the transaction manager (clause_mnesia_tm);mnesia_rpc, which runs other nodes' calls (mnesia_rpc, see queries from other nodes);mnesia_checkpoint_sup, with a process for each checkpoint;mnesia_controllerandmnesia_late_loader(clause_mnesia_controller): the controller answers the table definitions other nodes fetch, and learns after a merge which tables they hold.
Each child has OTP's name, order and modules, as supervisor:which_children/1 shows them.
mnesia_monitor does four things:
- Owns the tables:
mnesia_gvar, theschematable, every table and every index table belong to it. They go when mnesia stops;detstables and the log close. - Reads the configuration: see configuration.
- Keeps the directory: it loads a disc schema at start and runs every dump of the transaction log, so that dumps and schema changes never overlap.
- Applies schema changes: each change runs in a schema transaction of its own process, as OTP's schema
coordinator does:
- the transaction takes OTP's locks and makes OTP's checks in OTP's order (clause_mnesia_change), then the monitor applies the change;
- it counts as one committed or failed transaction; starting counts two commits;
- inside any activity it returns
{aborted, nested_transaction}.
Queries from other nodes
Another node's mnesia, OTP's or Clause's, calls OTP's internal module names on this node. Clause provides those modules, with the functions other nodes call and OTP's answers (mnesia's files and protocol); their other functions are declined:
- mnesia_lib:
is_running/0,is_running_remote/0,get_node_number/0, and the record readsdb_get,db_first,db_last,db_next_key,db_prev_key,db_slot, and the select chunksdb_select_init,db_select_rev_initanddb_select_cont; - mnesia_index: the index reads
dirty_read2/3anddirty_match_object/3; - mnesia_tm:
fixtable/3, which a transaction walking a table here calls; - mnesia_schema:
remote_read_schema/0, where a start would take the schema from, anddelete_schema2/0; - mnesia_controller:
get_remote_cstructs/0, the table definitions; - mnesia_rpc: the server for
{apply, M, F, Args}calls, andcall/4; - mnesia_checkpoint:
tm_prepare/1,call/2,cast/2andremote_deactivate/1, withmnesia_tm:prepare_checkpoint/1, for checkpoints over nodes; - mnesia_log:
tab_copier/3, which a backup on another node spawns.
create_schema/1 and delete_schema/1 ask each node through these queries, so they work with OTP nodes too.
Connecting nodes
Clause's mnesia connects to other nodes' mnesia, OTP's or Clause's, as OTP's does (mnesia's files and protocol):
- Protocol:
mnesia_monitor:negotiate_protocol/1agrees on protocol{8,6}(or{8,5}) with each node's monitor, which links the two monitors (clause_mnesia_connect). - Recovery nodes:
mnesia_recover:connect_nodes/1adds the nodes whose mnesia runs torecover_nodes, and the nodes exchange their transaction serials, so that transaction numbers keep growing across nodes (clause_mnesia_recover). - Going down: when a linked node's mnesia stops or its connection breaks, the node leaves
recover_nodes, this node records itsmnesia_down(mnesia_recover:has_mnesia_down/1) and reports the{mnesia_down, Node}system event. - Partitions: two running nodes that recorded each other down report
{inconsistent_database, running_partitioned_network, Node}when they meet again, unless the other node has master nodes for the schema, and stay apart; a node starting again reportsstarting_partitioned_network, unless it has master nodes itself, and takes the running node's replicas (protocol).
Each node keeps the outcomes of the transactions it took part in (transactions), and a disc
node logs them until each disc node taking part is certain (disc nodes); a decision another
node sends in {decisions, ...} is not taken yet.
Merging schemas
change_config(extra_db_nodes, Nodes), and a start with the extra_db_nodes parameter, merge this node's schema with
those of the nodes that run mnesia, OTP's or Clause's, as OTP's does (mnesia's files and protocol):
- The merge: after connecting, a schema transaction locks the schema on every node, takes the other node's table definitions and commits the merged ones on both sides with OTP's two-phase schema commit (clause_mnesia_merge, clause_mnesia_commit). The lock manager and the transaction manager answer other nodes' requests in OTP's raw form.
- After it: both nodes list each other in
db_nodesandrunning_db_nodes; each node's tables are read and written on the node that holds them, and the controllers report{mnesia_up, Node}. A table defined on both nodes with another cookie fails the merge with{error, {merge_schema_failed, Message}}, OTP's message. - A node going down: its tables stay defined but are read nowhere until it comes back; a node starting again with
extra_db_nodestakes the running nodes' definitions and loads each replica that a running node holds too from it (table copies), while a RAM table of its own comes back empty. - Schema changes after it reach every running node's schema (transactions).
- Not yet: a node asked to commit another node's restore, fragment change or SNMP change votes no.
Disc nodes
Nodes whose schemas are on disc, OTP's or Clause's, are created and start together as OTP's (mnesia's files and protocol):
- Creating:
create_schema/1,2over several nodes installs the same fallback on each, under the global lock of the schema, through OTP's fallback receiver (mnesia_bup:fallback_receiver/2, clause_mnesia_backup), which Clause nodes run for OTP'screate_schema/1too. - Starting: a node connects to the schema's other nodes as a merge does, which commits only the
definitions that differ. A replica that another node holds too then loads from a running node whose replica is
active; from its own files when no other node holds the table on disc or this node logged each of them going down
before it stopped (
initial); empty when the table is held in RAM only (ram_only); otherwise it waits until another node loaded the table, and loads it from there (clause_mnesia_loader). Until its load ends it is read nowhere andwait_for_tables/2waits for it. - Disc replicas go over nodes as RAM ones do; a
disc_copiesreceiver writes itsDCDfile, and twodisc_only_copiesreplicas exchangedetschunks. - Logs: a commit over disc nodes is logged under its decision on each of them, and each node's
mnesia_recovertells the others once it is certain; the other nodes' mnesia coming up and going down is logged and kept inDECISION_TAB.LOG, which the next start reads to decide its loads. - Schema changes that need a table's replicas on disc nodes, as
delete_table/1and index changes, abort while one of those nodes is down, with OTP'snot_activereason. - Master nodes decide the loads at start (protocol): a table loads only from its master nodes,
from this node's files when it is one of them (
local_master), and otherwise waits for one.force_load_table/1loads a waiting replica from this node's files (forced_by_user). - Majority: a write lock on a
majoritytable aborts with{no_majority, Tab}unless more than half of its replicas are active. - Copies between disc nodes:
add_table_copy/3,move_table_copy/3andchange_table_copy_type/3work for another node's disc replicas, anddel_table_copy(schema, Node)removes a stopped disc node, whose filesdelete_schema/1then removes. - Orphans: replicas that wait for each other at start are adopted when a node comes up (protocol): the smallest disc holder loads them from its files (
{adopt_orphan, Node}) through its late loader, leaving the tables another node loads from its own disc, or asks their master nodes to load them. - Commits choose OTP's protocol:
asym_trans, logged under its decision even on one node, when the written tables differ in nodes or storage.
Global variables
mnesia_gvar is a public set of {Name, Value} rows, as in OTP.
- Table properties: each table has
{{Tab, Item}, Value}rows:- from its definition:
cstruct,attributes,arity,record_name,setorbag,index,wild_pattern,record_validation,cookie,versionand the node lists; - from its replica on this node:
storage_type,where_to_read,where_to_write,where_to_commit,where_to_wlock,active_replicas,load_node,load_reason,index_info,commit_work, and{index, Pos}for each index table.
- from its definition:
- Answers built from these rows:
table_info(Tab, Item)reads them,table_info(Tab, all)lists them, andschema/1prints them withsize,memoryandmaster_nodes. Both list the same items as OTP, in the same order. - User properties: each also has a
{{Tab, user_property, Key}, Property}row, whichread_table_property/2reads. - Other rows:
mnesia_status, the configuration values,{schema, tables},{schema, local_tables},{current, db_nodes}and the transaction counters.
Master nodes are {master_nodes, {tab, Tab}, Nodes} rows of the mnesia_decision table, as in OTP.
A missing row gives OTP's answer:
- a table's
where_to_readisnowhere, and itswhere_to_writeandactive_replicasare[]; - any other missing row aborts with
{node_not_running, Node}when mnesia is not running, and with{no_exists, Name}when it is.
Configuration
The documented configuration parameters are read when mnesia starts. Each comes from the application environment, or
else from its documented default. A value of the wrong type stops the start with {bad_config, Name, Value}.
mnesia:start/1 takes {Name, Value} pairs and sets them before starting. A bad value returns
{error, {bad_type, Name, Value}}, as in OTP.
system_info/1 answers the configuration items even when mnesia is not running. Other items then answer as OTP's
do:
tablesandlocal_tablesabort with{node_not_running, Node};transaction_commitsand the other counters abort withbadarg;transactionsaborts with OTP'sbadmatch.
Schema
The schema lives in RAM, or on disc when mnesia's directory holds one (see disc storage).
create_table/2 checks a definition in OTP's order, with OTP's reasons
(clause_mnesia_schema):
- Option keys: an unknown key, or anything that is not a
{Key, Value}pair, givesbadarg. A repeated key gives{badarg, Tab, "Duplicate keys", Keys}. storage_properties:etsanddetsoptions that mnesia sets itself are refused.- Existing table:
already_exists. - The definition's checks:
- node lists, then the table name, the type and
record_name; - attributes: at least two atoms, never
snmp, none twice; - index positions: after the key,
bagorordered; local_content,access_mode,majority, the SNMP structure,user_properties,cookieandversion.
- node lists, then the table name, the type and
- Disc nodes: a disc node that is not running gives
not_active. Disc copies on this node with a RAM schema give{bad_type, Tab, disc_copies, Node}.
Behavior that follows OTP's:
- A table on other nodes only exists in the schema, with no replica here:
where_to_readisnowhereandstorage_typeisunknown. - A
read_onlytable is written nowhere: dirty writes abort with{no_exists, Tab}. {ram_copies, []}with no other copies means a table on this node.- An index listed twice gives two index tables, as in OTP.
delete_table/1 removes the table, its index tables and its rows. wait_for_tables/2 waits until each table has a
replica to read here, and returns {timeout, Tables} for the rest.
Schema changes
Each change takes OTP's locks: the schema's write lock first, then the table's write lock where OTP takes it, which
also aborts with {no_exists, Tab} for a table that is read_only or has no replica here. Then come OTP's checks:
{no_exists, {Tab, cstruct}} for an unknown table, {no_exists, Tab} without an active replica, and the definition's
checks of create_table/2 for the changed definition. Each change gives the definition its next major version.
clear_table/1: a transaction of its own, not a schema transaction. It takes the table's write lock and clears the table and its indexes at the commit. Inside a dirty activity it is a transaction; inside a transaction it aborts withnested_transaction.transform_table/3,4: new attributes and record name; the indexes keep their positions and are rebuilt.- The function sees each record in key order. A record it returns unchanged stays, and one with the new record name and the same key replaces it.
- A wrong arity, key or record name, or a failing function, aborts with
{"Bad transform function", Tab, Fun, Node, Reason}.mnesia_eventthen prints OTP'sTransform function failedreport. ignorechanges the definition only. For abagkey, only the records the function changes stay, as in OTP.
- Table copies:
add_table_copy/3adds a node first in its storage's list. Aram_copiesreplica on a node outside the running nodes only changes the definition. A replica on a running node of a table held on another running node, OTP's or Clause's, is loaded from that node with OTP's transfer before the commit (mnesia's files and protocol, clause_mnesia_loader); this node sends its replicas to other nodes the same way, from a process its controller starts.del_table_copy/2deletes the table with its last replica. Deleting the schema's copy on another node also removes that node's replicas of every table, and deletes the tables it alone held.move_table_copy/3needs both nodes running, so on one node it always aborts withnot_active. Over two nodes it adds the copy, loaded as above, then deletes the old one, as OTP's operations do.change_table_copy_type/3tounknowndeletes the replica. The other changes are described under storage types.
- Table properties:
write_table_property/2anddelete_table_property/2changeuser_properties.change_table_access_mode/2,change_table_load_order/2andchange_table_majority/2change their fields.read_onlywrites the table nowhere, so writes abort with{no_exists, Tab}.
- Not schema transactions:
set_master_nodes/1,2keep the master nodes that hold a replica. With mnesia stopped they check and log them againstschema.DAT, return{error, "No schema file exists"}with only a fallback, andokwithout a directory (disc nodes).force_load_table/1answersyesfor a table loaded here, and loads a replica that waits for another node from this node's files. For a table without a replica here, it waits for one, as OTP's does.change_config/2:dc_dump_limittakes effect at once;extra_db_nodesmerges the schemas and returns the given nodes that run mnesia with this one.
set_debug_level/1sets thedebugparameter and returns the previous level. While mnesia runs it also changes the event handler's subscriptions (see events).
Disc storage
Disc storage keeps OTP's files in mnesia's directory, the dir parameter (default Mnesia.<node()>)
(clause_mnesia_disc):
| File | Contents |
|---|---|
FALLBACK.BUP | the backup that create_schema/1,2 writes, installed at the next start |
schema.DAT | a dets table of the schema's {schema, Tab, CreateList} records |
LATEST.LOG | a disk_log of #commit{} records with each commit's disc writes, {master_nodes, Tab, Nodes} entries, and the decisions and other nodes' mnesia_up and mnesia_down records of disc nodes, after a #log_header{} |
PREVIOUS.LOG | the log a dump is moving into the tables' files |
DECISION_TAB.LOG | the {decision_list, Decisions} that each dump finding entries in the log writes: the transaction serial {trans_tid, serial, N}, the master nodes and the other nodes seen going down |
Tab.DCD, Tab.DCL | a disc_copies table's records, and its writes since the DCD file was written |
Tab.DAT, Tab_Pos.DAT | a disc_only_copies table's dets table, and the dets table of its index at Pos |
The disc schema
- Creating:
create_schema/1,2makes the directory and writes the fallback, with OTP's checks and errors: a repeated node, a node that has a schema or does not answer, a bad schema property, andschema_locationram({has_no_disc, Node}). - Deleting:
delete_schema/1removes mnesia's files from the directory, which stays. It fails while mnesia runs. - Using it:
system_info(use_dir)followsschema_location:discalways uses the directory,opt_discwhen it holds a fallback or a schema,ramnever.system_info(fallback_activated)istruewhile a fallback waits. - Starting: the fallback, if any, becomes
schema.DAT. Each table then gets its records: adisc_copiestable from itsDCDandDCLfiles, adisc_only_copiestable from itsdetsfile, a RAM table from a dump bydump_tables/1. Theirload_reasonislocal_only, the schema'sinitial; a table that other nodes hold too loads once the start connected to them (disc nodes). The decision log's master nodes are set, and transactions continue its serial. The log since the last dump is applied again: its committed writes, also those of OTP's schema transactions, and its master nodes. Then, withdump_disc_copies_at_startup(the default), thedisc_copiestables the log touched or that have aDCLfile get newDCDfiles; without it, the log's writes go to theirDCLfiles. The log starts afresh, and the decision log is written when the log held entries. - Schema changes: each change writes the changed tables' records to
schema.DATat once and is logged as OTP's schema transaction; it counts two log writes, as OTP's do. A newdisc_copiestable starts with aDCDfile without terms, as OTP's; a deleted table's files go. - The same files as OTP's: an OTP node starts on a directory a Clause node wrote and the reverse, with the records, indexes, master nodes, fallbacks and schema transactions left in the log found again.
Transaction log
- Logging: a commit that writes a
disc_copiesordisc_only_copiestable appends one#commit{}record toLATEST.LOGbefore the tables change, sosystem_info(transaction_log_writes)counts it. Dirty writes and transactions are logged,etsactivities and RAM tables are not.sync_transaction/1,2,3andsync_dirty/1,2write their record before going on; the others hand it to the log.set_master_nodes/1,2logs each table's master nodes, which the next start sets again. - Schema transactions: each logs OTP's commit,
{op, ...}tuples with the tables' create lists under a{decision, Tid, presume_abort, [Node], []}, then{decision, Tid, committed, [], []}:create_table,delete_table,add_index,del_index,transform(with its function),change_table_copy_type, the access mode, load order and majority with their old and new values,write_property,delete_property,add_snmp,del_snmp,dump_tablewith the table's size,change_table_fragwith the fragments created or deleted and arecoperation per moved record, and a restore'sclear_tableandrestore_recreatewith the restored records as the commit's writes. As OTP does, the log is dumped right afterdelete_table,transformandchange_table_copy_type, and before them, so that no older write replays over the table. A start replays cleared, restored and moved records in the log's order. A transaction that writes amajoritytable logs under its decision the same way, even when it wrote only RAM tables. - Dumps:
dump_log/0returnsdumped, and a dump also follows everydump_log_write_thresholdwrites and everydump_log_time_thresholdmilliseconds. A dump moves the log's writes into each table'sDCLfile, or writes a newDCDfile when theDCLfile has grown to1/dc_dump_limitof it.disc_only_copiestables are synced. The log goes toPREVIOUS.LOGwhile it is dumped, and a dump that found entries writesDECISION_TAB.LOG. - Errors:
sync_log/0syncs the log, and returns{error, no_such_log}with a RAM schema. Without a running mnesia both return{error, {node_not_running, Node}}. dump_tables/1: writes RAM tables toDCDfiles, which the next start loads. It aborts with{"Only allowed on ram_copies", Tab, Nodes}for disc tables,{bad_type, schema},{no_exists, Tab}, and{has_no_disc, Node}with a RAM schema.
Storage types
change_table_copy_type/3 moves a replica between storage types:
- Tables: the records move between
etsanddets, the indexes are built again for the new storage, and the disc files follow. A RAM table goes to disc only on a disc schema ({has_no_disc, Node}) and without a dump bydump_tables/1({combine_error, Tab, Node, "Table dump exists"}).ordered_settables cannot bedisc_only_copies. - The schema: to
disc_copiesit writes a new directory, and needsschema_locationopt_disc({combine_error, schema, Node, "schema_location must be opt_disc"}). Back toram_copiesit removes the directory's files, and aborts with{"Disc resident tables", Tabs, Node}while this node has disc tables.
Disc-only tables
A disc_only_copies table works on its dets table, as OTP's:
- Walks:
detshas no order, solast/1isfirst/1,prev/2isnext/2, and reverse selects run forward. - Indexes: each index is a
detsbagof{Value, Key}, listed inindex_infoas{{Pos, bag}, {dets, {Tab, index, {Pos, bag}}}}. It is built again at each start. - Information:
table_info(Tab, memory)is the file's size in bytes, asdetsgives it.
Dirty access
The dirty functions run in the calling process and work on the table's ets table:
- Reads (
dirty_read,dirty_match_object,dirty_select,dirty_select_reverse,dirty_all_keys, the walk functions,dirty_index_read,dirty_index_match_object) go to the replicawhere_to_readnames, this node's when it has one. Without a replica they abort with{no_exists, Args}, and a failing read gives{badarg, Args}. - Writes (
dirty_write,dirty_delete,dirty_delete_object,dirty_update_counter) first check the record against the table's record name and arity. They then update the replica and its indexes. - Counters:
dirty_update_counterfollows OTP's rules:- the table must be a set or ordered_set of three-field records;
- a missing counter starts at the increment, or at zero;
- a value that is not an integer, or that would go below zero, is replaced the same way.
- Index use: a match or one-clause select whose pattern leaves the key unbound but binds an indexed position
uses that index. It returns the records in OTP's order: last key first for matches, the table's order for
ordered_setselects. - Tables held on another node (mnesia's files and
protocol): a read runs as OTP's call of
mnesia_lib,mnesiaormnesia_indexon the nodewhere_to_readnames, through that node's mnesia_rpc, so the holder may be an OTP node. A write goes to each other replica'smnesia_tmas OTP's commit: synchronously, waiting for the holder's result, in async_dirtyactivity and whenever this node holds no replica, else without an answer. The holder applies it and reports its table events with the writer's activity id. A write whose holder goes while it waits returns{'EXIT', {aborted, {node_not_running, Node}}}, as OTP's;select/4chunks in dirty activities are read on the holder too.
Transactions
A transaction runs in the calling process (clause_mnesia_tm). Its
activity is {AccessModule, {tid, Counter, Pid}, #tidstore{}} under mnesia_activity_state in the process
dictionary, as in OTP:
- Store:
mnesia_tmgives each transaction anetsbag of its locks and of its writes and deletes. Reads merge these into the table's records (clause_mnesia_written), so a transaction sees its own writes, with OTP's order of results. - Commit:
mnesia_tmapplies the writes to the tables and their indexes, then releases the locks. A transaction whose process dies holds no locks afterwards. - Results:
{atomic, Value}, or{aborted, Reason}with OTP's reasons:abort/1's reason,{throw, Value}, an exit's reason, and{Reason, Stack}for an error. - Nesting: an inner transaction works on a copy of the outer store, which its commit hands back. Its abort leaves the outer transaction running. Inner commits and aborts count too.
- Restarts: a refused lock (
#cyclic{}) restarts the outermost transaction with the same tid, after OTP's growing pause, countingtransaction_restarts. When the retries run out the result is{aborted, nomore}. - Other nodes (mnesia's files and protocol):
a transaction writing tables held on other nodes, OTP's or Clause's, commits there with OTP's two-phase protocols
(clause_mnesia_commit):
sym_transfor tables replicated on the same nodes,asym_transfor tables of different nodes and majority tables, and for every schema change, which reaches every running node's schema. This node takes part in other nodes' commits the same way (clause_mnesia_participant):mnesia_tmvotes on and appliessym_transcommits, a process of its own eachasym_transcommit, with the transaction's table events. A node going down before it votes restarts the transaction, which commits on the nodes still running; a coordinator going down before deciding aborts its transaction on the participants unless another one knows it committed. Each node keeps the outcomes of the transactions it took part in and answers other nodes'what_happenedquestions from them.
select/4 and select_reverse/4 return OTP's #mnesia_select{} continuation. In a transaction with writes to the
table, each chunk merges them as OTP's does, chunk boundaries included.
Locks
mnesia_locker keeps read and write locks on records, whole tables ({Tab, '______WHOLETABLE_____'}) and global
items (clause_mnesia_locker):
- Conflicts: a request that conflicts only with younger transactions waits in the queue. One that conflicts with an older transaction is refused, and its transaction restarts. A free lock also waits behind older queued requests for its table, and for its record when it is a read.
- Release: a transaction's end releases its locks, and the queued requests are tried again, youngest first.
- Results:
lock/2returns what OTP's does: the nodes for a new write lock,[]for a record write lock held already, the majority flag for a table write lock held already, the records for a record read lock,okfor a new table read lock. - Sticky locks:
s_write/1and the other sticky operations need a replica here; the table's first one also takes its read lock and its sticky item. - Information:
system_info(held_locks),lock_queueandtransactionsgive OTP's terms. - Other nodes (mnesia's files and protocol): a
lock is taken by the lock manager of the node that keeps it, OTP's or Clause's, with OTP's raw messages: a read lock
on the node
where_to_readnames, which sends the records read with its grant, a write lock on each node ofwhere_to_write, a global lock on each listed node running with this one, an index read as oneix_readrequest. The transaction remembers those nodes: its commit sends their transaction managerssimple_commit, its abort their lock managersrelease_tid, and a restart waits for each of them to release its locks. Conflicts follow the same rules across nodes, by tid. When a transaction's process dies, the other nodes are told to abort it; when a node goes down, a transaction waiting for its grant restarts, and the node's transactions lose their locks here.
Activities
activity/2,3,4, async_dirty/1,2, sync_dirty/1,2 and ets/1,2 run a fun with mnesia's functions mapped as in OTP
(clause_mnesia_access):
- Dirty activities use the dirty functions;
etsworks on the tables directly. - Inside a transaction a dirty activity is a nested transaction, whose abort reason becomes an exit.
- Access modules: each function calls
AccessModule:F(ActivityId, Opaque, ...). The default modulemnesiaexports these arities, so other access modules can call back.table_info/2goes through the access module too. - Errors: an error in a dirty activity exits with
{Reason, Stack}; a returned{aborted, Reason}aborts.
Indexes
Each index is an ordered_set table of {{Value, Key}} (clause_mnesia_index):
- Bookkeeping:
index_infoandcommit_worklist the indexes newest first, as{{Pos, ordered}, {ram, Table}}(adisc_only_copiestable's asdetstables).table_info(Tab, index)lists their positions in that order. - Upkeep: every write and delete keeps the index tables current:
- a set table's entry changes only when its value does;
- a bag table's entry goes when no other record under the key holds its value.
- Schema changes:
add_table_index/2fills a new index from the table's records.del_table_index/2removes every index of the position. - Errors: both answer with OTP's reasons (
already_exists,no_exists,bad_type), and each change gives the table definition its next major version.
Events
mnesia_subscr keeps the subscriptions (clause_mnesia_subscr). It links
each subscriber and drops its subscriptions when it exits.
-
Subscribing:
subscribe/1andunsubscribe/1return{ok, Node}, or OTP's errors:{badarg, What}for an unknown category;{already_exists, What}for a second subscription of the kind; a table's simple and detailed subscriptions count as one;{no_exists, Tab}for an unknown table,{not_active_local, Tab}for a table without a replica here;{node_not_running, Node}without a running mnesia;- unsubscribing from a table that does not exist gives
badarg.
-
Where the subscribers are kept, as in OTP:
- the
subscribersandactivity_subscribersvariables; - a
{subscribers, Simple, Detailed}entry in the table'scommit_work, and itssubscribersproperty; - each change of
commit_work, an index's too, puts its entries in OTP's order; system_info(subscribers)lists the event manager first.
- the
-
System events:
{mnesia_system_event, Event}goes to each system subscriber and to the event manager:{mnesia_user, Event}fromreport_event/1;{mnesia_info, Format, Args}and the other reports;{mnesia_down, Node}when mnesia stops.
Without a running mnesia,
report_event/1starts an event manager for that event alone, which prints it. -
Activity events:
{mnesia_activity_event, {complete, Tid}}when a transaction that wrote commits, schema transactions included. Reads, aborts, inner transactions and dirty activities send none. -
Table events: sent while a commit or a dirty update applies, before the table changes.
- Simple:
{write, Record, Activity},{delete, {Tab, Key}, Activity}and{delete_object, Record, Activity}, the record named after the table. - Detailed:
{write, Tab, Record, OldRecords, Activity}and{delete, Tab, What, OldRecords, Activity}. - The activity is
{dirty, Pid}for a dirty update and the tid for a transaction.etsactivities send none. - A counter update is a write, with the record it replaced.
clear_table/1reports the table's schema record deleted and written again.
- Simple:
-
Schema events: each schema change reports the changed table's
{schema, Tab, Definition}record:- written twice for a new table or a new table copy, before and after it is stored;
- deleted for a deleted table, with
undefinedas the old records of a detailed event; - written once for any other change.
-
The handler: the default handler reports as OTP's:
- it prints info reports, once when one comes again, and user events, as
Mnesia(Node): ...; - it logs warnings and errors through
error_logger; - it prints the table events it subscribes to at the debug levels: the schema's at
debug, every local table's attrace, fromset_debug_level/1or from the start; - a process registered globally as
mnesia_global_loggergets a copy.
- it prints info reports, once when one comes again, and user events, as
-
Over nodes (protocol): a table subscription needs a replica here (
{error, {not_active_local, Tab}}); each node reports the updates its replicas apply, from any node's transactions and dirty writes.
Text files
clause_mnesia_text reads and writes OTP's text files: a
{tables, [{Tab, Options}]} term, then records named after their tables.
load_textfile/1:- mnesia starts first, on a new disc schema when its directory has none;
- each listed table is created, or takes the records when it exists; a table that cannot be created is reported, and its records left out;
- the records are written in one transaction, whose result it returns.
- Errors, with OTP's messages:
{error, open},{error, bad_header},{error, undefined_object}for a record of an unlisted table, and{error, read}for a term that does not parse. A table entry that is not a pair throws{error, badtab}, or fails withfunction_clausefor a triple, as in OTP. dump_to_textfile/1: writes this node's tables other than the schema, with their record names and attributes, then their records. Without a running mnesia it returnserror.
Query tables
table/1,2 give qlc a table (clause_mnesia_qlc):
- Options:
{lock, Lock},{n_objects, N}and{traverse, select | {select, MatchSpec}};qlctakes the others. - Reading: in the caller's activity, in chunks of
select/4. A filter on the key reads throughread/3, and one on an indexed position throughindex_read/3. - Information:
qlc:info/1prints OTP's form of the query. - Errors: outside an activity the query aborts with
no_transaction. A cursor's process takes the activity of the process that made it. - Fixing: a dirty traversal of a
setorbagtable fixes it withsafe_fixtable.
The report
clause_mnesia_info prints OTP's report.
-
info/0:- the locks held and wanted, and the coordinators of running transactions;
- each active table with its size and memory, or file size for a
disc_only_copiestable; - then the report of
system_info/0.
-
system_info/0: prints and returns whether mnesia runs:- the version, the debug level, the directory, the fallback, and the running and stopped nodes;
- the master node tables, the tables of each storage, and the tables written at the same replicas;
- the transaction and lock counts.
Without a running mnesia, both print only the first lines.
-
lkill/0: kills mnesia's processes at once, as OTP's debug function does, and the application ends asexited: normal.kill/0does so on each node, andms/0lists OTP's names that they end.
Checkpoints
A checkpoint keeps its tables as they were when it was activated (clause_mnesia_checkpoint).
- Activating:
activate_checkpoint/1returns{ok, Name, Nodes}; the default name is{Integer, node()}. OTP's errors:{badarg, Arg}for an unknown argument, and{already_exists, Name}for a name in use;combine_errorfor a table in bothminandmax, for no table at all, and for anyram_overrides_dumplist, which OTP accepts only for tables in both lists;{"Cannot prepare checkpoint (replica not available)", [Tab, Name]}for a table without an active replica.
- Retainers: each checkpoint is a process under
mnesia_checkpoint_supwith a retainer for each table. Before an update changes a key for the first time since activation, the retainer keeps the key's records; a cleared table keeps each of its keys. The schema keeps its records in the same way. - RAM tables: a
ram_copiestable, unlessram_overrides_dumpnames it, keeps its records from its dump (dump_tables/1) and retains nothing, as in OTP. A backup of it holds its dumped records only. - Bookkeeping, as in OTP:
system_info(checkpoints),table_info(Tab, checkpoints), the{Tab, {retainer, Name}}variables and a{checkpoints, Names}entry first in the table'scommit_work. - Deactivating:
deactivate_checkpoint/1returnsok, or{error, {no_exists, Name}}. A checkpoint also ends when its table's replica here goes, with the{mnesia_checkpoint_deactivated, Name}system event and OTP's error report. - Over nodes (protocol): a retainer is
written by each active replica of a
maxtable, by one replica of amintable, here when there is one. Each node writing a retainer has the checkpoint's process and retains its own replica's updates, with OTP's calls, so OTP and Clause nodes share checkpoints. A node going ends the checkpoints it alone wrote a table of; a node getting a new replica (by its start oradd_table_copy/3) joins the checkpoints keeping the table with most redundancy, with the records retained so far; a replica deleted leaves its retainers.deactivate_checkpoint/1ends the checkpoint on each of its nodes.
Backups
clause_mnesia_backup writes and reads backups through a backup module,
by default mnesia_backup (mnesia_backup), which keeps OTP's callbacks and its
disk_log file.
- Contents: a
#log_header{}of kindbackup_log, the schema's{schema, Tab, CreateList}items, then each table's records named after the table, and{Tab, Key}deletes. backup_checkpoint/2,3: the schema first, then each table of the checkpoint: its records now, then each retained key as a delete followed by the records at activation, so that restoring them in order gives the checkpoint's state. Without the schema in the checkpoint, each table's definition is written instead.- Arguments: a backup module, or
{module, Mod},{scope, global | local},{tables, Tabs}and{incremental, PreviousCheckpoint}. - An incremental backup holds the keys changed since the previous checkpoint: their records now, then the records the newer checkpoint retained.
- Errors as OTP's:
{badarg, Arg}, and{error, {'EXIT', Reason}}when the backup fails. A backup module whoseabort_write/1fails gets OTP's error report.
- Arguments: a backup module, or
backup/1,2: a checkpoint of every table, backed up and deactivated. A table without a replica here makes it fail.- Over nodes (protocol): a table whose retainer another node
writes is read there, by OTP's copier
mnesia_log:tab_copier/3. The checkpoint must be on the node backing it up. traverse_backup/4,6: passes each schema item and record to the fun, and writes what it returns to the target, or nothing with the target moduleread_only. The result is{ok, Acc}or OTP's errors, such as{"Backup traversal failed", Reason}.
Restoring
restore/2 restores tables from a backup in one schema transaction and returns {atomic, Tabs}:
- Options: each table is cleared (the default), kept, recreated with the backup's definition, or skipped:
{clear_tables, Tabs},{keep_tables, Tabs},{recreate_tables, Tabs},{skip_tables, Tabs}and{default_op, Op};{module, Mod}names the backup module. - Records: the backup's records of the restored tables are written in order, and its deletes applied, under the tables' record names. The schema's own definition is never restored.
- Errors:
{aborted, Reason}for a bad argument ({badarg, {clear_tables, schema}}and others) and for a backup that cannot be read, before any transaction. - Over nodes (protocol): every node running mnesia takes part; each clears or makes its replicas of the restored tables and writes the records of the tables it holds, which come in its commit, as OTP's.
Fallbacks
- Installing:
install_fallback/1,2copies a backup toFALLBACK.BUP. The backup's schema must hold this node's disc schema. Arguments: a backup module,{module, Mod},{scope, global | local}, and{mnesia_dir, Dir}with a local scope. Errors are OTP's{"Cannot install fallback", Reason}, such as{already_exists, Node}for a second fallback. - Uninstalling:
uninstall_fallback/0,1removes the fallback. - Over nodes (protocol): a global
fallback (the default scope) goes to every disc node of the backup's schema through OTP's fallback receivers, and a
global
uninstall_fallback/0,1removes it from every disc node of the fallback's schema through OTP'smnesia_bup:local_uninstall_fallback/2. A local one stays on its node. - Starting: the next start replaces the directory's database with the fallback: its schema, and each local
table's records in the table's files, a
disc_copiestable's asDCLwrites after an emptyDCDfile, as OTP's. The start's dump then merges them, unlessdump_disc_copies_at_startupisfalse. The decision log goes.
Fragmented tables
A table with frag_properties is split into fragments: the first is the table itself, fragment N the table
Tab_fragN (mnesia_frag).
- Hashing: mnesia_frag_hash is OTP's linear hashing over
erlang:phash2/2, with OTP's#hash_state{}and fragment numbers; states from before OTP R13 hash witherlang:phash/2. The base table'sfrag_propertieshold the hash module and state, andmnesia_gvarholds them as{Tab, frag_hash}. - Creating:
create_table/2withfrag_propertieschecks them as OTP does (n_fragments,node_pool,n_ram_copies,n_disc_copies,n_disc_only_copies,foreign_key,hash_module,hash_state) and creates each fragment, with its replicas spread over the node pool.delete_table/1of the base table deletes every fragment. - Access: with
mnesia_fragas the activity's access module, a record goes to the fragment of its key, or of its foreign key; reads without a key, selects, folds, walks and index reads go through every fragment.table_info/2in such an activity also answersbase_table,n_fragments,node_pool,foreign_key,foreigners, the replica counts,frag_names,frag_dist,frag_size,frag_memory, andsizeandmemoryover all fragments. change_table_frag/2:{activate, Props},deactivate,{add_frag, NodesOrDist}anddel_frag, which move the records that hash to another fragment, and{add_node, Node}and{del_node, Node}. Tables with a foreign key follow their foreign table's fragments. Errors as OTP's.- Majority:
change_table_majority/2of a base table changes every fragment; of another fragment it aborts withbad_type, as in OTP. - Over nodes (protocol):
fragments spread over a pool of OTP and Clause nodes;
add_fraganddel_fragmove records between fragments on either node,frag_sizeasks the node holding a fragment, anddel_table_copy(schema, Node)takes Node out of the pools.
SNMP
A table with an snmp structure, [{key, Types}] given to create_table/2 or snmp_open_table/2, keeps an ordered
index of its rows by SNMP row index, as OTP's mnesia_snmp_hook does
(clause_mnesia_snmp):
- Row indexes: an
integerkey is[Key], astringkey its length then its characters, afix_stringkey its characters; a tuple key joins its parts. A written key that makes no row index aborts with{bad_snmp_key, {Tab, Key}, Types}. - Lookups:
snmp_get_row/2,snmp_get_next_index/2andsnmp_get_mnesia_key/2, which see a transaction's own writes. Counter updates leave the index alone, as in OTP. snmp_close_table/1removes the index.
Tests
mnesia_dirtygolden: generated from OTP (fixture).mnesia_transactionsgolden: generated from OTP (fixture). It covers transaction results and abort terms, reads of own writes in each table type, walks, folds and index reads, nesting, the activity kinds, an access module, lock results and errors, conflicts between processes (waiting, restarts, retries running out, shared reads, a killed holder), schema transactions and select continuations.mnesia_schema_changesgolden: generated from OTP (fixture). It covers each schema change before starting and while running: results and abort terms, table copies on this node and on a node outside the schema, transform failures with their reports, properties, master nodes, configuration changes and their transaction counts.mnesia_discgolden: generated from OTP (fixture). It covers creating and deleting the disc schema with their errors, the directory's files, disc tables of each type and their indexes, transaction log writes and dumps,dump_tables/1, storage type changes of tables and of the schema,schema_locationand stopping and starting mnesia with the data found again.mnesia_eventsgolden: generated from OTP (fixture). It covers system, activity and table subscriptions with their events and errors, simple and detailed table events of dirty updates and transactions, schema events, the commit work's order, subscribers that exit, the debug levels' printouts,mnesia_downat stop,qlcqueries overtable/1,2withqlc:info/1, text files with their errors, the report ofinfo/0andsystem_info/0, andlkill/0andkill/0.mnesia_backupsgolden: generated from OTP (fixture). It covers checkpoints with their errors and bookkeeping, backups of the database and of checkpoints (full, incremental, of some tables, of a RAM schema), retained records of cleared tables, a checkpoint ended by its table's deletion, traversals that read and rewrite backups, restores with each option and their errors, and fallbacks installed, uninstalled and taken at the next start.mnesia_fragmentsgolden: generated from OTP (fixture). It coversmnesia_frag_hash's states and fragment numbers, fragmented tables created with their errors, access throughmnesia_frag, the fragment information, fragments added and deleted, activation, node pools, foreign keys, and SNMP indexes with their lookups in and outside transactions.mnesia_dir_exchangegolden: generated from OTP (fixture), with two nodes taking turns on one directory: a disc schema created, its tables written and their log partly dumped, master nodes set; a start without dumpingdisc_copiestables, records and tables changed; a backup installed as a fallback and started from. Each turn shows the directory's files and their terms; node b leaves schema transactions and a cleared table in the log for node a's start. Its runs pair Clause nodes with OTP nodes both ways, so that each reads the other's files.mnesia_schema_opsgolden: generated from OTP (fixture). Each schema operation runs between a start and a stop, and the log's terms after it are compared with OTP's, then the records the next start replays, and the directory's files after the last dump.mnesia_remote_queriesgolden: generated from OTP (fixture). Node a asks node b each query before b's mnesia ever ran, with a fallback, while it runs on a disc schema and after it stops, reads b's records throughdb_getand b'smnesia_rpc, lists b's processes and supervisor children, and checks b withcreate_schema/1anddelete_schema/1. Its runs pair Clause nodes with OTP nodes both ways.mnesia_connectgolden: generated from OTP (fixture). Node a negotiates with node b's monitor and connects to b, b refuses an unknown protocol and answers a decision query; b stops and starts and is connected again, and a partition between the running nodes is reported on both when they meet. Each step shows both nodes' system events, protocol and recovery variables, monitor links,mnesia_downrecords and transaction numbers. Its runs pair Clause nodes with OTP nodes both ways.mnesia_mergegolden: generated from OTP (fixture). Node a merges with node b, first failing on a table both define with other cookies, then after b deletes it; b stops, and starts again merging with a. Each step shows both nodes' db nodes and each table's readers, writers, replicas, storage, cookie and version. Its runs pair Clause nodes with OTP nodes both ways.mnesia_remote_dirtygolden: generated from OTP (fixture). After a merge, each node dirty-writes and reads the other node's table and counter table with every dirty function, and the holder reports the table events; then chunked selects, folds and writes in dirty activities, failing reads and refused writes, a write whose holder goes while it waits, and reads once the holder is gone. Its runs pair Clause nodes with OTP nodes both ways.mnesia_remote_locksgolden: generated from OTP (fixture). After a merge, each node's transactions take every kind of lock on the other node's table and read it, abort and nest; an older transaction waits in the other node's queue, a younger one is refused and restarts, a killed transaction's locks go, and a holder going down ends a wait and releases its transactions' locks. Its runs pair Clause nodes with OTP nodes both ways.mnesia_two_phasegolden: generated from OTP (fixture). After a merge, replicated tables are created from either node; each node's transactions write replicated tables, tables of different nodes, a majority table and only the other node's table, in sync, nested and aborted transactions, withclear_table/1and dirty writes, and both nodes hold the same records, the other node reporting the table events. Index, transform, property, load order, access mode and table changes reach the other node's schema; a clashingetsname makes the other node refuse a table; both nodes answerwhat_happened. One run ends with the participant going down before it votes, the other with the coordinator going down before this node votes. Its runs pair Clause nodes with OTP nodes both ways.mnesia_replicasgolden: generated from OTP (fixture). After a merge, copies are added on the other node and on this one by each node, a large table among them, deleted and moved both ways, with their errors; then b starts again and loads its replica of a replicated table from a. Each step shows both nodes' readers, writers, active replicas, load node and reason, and whether they hold the same records. Its runs pair Clause nodes with OTP nodes both ways.mnesia_disc_nodesgolden: generated from OTP (fixture). a creates the schema on both nodes, which start together; tables of each placement are written in transactions; schema changes wait for b while it is down; b starts again and loads from a; then a starts alone after b stopped last, loads what only it holds on disc and waits for the rest, which it loads from b once b is back. Each step shows both nodes' readers, writers, load nodes and reasons, and what each node's files hold. Its runs pair Clause nodes with OTP nodes both ways.mnesia_disc_mastersgolden: generated from OTP (fixture). Two disc nodes set master nodes while running and while stopped, refuse majority writes with one node down, start alone and force their loads; then replicas are added, moved and changed between the nodes, b leaves the schema while stopped, its files go, and it joins again as a RAM node made a disc node. Its runs pair Clause nodes with OTP nodes both ways.mnesia_partitionsgolden: generated from OTP (fixture). The connection between two running disc nodes breaks three times; each side writes alone, the nodes report the partition when they meet (on stderr) and b starts again, with and without master nodes. Then replicas wait for each other at start and a adopts them, alone, while starting, and through its master node b. Its runs pair Clause nodes with OTP nodes both ways.mnesia_remote_checkpointsgolden: generated from OTP (fixture). Checkpoints are activated on a and b with retainers on either node or both, records change on both, and backups read the other node's retainers; b stops (its checkpoints' end reported on stderr) and starts again, a new copy joins a checkpoint with the records retained so far, and deactivations and a deleted copy end checkpoints. Its runs pair Clause nodes with OTP nodes both ways.mnesia_remote_backupsgolden: generated from OTP (fixture). A backup of tables on a, on b and on both is installed as a fallback on both nodes and uninstalled from b; a local fallback stays on b; restores from a and from b clear, keep and recreate the tables, and bring back a deleted one; both nodes start again from a global fallback. Its runs pair Clause nodes with OTP nodes both ways.mnesia_remote_fraggolden: generated from OTP (fixture). Both nodes subscribe to tables held here and elsewhere and hear the events of transactions and dirty writes from either node; a fragmented table spread over both nodes is written and read from either, a fragment is added on b and deleted with its records moving between nodes, pool nodes are added and deleted, and b's schema copy is deleted while b is down, taking its fragments and its place in the pools. Its runs pair Clause nodes with OTP nodes both ways.- What
mnesia_dirtycovers: answers before starting, system information, everycreate_tableoption and error, table properties, dirty access of each table type, indexes, counters, argument errors, schema changes,schema/1's printout, error descriptions, and stopping and restarting.
Clause