Object Replication Class
gxObjRepl replicates objects between two independent object databases over gxStream with TLS, between Windows and Linux nodes in both directions: only objects travel, never file pages, and each node keeps its own addresses and indexes (DataReel 7.4).
Overview
Windows and Linux
Files in a Node
Roles, Epochs and Checks
Limits
The Journal and the Lock
The objrepl Tool and Checks
Configuration
Open and Close
Primary: Changes
Replication
Reads
gxObjReplReader: reads from another process (7.4.1)
Folders (no open node)
Overview
A node is a folder (ROOT). The primary takes the application's changes in transactions: Begin(), Put(), Remove(), Purge(), Commit(). A commit is durable on the primary when Commit() returns: its objects, their indexes, an outbox entry and the node's state are written in one gxdJournal transaction. Pump() sends the copy what it does not have and drops outbox entries the copy has acknowledged. The copy runs Serve(): it applies each commit in one transaction of its own, reads every object back and compares it with what was sent, and acknowledges only what is durable.
Objects are found by a 64-bit id both nodes share. A remove leaves a tombstone where the object was, so links to it still resolve and its address is never reused; Purge() frees a tombstone (refused while a live link names it). A link is an 8-byte file address inside an object at an offset the link map names (DB:OFFSET:TARGET_DB); links travel as ids and each node stores its own addresses. An object that grows moves and leaves a forwarding stub, so links to the old address still work.
Indexes are each node's own (index): B-tree indexes on up to 32 bytes at an offset and vector indexes (gxVectorIndex) on floats at an offset, kept in the same transaction as the objects. A copy may have indexes the primary does not.
gxObjReplConfig cfg;
cfg.Load("primary/objrepl.conf"); // ca, cert, key, copy, links, index ...
gxObjRepl p;
if(p.Open("primary", cfg, gxObjRepl::PRIMARY) != 0) printf("%s\n", p.Error().c_str());
p.OpenDatabase("events"); // before Begin()
p.Begin();
uint64_t id = p.NewId();
p.Put("events", id, &rec, sizeof(rec));
p.Commit(); // durable here, waiting in the outbox
p.Pump(); // 0: the copy has every commit
gxObjRepl c; // the copy (another process or machine)
c.Open("copy", cfg_copy, gxObjRepl::COPY);
c.Serve(); // until Stop() (signal-safe) or Close()
Windows and Linux
Object replication between Windows and Linux is new in DataReel 7.4 (beta 5):
- Mixed Windows and Linux nodes replicate both ways, with the primary on either side. Takeover() and Rejoin() work across the platforms: a Windows copy can take over from a Linux primary, and the Linux node rejoins as its copy (and the other way round).
- One canonical 32-byte gxStream block header on every platform (the form 64-bit Linux always sent), so the frames are the same bytes on both.
- A peer that sends the old header with 4-byte words (Windows and 32-bit builds from before beta 5) is refused with gxSOCKET_BLOCKHEADER_ERROR (PeerOldHeader()) and an alarm. Older 64-bit Linux builds always sent the canonical header.
- TLS uses each platform's own TLS library through gxSSL, with mutual certificates: OpenSSL on Linux, the Windows Schannel library on Windows. A Schannel build checks the certificates' dates, CA and key at the TLS handshake rather than at Open().
- From DataReel 6.4, programs built with the matching stream header can talk to 7.4 replication.
- Upgrade: every node must run a 7.4 build (7.4 beta 5 or later).
Tested Linux to Windows and Windows to Linux: takeover and rejoin with identical object and index digests in every run, a 2,500-commit stress run each way, and old Windows builds refused both ways. The objrepl tool stops on TERM/INT (POSIX), Ctrl+C or Ctrl+Break (Windows), or when ROOT/objrepl.stop appears.
Files in a Node
<db>.gxd and <db>.id.btx (each database: the objects and the id index), <db>.<name>.ix.btx / .vix with a .def file (the node's indexes), state.gxd (role, epoch, sequence numbers, digests), outbox.gxd (primary), digests.btx (the running digest after each commit, the last 1,000,000 kept), node.jnl (the journal over all of them), objrepl.lock (held while the node is open: one process per node), objrepl.status (a running node's status) and objrepl.alarm (why a stream was refused). During a full send the old data waits in prev/ until the new copy is whole.
Roles, Epochs and Checks
Each node has a role and an epoch. When the primary connects, both sides check names, roles, the epoch, the sequence number and a running digest of every commit: a copy refuses an older epoch, a primary whose history differs from its own (the digest at the copy's sequence number) is refused, and every refusal writes an alarm. Once the primary accepts the copy it sends its epoch first, and the copy saves it, fencing older primaries out. A copy that is behind gets what it misses from the outbox, or a full send of every database when the outbox no longer has it; the full send ends only when the copy has received exactly what was sent (a count and a hash).
Takeover (Takeover(), the node stopped) makes a copy the primary at the next epoch. Rejoin (Rejoin()) makes a former primary a copy again: if its copy had acknowledged every commit (a planned switchover) it follows on with no full send; otherwise it gets a full send from the new primary.
New ids carry the epoch (epoch << 40 plus a counter), so a new primary never hands out an id the old one may have used in commits that never reached it.
Limits
- Asynchronous: a commit is durable on the primary when Commit() returns and on the copy when Pump() returns 0. If the primary is lost, the commits the copy did not have are lost with it (the primary's status shows them as lag_seq); after a crash failover the old primary's Rejoin() counts them (dropped_at_rejoin).
- Trust: a peer whose certificate the copy accepts (allow-cn) is trusted with the stream: it can raise the copy's epoch, which fences other primaries out, or send a full send. Protect the certificates and keys.
- An object is at most 32 MB and a commit's changes at most 60 MB (one gxStream block is 64 MB).
- A copy further behind than the digest log's 1,000,000 commits, or whose history a primary cannot check, is refused: Rejoin() on it makes it take a full send.
- Threads: every call takes one lock in the object; readers (Get, FindKey, Nearest ...) run between the frames Serve() applies. See The Journal and the Lock. While a copy receives a full send, reads fail with "a full send is under way".
- Startup: Open() of a node with many databases opens them (and builds any missing index) under the lock, so readers wait for it once, at startup.
- Full send: a copy's SNAP_BEGIN still holds the lock while it sets the old data aside, but readers fail at once ("a full send is under way") rather than wait for it.
- A commit that fails on a journal sync error may still survive recovery: after such an error, read the object back before counting on either outcome.
- With the 32-bit engine each database file is limited to 2 GB (FAU_t); 1M-object stores need the 64-bit engine. Mixed 32/64-bit nodes replicate. Not tested: a 32-bit Windows build.
- The property test (prop_objrepl) and the wire fuzzer (fuzz_objrepl) are POSIX only (fork); the API test, the objrepl tool and the test scripts run on Windows and Linux.
- Index fields may not overlap link fields.
- Stopping: a close on a saturated disk can take minutes: the journal checkpoint syncs every file. The status file says "stopping" (with stopping_since) until the close is done, then "stopped" with close_secs;
objrepl checkreports a "stopping" longer than 10 s as WARN, and a node that died while closing as WARN (the next open recovers), never FAIL. - Platforms: see Windows and Linux.
The Journal and the Lock
Each node writes through one gxdJournal in write-back mode (ROOT/node.jnl): a commit's pages reach the files only after its batch is durable in the journal, as in a write-through commit. That lets the journal sync run without the node's lock: Commit() puts the batch in the journal with the lock held, syncs the journal file by its own handle with the lock given up (on Windows a second handle and FlushFileBuffers), then writes the batch's pages (WriteCommitted()) with the lock held again. Checkpoints sync the files the same way (CheckpointBegin() / CheckpointEnd()). Begin(), Close() and a soft checkpoint wait until no commit's sync is running.
The lock is one recursive mutex per node. Pump() gives it up for its network I/O and readers run in between; Serve() takes it per frame it applies. A test build (-DGXREPL_TEST_HOOKS=ON) with OBJREPL_TEST_HOLD_MS=N set prints every hold of the lock of N ms or more on stderr, by phase ("objrepl hold: PHASE MS ms"), so a wait a reader sees can be traced to what held the lock. Release builds have no such output.
The objrepl Tool and Checks
The objrepl tool (utils/objrepl/objrepl.cpp) runs a node from the command line and from ROOT/objrepl.conf: objrepl copy ROOT, objrepl digest|ixcheck|status|check|clear-alarm|takeover|rejoin ROOT, and (7.5 beta 3) objrepl swap OLD NEW. objrepl check prints one line, OK / WARN / FAIL (exit 0 / 1 / 2), for cron or a monitor. utils/objrepl/objrepl_certs.sh makes a private CA and the two node certificates.
Configuration
struct gxObjReplConfig { name, peer_name, ca, cert, key, allow_cn, copy, listen_addr, listen_port, links, index, trim, idle_timeout, ack_timeout, max_lag, max_behind, min_cert_days, log }name and peer_name: this node and the expected peer; ca, cert, key: TLS with certificates on both sides; allow_cn: the CN of the primary's client certificate (copy); copy: HOST[:PORT] (primary; port 2073 when none is given, 7.4.1); listen_addr/listen_port (copy; 127.0.0.1 and 2073, the registered gxStream port, by default, 7.4.1); links: "DB:OFFSET:TARGET_DB,..."; index: "NAME:DB:B:OFFSET:LEN" or "NAME:DB:V:OFFSET:DIM", comma separated; idle_timeout: seconds without a frame before the copy drops a connection (120); ack_timeout: seconds one frame and the copy's answer may take in all before the primary drops the connection and Pump() returns (300, 7.4.1); log: where messages go (stderr).
bool Set(const std::string &key, const std::string &value, std::string *why = 0) / bool Load(const std::string &fname, std::string *why = 0)One "key value" setting (name, peer-name, copy, listen, ca, cert, key, allow-cn, links, index, max-lag, max-behind, min-cert-days, trim, idle-timeout, ack-timeout), or a file of them (# comments). False and why for an unknown key or a bad value.
Open and Close
int Open(const std::string &root, const gxObjReplConfig &cfg, Role role)Opens ROOT (created if new) as PRIMARY or COPY. Checks the config and the certificates (readable, the key not readable by others, within their dates, signed by the CA, key and certificate matching). Returns 0; -1 with Error(); 4 when ROOT has the other role.
void Close() / int IsOpen() const / std::string Error() constCloses (stopping a Serve() running in another thread first); whether open; the last error.
Primary: Changes
int OpenDatabase(const std::string &db)Opens or creates a database before Begin() (the journal attaches files only between transactions).
int Begin() / int Commit() / int Rollback()A transaction. Commit() makes it durable with its outbox entry; a failed Commit() leaves nothing.
uint64_t NewId()An id no database here has used, with the epoch in the high bits.
int Put(const std::string &db, uint64_t id, const void *bytes, uint32_t n)An add, or an update of a live object or a tombstone. Link fields hold this node's addresses (AddressOf()).
int Remove(const std::string &db, uint64_t id) / int Purge(const std::string &db, uint64_t id)A remove leaves a tombstone (an unknown id gets one); a purge frees a tombstone no live link names.
Replication
int Pump()Primary: connect if needed (with the checks), send what the copy lacks (or a full send), drop acknowledged outbox entries. 0: the copy has every commit; 1: away or behind; 3: refused (alarm).
int Drain(int seconds)Primary: Pump() until the copy has every commit. 0, 2 (not drained) or 3 (refused).
int Serve() / void Stop()Copy: accept primaries and apply until Stop() (async-signal-safe; Serve() returns within half a second).
Reads
int Get(const std::string &db, uint64_t id, std::vector<unsigned char> &bytes) / int IsLive(...)A live object's bytes (links as this node's addresses); whether it is live.
FAU_t AddressOf(const std::string &db, uint64_t id) / uint64_t IdAt(const std::string &db, FAU_t a)An object's address here, and the id at an address (for link fields).
std::vector<uint64_t> Ids(const std::string &db, Which which = LIVE) / std::vector<std::string> Databases()The live ids or the tombstones of a database; the databases open here.
int FindKey(const std::string &index, const void *key, unsigned n, std::vector<uint64_t> &ids) / int Nearest(const std::string &index, const float *query, unsigned k, std::vector<gxObjReplHit> &hits)This node's indexes: the ids whose key starts with KEY, or the K nearest vectors.
int InSnapshot() / uint64_t Epoch() / LastSeq() / AppliedSeq() / CopyApplied() / long Snapshots()A copy inside a full send; the epoch; the primary's last commit, the copy's last applied one, the copy as last heard; full sends made.
gxObjReplReader: reads from another process (7.4.1)
int Open(const std::string &root, const std::string &index = "") / void Close()A node folder, read only, while the node runs in another process (or none runs). INDEX: the node's index spec, for FindKey() and Nearest(). Takes no node lock: the node keeps running and a second node still cannot open the folder.
int Get(...) / int IsLive(...) / int Ids(const std::string &db, std::vector<uint64_t> &ids, gxObjRepl::Which which = gxObjRepl::LIVE) / int Databases(std::vector<std::string> &dbs)As gxObjRepl's reads. Each call reads under the node journal's shared lock (the node takes it only while it writes a batch's pages), so it sees whole commits only, and opens and closes the files it needs. -1 with Error() when the node cannot be read now (a full send, a database being created): try again.
int FindKey(...) / int Nearest(...) / void ReleaseVectors()Index reads. Nearest() keeps the vector index in memory and reads it again when the node has moved on; ReleaseVectors() closes it (on Windows an open index file can make a copy's full send fail).
uint64_t Seq() / Epoch() / int Role() / int Refresh()The commit the last call read (a primary's last commit, a copy's applied one), the epoch, the role; Refresh() reads the state now.
Folders (no open node)
static int Digest(const std::string &root, const std::string &links, std::string &line, std::string *detail = 0)"objects N digest H": ids and contents with links as ids, equal on two nodes holding the same objects.
static int IndexCheck(const std::string &root, const std::string &index, std::string &report)Each index against entries rebuilt from the objects, and a digest of its contents. 0 consistent, 5 not.
static int Check(const std::string &root, const gxObjReplConfig &cfg, std::string &line) / static int Status(...) / static int ClearAlarm(...)OK / WARN / FAIL from the status and alarm files (0, 1, 2); the state; an alarm acknowledged.
static int Takeover(const std::string &root, std::string &msg) / static int Rejoin(const std::string &root, std::string &msg)A stopped copy becomes primary at the next epoch; a former primary (or a copy) becomes a copy again, with a full send unless every commit was acknowledged.