lokinet/llarp/context.cpp

601 lines
14 KiB
C++
Raw Normal View History

#include <llarp.hpp>
#include <llarp.h>
#include <config.hpp>
#include <crypto/crypto_libsodium.hpp>
2019-05-28 00:19:25 +00:00
#include <crypto/crypto_noop.hpp>
#include <dht/context.hpp>
#include <dnsd.hpp>
2019-01-11 01:19:36 +00:00
#include <ev/ev.hpp>
2019-04-14 16:08:51 +00:00
#include <metrics/metrictank_publisher.hpp>
#include <metrics/publishers.hpp>
#include <nodedb.hpp>
#include <router/router.hpp>
2019-01-11 01:19:36 +00:00
#include <util/logger.h>
2019-06-02 21:19:10 +00:00
#include <util/memfn.hpp>
#include <util/metrics.hpp>
#include <util/scheduler.hpp>
2019-04-14 16:08:51 +00:00
#include <absl/strings/str_split.h>
#include <cxxopts.hpp>
#include <signal.h>
#if(__FreeBSD__) || (__OpenBSD__) || (__NetBSD__)
#include <pthread_np.h>
#endif
namespace llarp
{
Context::Context()
{
}
Context::~Context()
{
m_scheduler->stop();
}
void
Context::progress()
{
2018-07-24 06:33:22 +00:00
std::cout << "." << std::flush;
}
bool
Context::Configure()
{
// llarp::LogInfo("loading config at ", configfile);
2019-02-12 00:33:19 +00:00
if(!config->Load(configfile.c_str()))
{
config.release();
llarp::LogError("failed to load config file ", configfile);
return false;
}
2019-06-02 21:19:10 +00:00
config->visit(util::memFn(&Context::iter_config, this));
2019-04-07 17:55:14 +00:00
if(!disableMetrics)
{
setupMetrics();
if(!disableMetricLogs)
{
m_metricsManager->instance()->addGlobalPublisher(
std::make_shared< metrics::StreamPublisher >(std::cerr));
}
}
return true;
}
void
Context::iter_config(const char *section, const char *key, const char *val)
{
2019-01-18 13:24:33 +00:00
if(!strcmp(section, "system"))
{
if(!strcmp(key, "pidfile"))
{
SetPIDFile(val);
2019-01-18 13:24:33 +00:00
}
}
2019-04-07 17:55:14 +00:00
if(!strcmp(section, "metrics"))
{
if(!strcmp(key, "disable-metrics"))
{
disableMetrics = true;
}
2019-04-14 16:08:51 +00:00
else if(!strcmp(key, "disable-metrics-log"))
2019-04-07 17:55:14 +00:00
{
disableMetricLogs = true;
}
2019-04-14 16:08:51 +00:00
else if(!strcmp(key, "json-metrics-path"))
2019-04-07 17:55:14 +00:00
{
2019-04-14 16:08:51 +00:00
jsonMetricsPath = val;
}
else if(!strcmp(key, "metric-tank-host"))
{
metricTankHost = val;
}
else
{
// consume everything else as a metric tag
metricTags[key] = val;
2019-04-07 17:55:14 +00:00
}
}
if(!strcmp(section, "router"))
{
if(!strcmp(key, "worker-threads") && !singleThreaded)
{
int workers = atoi(val);
if(workers > 0 && worker == nullptr)
{
worker.reset(llarp_init_threadpool(workers, "llarp-worker"));
}
2018-06-29 12:15:15 +00:00
}
else if(!strcmp(key, "net-threads"))
{
num_nethreads = atoi(val);
if(num_nethreads <= 0)
num_nethreads = 1;
if(singleThreaded)
num_nethreads = 0;
}
}
if(!strcmp(section, "netdb"))
{
if(!strcmp(key, "dir"))
{
nodedb_dir = val;
}
}
}
2019-04-07 17:55:14 +00:00
void
Context::setupMetrics()
{
if(!m_scheduler)
{
m_scheduler = std::make_unique< thread::Scheduler >();
}
if(!m_metricsManager)
{
m_metricsManager = std::make_unique< metrics::DefaultManagerGuard >();
}
if(!m_metricsPublisher)
{
m_metricsPublisher = std::make_unique< metrics::PublisherScheduler >(
*m_scheduler, m_metricsManager->instance());
}
2019-04-16 01:26:05 +00:00
if(!jsonMetricsPath.native().empty())
{
m_metricsManager->instance()->addGlobalPublisher(
std::make_shared< metrics::JsonPublisher >(
std::bind(&metrics::JsonPublisher::directoryPublisher,
std::placeholders::_1, jsonMetricsPath)));
}
2019-04-14 16:08:51 +00:00
if(!metricTankHost.empty())
{
if(std::getenv("LOKINET_ENABLE_METRIC_TANK"))
{
static std::string WARNING = R"(
__ ___ ____ _ _ ___ _ _ ____
\ \ / / \ | _ \| \ | |_ _| \ | |/ ___|
\ \ /\ / / _ \ | |_) | \| || || \| | | _
\ V V / ___ \| _ <| |\ || || |\ | |_| |
\_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____|
2019-05-28 00:19:25 +00:00
This Lokinet session is not private!!
2019-04-14 16:08:51 +00:00
2019-05-28 00:19:25 +00:00
Sending connection metrics to metrictank!!
2019-04-14 16:08:51 +00:00
__ ___ ____ _ _ ___ _ _ ____
\ \ / / \ | _ \| \ | |_ _| \ | |/ ___|
\ \ /\ / / _ \ | |_) | \| || || \| | | _
\ V V / ___ \| _ <| |\ || || |\ | |_| |
\_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____|
)";
std::cerr << WARNING << '\n';
std::pair< std::string, std::string > split =
absl::StrSplit(metricTankHost, ':');
m_metricsManager->instance()->addGlobalPublisher(
std::make_shared< metrics::MetricTankPublisher >(
metricTags, split.first, stoi(split.second)));
}
else
{
std::cerr << "metrictank host specified, but "
"LOKINET_ENABLE_METRIC_TANK not set, skipping\n";
}
}
2019-04-14 17:23:58 +00:00
m_metricsPublisher->setDefault(absl::Seconds(30));
2019-04-07 17:55:14 +00:00
m_scheduler->start();
}
void
Context::SetPIDFile(const std::string &fname)
2019-01-18 13:24:33 +00:00
{
pidfile = fname;
}
int
Context::LoadDatabase()
{
nodedb = std::make_unique< llarp_nodedb >(router->diskworker());
if(!llarp_nodedb::ensure_dir(nodedb_dir.c_str()))
{
llarp::LogError("nodedb_dir is incorrect");
return 0;
}
// llarp::LogInfo("nodedb_dir [", nodedb_dir, "] configured!");
ssize_t loaded = nodedb->load_dir(nodedb_dir.c_str());
llarp::LogInfo("nodedb_dir loaded ", loaded, " RCs from [", nodedb_dir,
"]");
2018-06-17 15:26:00 +00:00
if(loaded < 0)
{
// shouldn't be possible
llarp::LogError("nodedb_dir directory doesn't exist");
return 0;
}
return 1;
}
bool
Context::PutDatabase(__attribute__((unused)) struct llarp::RouterContact &rc)
{
// FIXME
2018-09-22 10:23:23 +00:00
// return llarp_nodedb_put_rc(nodedb, rc);
return false;
}
llarp::RouterContact *
Context::GetDatabase(__attribute__((unused)) const byte_t *pk)
2018-06-21 11:11:55 +00:00
{
// FIXME
2018-09-22 10:23:23 +00:00
// return llarp_nodedb_get_rc(nodedb, pk);
return nullptr;
2018-06-21 11:11:55 +00:00
}
int
2019-05-28 00:19:25 +00:00
Context::Setup(bool debug)
{
2018-07-24 06:37:12 +00:00
llarp::LogInfo(LLARP_VERSION, " ", LLARP_RELEASE_MOTTO);
llarp::LogInfo("starting up");
2019-06-02 21:17:05 +00:00
#if defined(WIN32)
mainloop = llarp_make_ev_loop();
2019-06-02 21:17:05 +00:00
#else
mainloop = llarp_make_uv_loop();
#endif
2018-06-06 17:02:57 +00:00
// ensure worker thread pool
if(!worker && !singleThreaded)
worker.reset(llarp_init_threadpool(2, "llarp-worker"));
2018-06-06 17:02:57 +00:00
else if(singleThreaded)
{
llarp::LogInfo("running in single threaded mode");
worker.reset(llarp_init_same_process_threadpool());
2018-06-06 17:02:57 +00:00
}
// ensure netio thread
if(singleThreaded)
{
logic = std::make_shared< Logic >(worker.get());
2018-06-06 17:02:57 +00:00
}
else
logic = std::make_shared< Logic >();
2019-05-28 00:19:25 +00:00
if(debug)
{
static std::string WARNING = R"(
__ ___ ____ _ _ ___ _ _ ____
\ \ / / \ | _ \| \ | |_ _| \ | |/ ___|
\ \ /\ / / _ \ | |_) | \| || || \| | | _
\ V V / ___ \| _ <| |\ || || |\ | |_| |
\_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____|
This Lokinet session is not private!!
Sending traffic unencrypted!!
__ ___ ____ _ _ ___ _ _ ____
\ \ / / \ | _ \| \ | |_ _| \ | |/ ___|
\ \ /\ / / _ \ | |_) | \| || || \| | | _
\ V V / ___ \| _ <| |\ || || |\ | |_| |
\_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____|
)";
std::cerr << WARNING << '\n';
crypto = std::make_unique< NoOpCrypto >();
}
else
{
crypto = std::make_unique< sodium::CryptoLibSodium >();
}
cryptoManager = std::make_unique< CryptoManager >(crypto.get());
router = std::make_unique< Router >(worker.get(), mainloop, logic);
if(!router->Configure(config.get()))
2018-06-06 17:02:57 +00:00
{
llarp::LogError("Failed to configure router");
return 1;
}
2018-12-28 15:34:41 +00:00
// must be done after router is made so we can use its disk io worker
2019-04-14 16:08:51 +00:00
// must also be done after configure so that netid is properly set if it
// is provided by config
2018-12-28 15:34:41 +00:00
if(!this->LoadDatabase())
return 1;
return 0;
}
int
Context::Run()
{
if(router == nullptr)
{
// we are not set up so we should die
llarp::LogError("cannot run non configured context");
return 1;
}
2019-01-18 13:24:33 +00:00
if(!WritePIDFile())
return 1;
// run
if(!router->Run(nodedb.get()))
return 1;
// run net io thread
2018-09-21 12:30:57 +00:00
llarp::LogInfo("running mainloop");
llarp_ev_loop_run_single_process(mainloop, worker.get(), logic);
// waits for router graceful stop
return 0;
}
2019-01-18 13:24:33 +00:00
bool
Context::WritePIDFile() const
{
if(pidfile.size())
{
std::ofstream f(pidfile);
f << std::to_string(getpid());
return f.good();
}
else
return true;
}
void
Context::RemovePIDFile() const
{
if(pidfile.size())
{
fs::path f = pidfile;
std::error_code ex;
if(fs::exists(f, ex))
{
if(!ex)
fs::remove(f);
}
}
}
void
Context::HandleSignal(int sig)
{
2018-11-29 13:12:28 +00:00
if(sig == SIGINT || sig == SIGTERM)
{
SigINT();
}
// TODO(despair): implement hot-reloading config on NT
#ifndef _WIN32
if(sig == SIGHUP)
{
llarp::LogInfo("SIGHUP");
if(router)
{
2019-05-07 17:46:38 +00:00
router->hiddenServiceContext().ForEachService(
[](const std::string &name,
const llarp::service::Endpoint_ptr &ep) -> bool {
ep->ResetInternalState();
llarp::LogInfo("Reset internal state for ", name);
return true;
});
2019-05-07 18:15:22 +00:00
router->PumpLL();
Config newconfig;
2019-05-07 17:46:38 +00:00
if(!newconfig.Load(configfile.c_str()))
{
llarp::LogError("failed to load config file ", configfile);
return;
}
// validate config
if(!router->ValidateConfig(&newconfig))
{
llarp::LogWarn("new configuration is invalid");
return;
}
// reconfigure
if(!router->Reconfigure(&newconfig))
{
llarp::LogError("Failed to reconfigure so we will stop.");
router->Stop();
return;
}
llarp::LogInfo("router reconfigured");
}
}
#endif
}
void
Context::SigINT()
{
if(router)
{
/// async stop router on sigint
router->Stop();
}
else
{
if(logic)
logic->stop();
2019-06-02 21:17:05 +00:00
llarp_ev_loop_stop(mainloop);
Close();
}
}
void
Context::Close()
{
llarp::LogDebug("stop workers");
if(worker)
llarp_threadpool_stop(worker.get());
llarp::LogDebug("join workers");
if(worker)
llarp_threadpool_join(worker.get());
llarp::LogDebug("free config");
config.release();
llarp::LogDebug("free workers");
worker.release();
llarp::LogDebug("free nodedb");
nodedb.release();
llarp::LogDebug("free router");
router.release();
llarp::LogDebug("free logic");
logic.reset();
2019-01-18 13:24:33 +00:00
RemovePIDFile();
}
bool
Context::LoadConfig(const std::string &fname)
{
config = std::make_unique< Config >();
configfile = fname;
return Configure();
}
} // namespace llarp
2018-05-27 18:03:10 +00:00
struct llarp_main
{
std::unique_ptr< llarp::Context > ctx;
};
2018-07-27 03:41:55 +00:00
extern "C"
2018-05-27 18:03:10 +00:00
{
2018-07-27 03:41:55 +00:00
struct llarp_main *
llarp_main_init(const char *fname, bool multiProcess)
{
if(!fname)
fname = "daemon.ini";
char *var = getenv("LLARP_DEBUG");
if(var && *var == '1')
{
cSetLogLevel(eLogDebug);
}
llarp_main *m = new llarp_main;
m->ctx = std::make_unique< llarp::Context >();
m->ctx->singleThreaded = !multiProcess;
if(!m->ctx->LoadConfig(fname))
{
m->ctx->Close();
delete m;
return nullptr;
}
return m;
}
2018-07-27 03:41:55 +00:00
void
llarp_main_signal(struct llarp_main *ptr, int sig)
2018-05-27 18:03:10 +00:00
{
ptr->ctx->HandleSignal(sig);
2018-05-27 18:03:10 +00:00
}
2018-07-27 03:41:55 +00:00
int
2019-05-28 00:19:25 +00:00
llarp_main_setup(struct llarp_main *ptr, bool debug)
2018-07-27 03:41:55 +00:00
{
2019-05-28 00:19:25 +00:00
return ptr->ctx->Setup(debug);
2018-07-27 03:41:55 +00:00
}
2018-07-27 03:41:55 +00:00
int
llarp_main_run(struct llarp_main *ptr)
{
if(!ptr)
{
llarp::LogError("No ptr passed in");
return 1;
}
return ptr->ctx->Run();
2018-07-27 03:41:55 +00:00
}
2018-05-27 18:03:10 +00:00
2018-07-27 03:41:55 +00:00
void
llarp_main_abort(struct llarp_main *ptr)
{
ptr->ctx->router->logic()->stop_timer();
2018-07-27 03:41:55 +00:00
}
void
llarp_main_queryDHT_RC(struct llarp_main *ptr,
struct llarp_router_lookup_job *job)
2018-07-27 03:41:55 +00:00
{
llarp_dht_lookup_router(ptr->ctx->router->dht(), job);
2018-07-27 03:41:55 +00:00
}
2018-07-27 03:41:55 +00:00
bool
llarp_main_init_dnsd(struct llarp_main *ptr, struct dnsd_context *dnsd,
const llarp::Addr &dnsd_sockaddr,
const llarp::Addr &dnsc_sockaddr)
2018-07-27 03:41:55 +00:00
{
return llarp_dnsd_init(dnsd, ptr->ctx->logic.get(),
ptr->ctx->mainloop.get(), dnsd_sockaddr,
dnsc_sockaddr);
2018-07-27 03:41:55 +00:00
}
2018-09-22 10:23:23 +00:00
bool
llarp_main_init_dotLokiLookup(struct llarp_main *ptr,
struct dotLokiLookup *dll)
{
2018-12-03 22:22:59 +00:00
(void)ptr;
(void)dll;
// TODO: gut me
2018-12-03 22:22:59 +00:00
return false;
2018-09-22 10:23:23 +00:00
}
2018-07-27 03:41:55 +00:00
void
llarp_main_free(struct llarp_main *ptr)
{
delete ptr;
2018-07-27 03:41:55 +00:00
}
2018-06-29 12:15:15 +00:00
2018-09-22 10:23:23 +00:00
int
llarp_main_loadDatabase(struct llarp_main *ptr)
{
return ptr->ctx->LoadDatabase();
}
2018-07-27 03:41:55 +00:00
const char *
handleBaseCmdLineArgs(int argc, char *argv[])
2018-07-26 10:52:23 +00:00
{
// clang-format off
cxxopts::Options options(
"lokinet",
"Lokinet is a private, decentralized and IP based overlay network for the internet"
);
options.add_options()
("c,config", "Config file", cxxopts::value< std::string >()->default_value("daemon.ini"))
("o,logLevel", "logging level");
// clang-format on
auto result = options.parse(argc, argv);
std::string logLevel = result["logLevel"].as< std::string >();
if(logLevel == "debug")
{
cSetLogLevel(eLogDebug);
2018-07-26 10:52:23 +00:00
}
else if(logLevel == "info")
{
cSetLogLevel(eLogInfo);
}
else if(logLevel == "warn")
{
cSetLogLevel(eLogWarn);
}
else if(logLevel == "error")
{
cSetLogLevel(eLogError);
}
// this isn't thread safe, but reconfiguring during run is likely unsafe
// either way
static std::string confname = result["config"].as< std::string >();
return confname.c_str();
2018-07-26 10:52:23 +00:00
}
}