Merge branch 'fix/notarizations-lock' into dev
This commit is contained in:
+165
-27
@@ -79,6 +79,7 @@
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/interprocess/sync/file_lock.hpp>
|
||||
#include <boost/thread.hpp>
|
||||
#include <leveldb/env.h>
|
||||
#include <chrono>
|
||||
#include <wolfssl/options.h>
|
||||
#include <wolfssl/ssl.h>
|
||||
@@ -125,6 +126,152 @@ static const char* DEFAULT_ASMAP_FILENAME="asmap.dat";
|
||||
// in-memory cache the DB is opened with; the value here does not affect validation.
|
||||
static const size_t NOTARIZATION_DB_CACHE_BYTES = 100 * 1024 * 1024; // 100 MiB
|
||||
|
||||
// How long AppInit2() waits for another process to release notarizations/LOCK before it gives up and
|
||||
// runs on an in-memory notarizations DB.
|
||||
static const int NOTARIZATION_LOCK_WAIT_SECONDS = 30;
|
||||
|
||||
/**
|
||||
* Try to take <dbdir>/LOCK with LevelDB's own Env::LockFile, i.e. the same lock DB::Open takes, and
|
||||
* release it at once. ok() means the lock is free (a missing LOCK file cannot be held). Anything else
|
||||
* means it could not be taken: usually another process holds it ("Resource temporarily unavailable"),
|
||||
* but it may also be e.g. a permission error. The caller treats every non-ok status as held, and so
|
||||
* never moves or wipes the directory on its strength.
|
||||
*/
|
||||
static leveldb::Status ProbeLevelDBLock(const boost::filesystem::path& dbdir)
|
||||
{
|
||||
const boost::filesystem::path lockpath = dbdir / "LOCK";
|
||||
boost::system::error_code ec;
|
||||
if (!boost::filesystem::exists(lockpath, ec))
|
||||
return leveldb::Status::OK();
|
||||
leveldb::Env* env = leveldb::Env::Default();
|
||||
leveldb::FileLock* lock = NULL;
|
||||
leveldb::Status status = env->LockFile(lockpath.string(), &lock);
|
||||
if (status.ok())
|
||||
env->UnlockFile(lock);
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does <dbdir> hold any LevelDB data, i.e. a non-empty table (.ldb/.sst) or write-ahead log (.log)?
|
||||
* CURRENT, MANIFEST-*, LOCK and the LOG/LOG.old info logs carry no records. When in doubt (the
|
||||
* directory cannot be listed) say yes, so the caller keeps a copy.
|
||||
*/
|
||||
static bool LevelDBDirHasData(const boost::filesystem::path& dbdir)
|
||||
{
|
||||
boost::system::error_code ec;
|
||||
if (!boost::filesystem::exists(dbdir, ec))
|
||||
return ec ? true : false;
|
||||
boost::filesystem::directory_iterator it(dbdir, ec), end;
|
||||
if (ec)
|
||||
return true;
|
||||
for (; it != end; it.increment(ec)) {
|
||||
if (ec)
|
||||
return true;
|
||||
const std::string ext = it->path().extension().string();
|
||||
if (ext != ".ldb" && ext != ".sst" && ext != ".log")
|
||||
continue;
|
||||
boost::system::error_code sizeEc;
|
||||
const uintmax_t size = boost::filesystem::file_size(it->path(), sizeEc);
|
||||
if (sizeEc || size > 0)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the notarizations (dPoW) DB. It is non-essential and node-regenerable, so nothing here may fail
|
||||
* startup (previously any open failure surfaced as a spurious "Error opening block database"):
|
||||
* - LOCK cannot be taken (typically a previous dragonxd that is still exiting): wait up to
|
||||
* NOTARIZATION_LOCK_WAIT_SECONDS for it and retry; if it is still held, run this session on an
|
||||
* in-memory DB and leave the on-disk one alone.
|
||||
* - otherwise the DB is unreadable (seen: a torn snapshot, 0-byte log -> leveldb "Database I/O error"):
|
||||
* move it aside under a timestamped notarizations.corrupt-* name, never deleting an earlier copy, and
|
||||
* create a fresh one. A directory holding no data is recreated in place instead, so a persistent
|
||||
* failure (e.g. disk full) does not add another empty copy on every start. If even that fails, fall
|
||||
* back to an in-memory DB.
|
||||
* The lock is probed only after an open fails, so a holder that exits between the failed open and the
|
||||
* probe makes the probe report "free" for a DB that is fine. The DB is therefore treated as corrupt only
|
||||
* when an open fails although the probe just before that open found the lock free.
|
||||
*/
|
||||
static NotarizationDB* OpenNotarizationDB(bool fWipe)
|
||||
{
|
||||
const boost::filesystem::path ndir = GetDataDir() / "notarizations";
|
||||
std::string strError;
|
||||
bool fWaited = false; // the bounded wait for the lock has been used up
|
||||
bool fProbedFree = false; // the probe right before the last open attempt found the lock free
|
||||
int64_t nWaitStart = 0;
|
||||
while (true) {
|
||||
try {
|
||||
NotarizationDB* pdb = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe);
|
||||
if (fWaited)
|
||||
LogPrintf("%s: notarizations/LOCK released after %d s; notarizations DB opened\n", __func__, (GetTimeMillis() - nWaitStart) / 1000);
|
||||
else if (fProbedFree)
|
||||
LogPrintf("%s: notarizations DB opened on retry (notarizations/LOCK was released after the first attempt)\n", __func__);
|
||||
return pdb;
|
||||
} catch (const std::exception& e) {
|
||||
strError = e.what();
|
||||
}
|
||||
if (fProbedFree)
|
||||
break; // failed with the lock free beforehand: genuinely unreadable
|
||||
|
||||
leveldb::Status lockStatus = ProbeLevelDBLock(ndir);
|
||||
if (!lockStatus.ok()) {
|
||||
if (!fWaited) {
|
||||
LogPrintf("%s: notarizations DB failed to open (%s): notarizations/LOCK could not be taken (%s); waiting for a previous dragonxd to release notarizations/LOCK (up to %d s)\n",
|
||||
__func__, strError, lockStatus.ToString(), NOTARIZATION_LOCK_WAIT_SECONDS);
|
||||
fWaited = true;
|
||||
nWaitStart = GetTimeMillis();
|
||||
const int64_t nDeadline = nWaitStart + NOTARIZATION_LOCK_WAIT_SECONDS * 1000LL;
|
||||
while (GetTimeMillis() < nDeadline && !ShutdownRequested()) {
|
||||
MilliSleep(std::min<int64_t>(1000, std::max<int64_t>(1, nDeadline - GetTimeMillis())));
|
||||
lockStatus = ProbeLevelDBLock(ndir);
|
||||
if (lockStatus.ok())
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!lockStatus.ok()) {
|
||||
LogPrintf("%s: notarizations/LOCK still could not be taken after %d s (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n",
|
||||
__func__, (GetTimeMillis() - nWaitStart) / 1000, lockStatus.ToString());
|
||||
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
|
||||
}
|
||||
}
|
||||
// The lock is free now: open once more before calling the DB corrupt.
|
||||
fProbedFree = true;
|
||||
}
|
||||
|
||||
if (!LevelDBDirHasData(ndir)) {
|
||||
LogPrintf("%s: notarizations DB failed to open (%s) and holds no data; recreating it in place (non-fatal)\n", __func__, strError);
|
||||
try {
|
||||
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
|
||||
} catch (const std::exception& e) {
|
||||
LogPrintf("%s: could not recreate the notarizations DB (%s); using an in-memory notarizations DB for this run\n", __func__, e.what());
|
||||
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __func__, strError);
|
||||
// Move (do NOT delete) the old DB aside, so a transient open failure (fd exhaustion, disk full,
|
||||
// permissions) cannot permanently destroy notarization history. Earlier copies are kept too.
|
||||
try {
|
||||
const std::string base = ndir.string() + ".corrupt-" + DateTimeStrFormat("%Y%m%d-%H%M%S", GetTime());
|
||||
boost::filesystem::path aside(base);
|
||||
for (int i = 1; boost::filesystem::exists(aside); i++)
|
||||
aside = base + strprintf(".%d", i);
|
||||
boost::filesystem::rename(ndir, aside);
|
||||
LogPrintf("%s: moved the old notarizations DB to %s\n", __func__, aside.string());
|
||||
} catch (const std::exception& e) {
|
||||
LogPrintf("%s: could not move the notarizations DB aside (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n",
|
||||
__func__, e.what());
|
||||
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
|
||||
}
|
||||
try {
|
||||
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
|
||||
} catch (const std::exception& e) {
|
||||
LogPrintf("%s: could not recreate the notarizations DB (%s); using an in-memory notarizations DB for this run\n", __func__, e.what());
|
||||
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
CClientUIInterface uiInterface; // global UI callback dispatcher (declared extern in ui_interface.h)
|
||||
|
||||
// Shutdown
|
||||
@@ -211,9 +358,9 @@ void Shutdown()
|
||||
/// for example if the data directory was found to be locked.
|
||||
/// Be sure that anything that writes files or flushes caches only does this if the respective
|
||||
/// module was initialized.
|
||||
static char shutoffstr[128];
|
||||
sprintf(shutoffstr,"%s-shutoff","hush");
|
||||
RenameThread(shutoffstr);
|
||||
// Do not RenameThread() here: Shutdown() runs on the main thread, whose name is the process name
|
||||
// (/proc/<pid>/comm). Renaming it made 'pgrep -x dragonxd' stop matching a node that was still
|
||||
// shutting down and holding its locks, so pgrep-based restart scripts relaunched it too early.
|
||||
mempool.AddTransactionsUpdated(1);
|
||||
|
||||
if(fDebug) {
|
||||
@@ -274,6 +421,13 @@ void Shutdown()
|
||||
delete pblocktree;
|
||||
pblocktree = NULL;
|
||||
}
|
||||
// Close the notarizations DB with the other LevelDBs. It used to be left open until process
|
||||
// teardown, which made notarizations/LOCK the one LevelDB lock still held after "Shutdown: done"
|
||||
// (and after the datadir .lock was released), so a quickly restarted successor failed to open it.
|
||||
if (pnotarizations != NULL) {
|
||||
delete pnotarizations;
|
||||
pnotarizations = NULL;
|
||||
}
|
||||
}
|
||||
#ifdef ENABLE_WALLET
|
||||
if (pwalletMain)
|
||||
@@ -2075,35 +2229,19 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
|
||||
do {
|
||||
try {
|
||||
UnloadBlockIndex();
|
||||
delete pcoinsTip;
|
||||
delete pcoinsdbview;
|
||||
delete pcoinscatcher;
|
||||
delete pblocktree;
|
||||
delete pnotarizations;
|
||||
// Shutdown() deletes (and pcoinsTip: flushes) whatever is non-NULL here, so never leave
|
||||
// a pointer dangling if one of the reopens below throws.
|
||||
delete pcoinsTip; pcoinsTip = NULL;
|
||||
delete pcoinsdbview; pcoinsdbview = NULL;
|
||||
delete pcoinscatcher; pcoinscatcher = NULL;
|
||||
delete pblocktree; pblocktree = NULL;
|
||||
delete pnotarizations; pnotarizations = NULL;
|
||||
|
||||
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles);
|
||||
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
|
||||
pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
|
||||
pcoinsTip = new CCoinsViewCache(pcoinscatcher);
|
||||
try {
|
||||
pnotarizations = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fReindex);
|
||||
} catch (const std::exception& e) {
|
||||
// The notarizations (dPoW) DB is non-essential and node-regenerable. It has been seen to
|
||||
// snapshot/flush torn (0-byte log -> leveldb "Database I/O error" on reopen), which
|
||||
// previously aborted startup with a spurious "Error opening block database" and forced a
|
||||
// full resync. Wipe and recreate it instead of failing hard.
|
||||
LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __FUNCTION__, e.what());
|
||||
// Move (do NOT delete) the old DB aside, so a transient open failure (fd
|
||||
// exhaustion, disk full, permissions) cannot permanently destroy notarization
|
||||
// history. If the recreate below also fails it propagates as fatal and the old
|
||||
// data survives in notarizations.corrupt for recovery.
|
||||
{
|
||||
boost::filesystem::path ndir = GetDataDir() / "notarizations";
|
||||
boost::filesystem::remove_all(ndir.string() + ".corrupt");
|
||||
boost::filesystem::rename(ndir, ndir.string() + ".corrupt");
|
||||
}
|
||||
pnotarizations = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
|
||||
}
|
||||
pnotarizations = OpenNotarizationDB(fReindex);
|
||||
|
||||
|
||||
if (fReindex) {
|
||||
|
||||
@@ -2992,6 +2992,8 @@ static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const CO
|
||||
|
||||
void ConnectNotarizations(const CBlock &block, int height)
|
||||
{
|
||||
if (pnotarizations == NULL) // closed by Shutdown()
|
||||
return;
|
||||
NotarizationsInBlock notarizations = ScanBlockNotarizations(block, height);
|
||||
if (notarizations.size() > 0) {
|
||||
CDBBatch batch = CDBBatch(*pnotarizations);
|
||||
@@ -3004,6 +3006,8 @@ void ConnectNotarizations(const CBlock &block, int height)
|
||||
|
||||
void DisconnectNotarizations(const CBlock &block)
|
||||
{
|
||||
if (pnotarizations == NULL) // closed by Shutdown()
|
||||
return;
|
||||
NotarizationsInBlock nibs;
|
||||
if (GetBlockNotarizations(block.GetHash(), nibs)) {
|
||||
CDBBatch batch = CDBBatch(*pnotarizations);
|
||||
|
||||
+10
-1
@@ -9,7 +9,10 @@
|
||||
#include "main.h"
|
||||
#include <boost/foreach.hpp>
|
||||
|
||||
NotarizationDB *pnotarizations;
|
||||
// Owned by init: opened in AppInit2() and closed (set back to NULL) in Shutdown(), so that
|
||||
// notarizations/LOCK is released together with the other LevelDB locks. Every accessor treats NULL
|
||||
// as an empty DB, so a straggler after Shutdown() cannot dereference it.
|
||||
NotarizationDB *pnotarizations = NULL;
|
||||
NotarizationDB::NotarizationDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "notarizations", nCacheSize, fMemory, fWipe, false, 64) { }
|
||||
|
||||
NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) {
|
||||
@@ -55,11 +58,15 @@ NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) {
|
||||
}
|
||||
|
||||
bool GetBlockNotarizations(uint256 blockHash, NotarizationsInBlock &nibs) {
|
||||
if (pnotarizations == NULL)
|
||||
return false;
|
||||
return pnotarizations->Read(blockHash, nibs);
|
||||
}
|
||||
|
||||
|
||||
bool GetBackNotarization(uint256 notarizationHash, Notarization &n) {
|
||||
if (pnotarizations == NULL)
|
||||
return false;
|
||||
return pnotarizations->Read(notarizationHash, n);
|
||||
}
|
||||
|
||||
@@ -86,6 +93,8 @@ void EraseBackNotarizations(const NotarizationsInBlock notarizations, CDBBatch &
|
||||
// Scan notarizationsdb backwards for blocks containing a notarization
|
||||
// for given symbol. Return height of matched notarization or 0.
|
||||
int ScanNotarizationsDB(int height, std::string symbol, int scanLimitBlocks, Notarization& out) {
|
||||
if (pnotarizations == NULL)
|
||||
return 0;
|
||||
if (height < 0 || height > chainActive.Height())
|
||||
return false;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user