Examples › Database Examples
database_replication_6x
Legacy: examples_database/replication_6x/repl6_writer.cpp, examples_database/replication_6x/repl6_check.cpp · Modern: examples_modern/database/replication_6x/modern.cpp
Modern equivalent of repl6_writer (primary) and repl6_check (copy): a 6.x program replicating its records with the DataReel 7.x object replication (gxv7ObjRepl, dr7features.h). One program has both roles, and a self test runs the copy in a std::jthread and the primary in main() over 127.0.0.1 with mutual TLS. The modern parts:
- The record is a trivially copyable struct (std::array for the station name) with its layout fixed by static_assert, so it stays byte compatible with the legacy programs' records.
- Ids are a std::vector, not new[]/delete[]; every gxv7ObjRepl error becomes an exception carrying Error(), so one try/catch replaces the "printf; delete[] ids; return 1" after each call.
- A batch is committed by an RAII guard that rolls back if the batch is left early.
- The copy stops through Stop() from the main thread (no signal handler needed in the self test); std::jthread joins it.
Usage: modern primary ROOT CONF RECORDS | copy ROOT CONF | selftest CERTDIR (CERTDIR holds ca.pem, primary.pem/.key and copy.pem/.key with CNs objrepl-primary and objrepl-copy, as run_repl6_cross.sh makes them)
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| gxString / UString | std::string, std::string_view | C++98 / C++17 | string_view looks at text without copying it. |
| Atoi(), Atol(), Atof(), atoi() | std::from_chars() into std::optional<T>; std::stoi() | C++17 | Overflow and junk are reported, not turned into 0. |
| MemoryBuffer | std::vector<unsigned char> or std::vector<std::byte>; std::span for views | C++98 / C++17 / C++20 | std::search finds a byte pattern; std::fill for MemSet(). |
| strcpy(), strncpy(), memmove() into char arrays | std::string; std::array<char, N> + string_view::copy() | C++11 / C++17 | |
| gxDatabase | keep gxDatabase: a stack object, errors as exceptions, static_assert(std::is_trivially_copyable_v<Record>) | C++17 | The standard library has no database file; the file format is DataReel's. |
| gxv7VectorIndex, gxv7ObjRepl, gxv7ObjectClient | keep them; std::span, <random>, std::ranges for checks | C++20 | Needs DATAREEL7_FEATURES_DIR. |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_database/replication_6x/repl6_writer.cpp 84 lines
#include "gxdlcode.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "dr7features.h" #include "repl6_records.h" // digest ROOT, status ROOT, engine: the same in both programs (-1: none of them) static int folder_cmd(int argc, char **argv) { gxString line; if(argc == 2 && strcmp(argv[1], "engine") == 0) { printf("engine %s\n", gxv7ObjRepl::Engine64() ? "64-bit" : "32-bit"); return gxv7ObjRepl::Engine64() ? 0 : 1; } if(argc == 3 && strcmp(argv[1], "digest") == 0) { int rc = gxv7ObjRepl::Digest(argv[2], line); printf("%s\n", line.c_str()); return rc == 0 ? 0 : 1; } if(argc == 3 && strcmp(argv[1], "status") == 0) { int rc = gxv7ObjRepl::Status(argv[2], line); printf("%s\n", line.c_str()); return rc == 0 ? 0 : 1; } return -1; } static int primary(const char *root, const char *conf, long records) { gxv7ObjRepl p; if(p.LoadConfig(conf) != 0 || p.Open(root, gxv7ObjRepl::PRIMARY) != 0 || p.OpenDatabase(REPL6_DB) != 0) { printf("repl6_writer: %s\n", p.Error().c_str()); return 1; } unsigned long long *ids = new unsigned long long[records > 0 ? records : 1]; long adds = 0, updates = 0, removes = 0; Reading r; for(long i = 0; i < records; ) { if(p.Begin() != 0) { printf("repl6_writer: Begin: %s\n", p.Error().c_str()); delete[] ids; return 1; } for(int k = 0; k < 25 && i < records; k++, i++) { ids[i] = p.NewId(); make_reading(r, i + 1, 0); if(ids[i] == 0 || p.Put(REPL6_DB, ids[i], &r, sizeof(r)) != 0) { printf("repl6_writer: Put: %s\n", p.Error().c_str()); delete[] ids; return 1; } adds++; if(i % 7 == 6) { // an update of an earlier record make_reading(r, i - 5, 1); if(p.Put(REPL6_DB, ids[i - 6], &r, sizeof(r)) != 0) { printf("repl6_writer: update: %s\n", p.Error().c_str()); delete[] ids; return 1; } updates++; } if(i % 11 == 10 && (i - 3) % 7 != 0) { // a remove (the id stays as a // tombstone), never of one updated later if(p.Remove(REPL6_DB, ids[i - 3]) != 0) { printf("repl6_writer: Remove: %s\n", p.Error().c_str()); delete[] ids; return 1; } removes++; } } if(p.Commit() != 0) { printf("repl6_writer: Commit: %s\n", p.Error().c_str()); delete[] ids; return 1; } p.Pump(); // The copy may be away: Drain() below waits for it } delete[] ids; int rc = p.Drain(120); printf("repl6_writer: %ld adds, %ld updates, %ld removes, last_seq %llu, copy has %llu (%s)\n", adds, updates, removes, p.LastSeq(), p.CopyApplied(), rc == 0 ? "drained" : "not drained"); if(rc != 0) printf("repl6_writer: %s\n", p.Error().c_str()); p.Close(); return rc == 0 ? 0 : 2; } int main(int argc, char **argv) { int rc = folder_cmd(argc, argv); if(rc >= 0) return rc; if(argc == 5 && strcmp(argv[1], "primary") == 0) return primary(argv[2], argv[3], atol(argv[4])); fprintf(stderr, "usage: repl6_writer primary ROOT CONF RECORDS | digest ROOT | status ROOT | engine\n"); return 64; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_database/replication_6x/repl6_check.cpp 126 lines
#include "gxdlcode.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <atomic> #include <chrono> #include <thread> #if defined(__WIN32__) || defined(_WIN32) #include <windows.h> #include <io.h> #define access _access #define F_OK 0 #else #include <unistd.h> #endif #include "dr7features.h" #include "repl6_records.h" // digest ROOT, status ROOT, engine: the same in both programs (-1: none of them) static int folder_cmd(int argc, char **argv) { gxString line; if(argc == 2 && strcmp(argv[1], "engine") == 0) { printf("engine %s\n", gxv7ObjRepl::Engine64() ? "64-bit" : "32-bit"); return gxv7ObjRepl::Engine64() ? 0 : 1; } if(argc == 3 && strcmp(argv[1], "digest") == 0) { int rc = gxv7ObjRepl::Digest(argv[2], line); printf("%s\n", line.c_str()); return rc == 0 ? 0 : 1; } if(argc == 3 && strcmp(argv[1], "status") == 0) { int rc = gxv7ObjRepl::Status(argv[2], line); printf("%s\n", line.c_str()); return rc == 0 ? 0 : 1; } return -1; } static gxv7ObjRepl *serving = 0; static void on_signal(int) { if(serving) serving->Stop(); } #if defined(__WIN32__) || defined(_WIN32) static BOOL WINAPI on_ctrl(DWORD) { if(serving) serving->Stop(); return TRUE; } #endif static int copy(const char *root, const char *conf, int check) { gxv7ObjRepl c; if(c.LoadConfig(conf) != 0 || c.Open(root, gxv7ObjRepl::COPY) != 0) { printf("repl6_check: %s\n", c.Error().c_str()); return 1; } serving = &c; signal(SIGINT, on_signal); signal(SIGTERM, on_signal); #if defined(__WIN32__) || defined(_WIN32) SetConsoleCtrlHandler(on_ctrl, TRUE); #endif // ROOT/objrepl.stop (any platform): stop within a second gxString stopf(root); stopf << "/objrepl.stop"; remove(stopf.c_str()); std::atomic<int> done(0); std::thread watch([&]() { while(!done) { if(access(stopf.c_str(), F_OK) == 0) { c.Stop(); remove(stopf.c_str()); break; } std::this_thread::sleep_for(std::chrono::milliseconds(500)); } }); printf("repl6_check: serving %s\n", root); fflush(stdout); int rc = c.Serve(); done = 1; watch.join(); serving = 0; if(rc != 0) printf("repl6_check: %s\n", c.Error().c_str()); printf("repl6_check: applied_seq %llu epoch %llu\n", c.AppliedSeq(), c.Epoch()); if(check) { unsigned long long *ids = 0; unsigned long n = 0, bad = 0; if(c.Ids(REPL6_DB, ids, n) != 0) { printf("repl6_check: Ids: %s\n", c.Error().c_str()); rc = -1; } // With a "station" index in CONF (index station:readings:B:0:16, the // copy's own B-tree on the station name): each record is found by // its station with FindKey() unsigned long found = 0, missed = 0; int have_index = 0; for(unsigned long i = 0; i < n; i++) { MemoryBuffer b; if(c.Get(REPL6_DB, ids[i], b) != 0 || !reading_ok(b)) { bad++; continue; } Reading r; memcpy(&r, b.m_buf(), sizeof(r)); unsigned long long hits[256]; unsigned count = 0; if(c.FindKey("station", r.station, sizeof(r.station), hits, 256, count) != 0) continue; have_index = 1; int in = 0; for(unsigned k = 0; k < count && k < 256; k++) if(hits[k] == ids[i]) in = 1; if(in) found++; else missed++; } delete[] ids; printf("repl6_check: %lu live records, %lu with a bad CRC or unreadable\n", n, bad); if(have_index) { printf("repl6_check: station index: %lu records found by FindKey(), %lu not found\n", found, missed); if(missed) bad++; } if(bad) rc = -1; } c.Close(); return rc == 0 ? 0 : 1; } int main(int argc, char **argv) { int rc = folder_cmd(argc, argv); if(rc >= 0) return rc; if((argc == 4 || argc == 5) && strcmp(argv[1], "copy") == 0) return copy(argv[2], argv[3], argc == 5 && strcmp(argv[4], "--check") == 0); fprintf(stderr, "usage: repl6_check copy ROOT CONF [--check] | digest ROOT | status ROOT | engine\n"); return 64; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_database/replication_6x/repl6_records.h 45 lines
#ifndef __REPL6_RECORDS_H__ #define __REPL6_RECORDS_H__ #include <string.h> #include "gxstring.h" #include "gxcrc32.h" #include "membuf.h" // One station reading, a plain 6.x record. The CRC covers the bytes // before it. struct Reading { char station[16]; long long seq; double value; unsigned int day; unsigned int crc; }; static const char *REPL6_DB = "readings"; static inline void make_reading(Reading &r, long long seq, int version) { memset(&r, 0, sizeof(r)); gxString s; s << "KST" << (int)(seq % 97); strncpy(r.station, s.c_str(), sizeof(r.station) - 1); r.seq = seq; r.value = (double)seq * 0.25 + version; r.day = 20261117 + (unsigned)(seq % 3); r.crc = (unsigned int)calcCRC32((const char *)&r, (unsigned)((char *)&r.crc - (char *)&r)); } static inline int reading_ok(const MemoryBuffer &b) { if(b.length() != sizeof(Reading)) return 0; Reading r; memcpy(&r, b.m_buf(), sizeof(r)); return r.crc == (unsigned int)calcCRC32((const char *)&r, (unsigned)((char *)&r.crc - (char *)&r)); } #endif // __REPL6_RECORDS_H__ // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++20)
examples_modern/database/replication_6x/modern.cpp 171 lines
#include <array> #include <chrono> #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <filesystem> #include <iostream> #include <stdexcept> #include <string> #include <thread> #include <type_traits> #include <utility> #include <vector> #include "dr7features.h" #include "gxcrc32.h" #include "membuf.h" struct Reading { // Same bytes as repl6_records.h std::array<char, 16> station{}; long long seq = 0; double value = 0; unsigned int day = 0; unsigned int crc = 0; }; static_assert(std::is_trivially_copyable_v<Reading>); static_assert(sizeof(Reading) == 40 && offsetof(Reading, crc) == 36); constexpr const char *DB = "readings"; unsigned int crc_of(const Reading &r) { return (unsigned int)calcCRC32(reinterpret_cast<const char *>(&r), unsigned(offsetof(Reading, crc))); } Reading make_reading(long long seq, int version) { Reading r; std::string s = "KST" + std::to_string(seq % 97); s.copy(r.station.data(), r.station.size() - 1); r.seq = seq; r.value = double(seq) * 0.25 + version; r.day = 20261117u + unsigned(seq % 3); r.crc = crc_of(r); return r; } void ok(gxv7ObjRepl &p, int rv, const char *what) { if(rv != 0) throw std::runtime_error(std::string(what) + ": " + p.Error().c_str()); } class Batch { // Commit, or roll back if left early public: explicit Batch(gxv7ObjRepl &p) : p_(p) { ok(p_, p_.Begin(), "Begin"); } void commit() { ok(p_, p_.Commit(), "Commit"); done_ = true; } ~Batch() { if(!done_) p_.Rollback(); } private: gxv7ObjRepl &p_; bool done_ = false; }; int primary(gxv7ObjRepl &p, long records) { ok(p, p.OpenDatabase(DB), "OpenDatabase"); std::vector<unsigned long long> ids; for(long i = 0; i < records;) { Batch batch(p); for(int k = 0; k < 25 && i < records; k++, i++) { unsigned long long id = p.NewId(); if(id == 0) throw std::runtime_error("NewId: " + std::string(p.Error().c_str())); Reading r = make_reading(i + 1, 0); ok(p, p.Put(DB, id, &r, sizeof r), "Put"); ids.push_back(id); } batch.commit(); p.Pump(); } int rc = p.Drain(60); std::cout << "primary: " << ids.size() << " records, last_seq " << p.LastSeq() << ", copy has " << p.CopyApplied() << (rc == 0 ? " (drained)\n" : " (not drained)\n"); return rc; } int check_copy(gxv7ObjRepl &c) { unsigned long long *raw = nullptr; unsigned long count = 0; if(c.Ids(DB, raw, count) != 0) return -1; std::vector<unsigned long long> ids(raw, raw + count); // Own the array delete[] raw; int bad = 0; for(auto id : ids) { MemoryBuffer b; Reading r; if(c.Get(DB, id, b) != 0 || b.length() != sizeof r) { bad++; continue; } std::memcpy(&r, b.m_buf(), sizeof r); bad += r.crc != crc_of(r); } std::cout << "copy: " << ids.size() << " records, " << bad << " bad\n"; return bad ? -1 : int(ids.size()); } int main(int argc, char **argv) { try { const std::string mode = argc > 1 ? argv[1] : ""; if(mode == "primary" && argc == 5) { gxv7ObjRepl p; ok(p, p.LoadConfig(argv[3]), "LoadConfig"); ok(p, p.Open(argv[2], gxv7ObjRepl::PRIMARY), "Open"); return primary(p, std::atol(argv[4])) == 0 ? 0 : 2; } if(mode == "copy" && argc == 4) { gxv7ObjRepl c; ok(c, c.LoadConfig(argv[3]), "LoadConfig"); ok(c, c.Open(argv[2], gxv7ObjRepl::COPY), "Open"); return c.Serve(); } if(mode == "selftest" && argc == 3) { namespace fs = std::filesystem; const fs::path certs = argv[2]; fs::remove_all("modern_r_primary"); fs::remove_all("modern_r_copy"); const std::string port = "47391"; gxv7ObjRepl copy; for(auto [k, v] : {std::pair{"name", "copy1"}, {"peer-name", "primary1"}}) copy.SetConfig(k, v); copy.SetConfig("listen", ("127.0.0.1:" + port).c_str()); copy.SetConfig("ca", (certs / "ca.pem").string().c_str()); copy.SetConfig("cert", (certs / "copy.pem").string().c_str()); copy.SetConfig("key", (certs / "copy.key").string().c_str()); copy.SetConfig("allow-cn", "objrepl-primary"); ok(copy, copy.Open("modern_r_copy", gxv7ObjRepl::COPY), "copy Open"); std::jthread server([©] { copy.Serve(); }); std::this_thread::sleep_for(std::chrono::milliseconds(300)); int rc; { gxv7ObjRepl p; p.SetConfig("name", "primary1"); p.SetConfig("peer-name", "copy1"); p.SetConfig("copy", ("127.0.0.1:" + port).c_str()); p.SetConfig("ca", (certs / "ca.pem").string().c_str()); p.SetConfig("cert", (certs / "primary.pem").string().c_str()); p.SetConfig("key", (certs / "primary.key").string().c_str()); ok(p, p.Open("modern_r_primary", gxv7ObjRepl::PRIMARY), "primary Open"); rc = primary(p, 200); p.Close(); } copy.Stop(); // Serve() returns server.join(); int n = check_copy(copy); copy.Close(); fs::remove_all("modern_r_primary"); fs::remove_all("modern_r_copy"); return (rc == 0 && n == 200) ? 0 : 1; } } catch(const std::exception &e) { std::cout << "objrepl error: " << e.what() << "\n"; return 1; } std::cout << "usage: " << argv[0] << " primary ROOT CONF RECORDS | copy ROOT CONF | selftest CERTDIR\n"; return 64; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Build and run
cmake -S examples_modern -B build-modern -DDATAREEL7_FEATURES_DIR=/path/to/datareel-7.4 -DCMAKE_CXX_STANDARD=20 cmake --build build-modern --target database_replication_6x ./build-modern/database_replication_6x
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
objrepl: copy listening on 127.0.0.1:47391 (gxStream, TLS, client CN objrepl-primary), applied 0, epoch 1 primary: 200 records, last_seq 8, copy has 8 (drained) copy: 200 records, 0 bad