init: Pass reference to ArgsManager around instead of relying on global

pull/764/head
MarcoFalke 4 years ago
parent 197450f808
commit fa40017706
No known key found for this signature in database
GPG Key ID: CE2B75697E69A548

@ -50,11 +50,9 @@ static bool AppInit(int argc, char* argv[])
util::ThreadSetInternalName("init"); util::ThreadSetInternalName("init");
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
SetupServerArgs(node); SetupServerArgs(node);
ArgsManager& args = *Assert(node.args);
std::string error; std::string error;
if (!gArgs.ParseParameters(argc, argv, error)) { if (!gArgs.ParseParameters(argc, argv, error)) {
return InitError(Untranslated(strprintf("Error parsing command line arguments: %s\n", error))); return InitError(Untranslated(strprintf("Error parsing command line arguments: %s\n", error)));
@ -109,15 +107,13 @@ static bool AppInit(int argc, char* argv[])
// -server defaults to true for bitcoind but not for the GUI so do this here // -server defaults to true for bitcoind but not for the GUI so do this here
gArgs.SoftSetBoolArg("-server", true); gArgs.SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console // Set this early so that parameter interactions go to console
InitLogging(); InitLogging(args);
InitParameterInteraction(); InitParameterInteraction(args);
if (!AppInitBasicSetup()) if (!AppInitBasicSetup(args)) {
{
// InitError will have been called with detailed error, which ends up on console // InitError will have been called with detailed error, which ends up on console
return false; return false;
} }
if (!AppInitParameterInteraction()) if (!AppInitParameterInteraction(args)) {
{
// InitError will have been called with detailed error, which ends up on console // InitError will have been called with detailed error, which ends up on console
return false; return false;
} }

@ -107,14 +107,14 @@ static const char* DEFAULT_ASMAP_FILENAME="ip_asn.map";
*/ */
static const char* BITCOIN_PID_FILENAME = "bitcoind.pid"; static const char* BITCOIN_PID_FILENAME = "bitcoind.pid";
static fs::path GetPidFile() static fs::path GetPidFile(const ArgsManager& args)
{ {
return AbsPathForConfigVal(fs::path(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME))); return AbsPathForConfigVal(fs::path(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME)));
} }
NODISCARD static bool CreatePidFile() NODISCARD static bool CreatePidFile(const ArgsManager& args)
{ {
fsbridge::ofstream file{GetPidFile()}; fsbridge::ofstream file{GetPidFile(args)};
if (file) { if (file) {
#ifdef WIN32 #ifdef WIN32
tfm::format(file, "%d\n", GetCurrentProcessId()); tfm::format(file, "%d\n", GetCurrentProcessId());
@ -123,7 +123,7 @@ NODISCARD static bool CreatePidFile()
#endif #endif
return true; return true;
} else { } else {
return InitError(strprintf(_("Unable to create the PID file '%s': %s"), GetPidFile().string(), std::strerror(errno))); return InitError(strprintf(_("Unable to create the PID file '%s': %s"), GetPidFile(args).string(), std::strerror(errno)));
} }
} }
@ -180,6 +180,7 @@ void Shutdown(NodeContext& node)
TRY_LOCK(g_shutdown_mutex, lock_shutdown); TRY_LOCK(g_shutdown_mutex, lock_shutdown);
if (!lock_shutdown) return; if (!lock_shutdown) return;
LogPrintf("%s: In progress...\n", __func__); LogPrintf("%s: In progress...\n", __func__);
Assert(node.args);
/// Note: Shutdown() must be able to handle cases in which initialization failed part of the way, /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
/// for example if the data directory was found to be locked. /// for example if the data directory was found to be locked.
@ -230,7 +231,7 @@ void Shutdown(NodeContext& node)
node.connman.reset(); node.connman.reset();
node.banman.reset(); node.banman.reset();
if (::mempool.IsLoaded() && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) { if (::mempool.IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
DumpMempool(::mempool); DumpMempool(::mempool);
} }
@ -301,19 +302,19 @@ void Shutdown(NodeContext& node)
GetMainSignals().UnregisterBackgroundSignalScheduler(); GetMainSignals().UnregisterBackgroundSignalScheduler();
globalVerifyHandle.reset(); globalVerifyHandle.reset();
ECC_Stop(); ECC_Stop();
node.args = nullptr;
node.mempool = nullptr; node.mempool = nullptr;
node.chainman = nullptr; node.chainman = nullptr;
node.scheduler.reset(); node.scheduler.reset();
try { try {
if (!fs::remove(GetPidFile())) { if (!fs::remove(GetPidFile(*node.args))) {
LogPrintf("%s: Unable to remove PID file: File does not exist\n", __func__); LogPrintf("%s: Unable to remove PID file: File does not exist\n", __func__);
} }
} catch (const fs::filesystem_error& e) { } catch (const fs::filesystem_error& e) {
LogPrintf("%s: Unable to remove PID file: %s\n", __func__, fsbridge::get_filesystem_error_message(e)); LogPrintf("%s: Unable to remove PID file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
} }
node.args = nullptr;
LogPrintf("%s: done\n", __func__); LogPrintf("%s: done\n", __func__);
} }
@ -372,7 +373,7 @@ void SetupServerArgs(NodeContext& node)
node.args = &gArgs; node.args = &gArgs;
ArgsManager& argsman = *node.args; ArgsManager& argsman = *node.args;
SetupHelpOptions(gArgs); SetupHelpOptions(argsman);
argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN); const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
@ -684,7 +685,7 @@ static void CleanupBlockRevFiles()
} }
} }
static void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImportFiles) static void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImportFiles, const ArgsManager& args)
{ {
const CChainParams& chainparams = Params(); const CChainParams& chainparams = Params();
ScheduleBatchPriority(); ScheduleBatchPriority();
@ -780,6 +781,7 @@ static bool InitSanityCheck()
static bool AppInitServers(const util::Ref& context, NodeContext& node) static bool AppInitServers(const util::Ref& context, NodeContext& node)
{ {
const ArgsManager& args = *Assert(node.args);
RPCServer::OnStarted(&OnRPCStarted); RPCServer::OnStarted(&OnRPCStarted);
RPCServer::OnStopped(&OnRPCStopped); RPCServer::OnStopped(&OnRPCStopped);
if (!InitHTTPServer()) if (!InitHTTPServer())
@ -794,7 +796,7 @@ static bool AppInitServers(const util::Ref& context, NodeContext& node)
} }
// Parameter interaction based on rules // Parameter interaction based on rules
void InitParameterInteraction() void InitParameterInteraction(ArgsManager& args)
{ {
// when specifying an explicit binding address, you want to listen on it // when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified // even when -connect or -proxy is specified
@ -863,7 +865,7 @@ void InitParameterInteraction()
* Note that this is called very early in the process lifetime, so you should be * Note that this is called very early in the process lifetime, so you should be
* careful about what global state you rely on here. * careful about what global state you rely on here.
*/ */
void InitLogging() void InitLogging(const ArgsManager& args)
{ {
LogInstance().m_print_to_file = !gArgs.IsArgNegated("-debuglogfile"); LogInstance().m_print_to_file = !gArgs.IsArgNegated("-debuglogfile");
LogInstance().m_file_path = AbsPathForConfigVal(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE)); LogInstance().m_file_path = AbsPathForConfigVal(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
@ -909,7 +911,7 @@ std::set<BlockFilterType> g_enabled_filter_types;
std::terminate(); std::terminate();
}; };
bool AppInitBasicSetup() bool AppInitBasicSetup(ArgsManager& args)
{ {
// ********************************************************* Step 1: setup // ********************************************************* Step 1: setup
#ifdef _MSC_VER #ifdef _MSC_VER
@ -951,7 +953,7 @@ bool AppInitBasicSetup()
return true; return true;
} }
bool AppInitParameterInteraction() bool AppInitParameterInteraction(const ArgsManager& args)
{ {
const CChainParams& chainparams = Params(); const CChainParams& chainparams = Params();
// ********************************************************* Step 2: parameter interactions // ********************************************************* Step 2: parameter interactions
@ -1247,9 +1249,10 @@ bool AppInitLockDataDirectory()
bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
{ {
const ArgsManager& args = *Assert(node.args);
const CChainParams& chainparams = Params(); const CChainParams& chainparams = Params();
// ********************************************************* Step 4a: application initialization // ********************************************************* Step 4a: application initialization
if (!CreatePidFile()) { if (!CreatePidFile(args)) {
// Detailed error printed inside CreatePidFile(). // Detailed error printed inside CreatePidFile().
return false; return false;
} }
@ -1853,7 +1856,9 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA
vImportFiles.push_back(strFile); vImportFiles.push_back(strFile);
} }
g_load_block = std::thread(&TraceThread<std::function<void()>>, "loadblk", [=, &chainman]{ ThreadImport(chainman, vImportFiles); }); g_load_block = std::thread(&TraceThread<std::function<void()>>, "loadblk", [=, &chainman, &args] {
ThreadImport(chainman, vImportFiles, args);
});
// Wait for genesis block to be processed // Wait for genesis block to be processed
{ {

@ -8,8 +8,8 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <util/system.h>
class ArgsManager;
struct NodeContext; struct NodeContext;
namespace interfaces { namespace interfaces {
struct BlockAndHeaderTipInfo; struct BlockAndHeaderTipInfo;
@ -25,21 +25,21 @@ class Ref;
void Interrupt(NodeContext& node); void Interrupt(NodeContext& node);
void Shutdown(NodeContext& node); void Shutdown(NodeContext& node);
//!Initialize the logging infrastructure //!Initialize the logging infrastructure
void InitLogging(); void InitLogging(const ArgsManager& args);
//!Parameter interaction: change current parameters depending on various rules //!Parameter interaction: change current parameters depending on various rules
void InitParameterInteraction(); void InitParameterInteraction(ArgsManager& args);
/** Initialize bitcoin core: Basic context setup. /** Initialize bitcoin core: Basic context setup.
* @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @note This can be done before daemonization. Do not call Shutdown() if this function fails.
* @pre Parameters should be parsed and config file should be read. * @pre Parameters should be parsed and config file should be read.
*/ */
bool AppInitBasicSetup(); bool AppInitBasicSetup(ArgsManager& args);
/** /**
* Initialization: parameter interaction. * Initialization: parameter interaction.
* @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @note This can be done before daemonization. Do not call Shutdown() if this function fails.
* @pre Parameters should be parsed and config file should be read, AppInitBasicSetup should have been called. * @pre Parameters should be parsed and config file should be read, AppInitBasicSetup should have been called.
*/ */
bool AppInitParameterInteraction(); bool AppInitParameterInteraction(const ArgsManager& args);
/** /**
* Initialization sanity checks: ecc init, sanity checks, dir lock. * Initialization sanity checks: ecc init, sanity checks, dir lock.
* @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @note This can be done before daemonization. Do not call Shutdown() if this function fails.

@ -71,13 +71,13 @@ public:
uint64_t getAssumedBlockchainSize() override { return Params().AssumedBlockchainSize(); } uint64_t getAssumedBlockchainSize() override { return Params().AssumedBlockchainSize(); }
uint64_t getAssumedChainStateSize() override { return Params().AssumedChainStateSize(); } uint64_t getAssumedChainStateSize() override { return Params().AssumedChainStateSize(); }
std::string getNetwork() override { return Params().NetworkIDString(); } std::string getNetwork() override { return Params().NetworkIDString(); }
void initLogging() override { InitLogging(); } void initLogging() override { InitLogging(gArgs); }
void initParameterInteraction() override { InitParameterInteraction(); } void initParameterInteraction() override { InitParameterInteraction(gArgs); }
bilingual_str getWarnings() override { return GetWarnings(true); } bilingual_str getWarnings() override { return GetWarnings(true); }
uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); } uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); }
bool baseInitialize() override bool baseInitialize() override
{ {
return AppInitBasicSetup() && AppInitParameterInteraction() && AppInitSanityChecks() && return AppInitBasicSetup(gArgs) && AppInitParameterInteraction(gArgs) && AppInitSanityChecks() &&
AppInitLockDataDirectory(); AppInitLockDataDirectory();
} }
bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override

@ -97,8 +97,8 @@ BasicTestingSetup::BasicTestingSetup(const std::string& chainName, const std::ve
SelectParams(chainName); SelectParams(chainName);
SeedInsecureRand(); SeedInsecureRand();
if (G_TEST_LOG_FUN) LogInstance().PushBackCallback(G_TEST_LOG_FUN); if (G_TEST_LOG_FUN) LogInstance().PushBackCallback(G_TEST_LOG_FUN);
InitLogging(); InitLogging(*m_node.args);
AppInitParameterInteraction(); AppInitParameterInteraction(*m_node.args);
LogInstance().StartLogging(); LogInstance().StartLogging();
SHA256AutoDetect(); SHA256AutoDetect();
ECC_Start(); ECC_Start();

Loading…
Cancel
Save