Merge pull request #23 from naim94a/feature/windows-service
Feature/windows service
This commit is contained in:
commit
7d27979828
78
src/main.cpp
78
src/main.cpp
|
@ -25,15 +25,8 @@
|
|||
#include <memory>
|
||||
#include <algorithm>
|
||||
#include <boost/program_options.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_types.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/log/sources/severity_channel_logger.hpp>
|
||||
#include <boost/log/sinks/text_file_backend.hpp>
|
||||
#include <boost/log/sinks/async_frontend.hpp>
|
||||
#include <boost/log/keywords/format.hpp>
|
||||
#include <boost/log/expressions.hpp>
|
||||
#include <boost/log/support/date_time.hpp>
|
||||
#include <boost/log/utility/setup/common_attributes.hpp>
|
||||
|
||||
#include "multiplatform.h"
|
||||
#include "udpTracker.hpp"
|
||||
|
@ -104,33 +97,7 @@ int main(int argc, char *argv[])
|
|||
;
|
||||
|
||||
|
||||
boost::program_options::options_description configOptions("Configuration options");
|
||||
configOptions.add_options()
|
||||
("db.driver", boost::program_options::value<std::string>()->default_value("sqlite3"), "database driver to use")
|
||||
("db.param", boost::program_options::value<std::string>()->default_value("/var/lib/udpt.db"), "database connection parameters")
|
||||
|
||||
("tracker.is_dynamic", boost::program_options::value<bool>()->default_value(true), "Sets if the tracker is dynamic")
|
||||
("tracker.port", boost::program_options::value<unsigned short>()->default_value(6969), "UDP port to listen on")
|
||||
("tracker.threads", boost::program_options::value<unsigned>()->default_value(5), "threads to run (UDP only)")
|
||||
("tracker.allow_remotes", boost::program_options::value<bool>()->default_value(true), "allows clients to report remote IPs")
|
||||
("tracker.allow_iana_ips", boost::program_options::value<bool>()->default_value(false), "allows IANA reserved IPs to connect (useful for debugging)")
|
||||
("tracker.announce_interval", boost::program_options::value<unsigned>()->default_value(1800), "announce interval")
|
||||
("tracker.cleanup_interval", boost::program_options::value<unsigned>()->default_value(120), "sets database cleanup interval")
|
||||
|
||||
("apiserver.enable", boost::program_options::value<bool>()->default_value(0), "Enable API server?")
|
||||
("apiserver.threads", boost::program_options::value<unsigned short>()->default_value(1), "threads for API server")
|
||||
("apiserver.port", boost::program_options::value<unsigned short>()->default_value(6969), "TCP port to listen on")
|
||||
|
||||
("logging.filename", boost::program_options::value<std::string>()->default_value("/var/log/udpt.log"), "file to write logs to")
|
||||
("logging.level", boost::program_options::value<std::string>()->default_value("warning"), "log level (fatal/error/warning/info/debug/trace)")
|
||||
|
||||
#ifdef linux
|
||||
("daemon.chdir", boost::program_options::value<std::string>()->default_value("/"), "home directory for daemon")
|
||||
#endif
|
||||
#ifdef WIN32
|
||||
("service.name", boost::program_options::value<std::string>()->default_value("udpt"), "service name to use")
|
||||
#endif
|
||||
;
|
||||
const boost::program_options::options_description& configOptions = Tracker::getConfigOptions();
|
||||
|
||||
boost::program_options::variables_map var_map;
|
||||
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, commandLine), var_map);
|
||||
|
@ -178,44 +145,8 @@ int main(int argc, char *argv[])
|
|||
}
|
||||
}
|
||||
|
||||
// setup logging...
|
||||
boost::log::add_common_attributes();
|
||||
boost::shared_ptr<boost::log::sinks::text_file_backend> logBackend = boost::make_shared<boost::log::sinks::text_file_backend>(
|
||||
boost::log::keywords::file_name = var_map["logging.filename"].as<std::string>(),
|
||||
boost::log::keywords::auto_flush = true,
|
||||
boost::log::keywords::open_mode = std::ios::out | std::ios::app
|
||||
);
|
||||
typedef boost::log::sinks::asynchronous_sink<boost::log::sinks::text_file_backend> udptSink_t;
|
||||
boost::shared_ptr<udptSink_t> async_sink (new udptSink_t(logBackend));
|
||||
async_sink->set_formatter(
|
||||
boost::log::expressions::stream
|
||||
<< boost::log::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S") << " "
|
||||
<< boost::log::expressions::attr<int>("Severity")
|
||||
<< " [" << boost::log::expressions::attr<std::string>("Channel") << "] \t"
|
||||
<< boost::log::expressions::smessage
|
||||
);
|
||||
auto loggingCore = boost::log::core::get();
|
||||
loggingCore->add_sink(async_sink);
|
||||
|
||||
boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "main");
|
||||
|
||||
std::string severity = var_map["logging.level"].as<std::string>();
|
||||
std::transform(severity.begin(), severity.end(), severity.begin(), ::tolower);
|
||||
int severityVal = boost::log::trivial::warning;
|
||||
if ("fatal" == severity) severityVal = boost::log::trivial::fatal;
|
||||
else if ("error" == severity) severityVal = boost::log::trivial::error;
|
||||
else if ("warning" == severity) severityVal = boost::log::trivial::warning;
|
||||
else if ("info" == severity) severityVal = boost::log::trivial::info;
|
||||
else if ("debug" == severity) severityVal = boost::log::trivial::debug;
|
||||
else if ("trace" == severity) severityVal = boost::log::trivial::trace;
|
||||
else
|
||||
{
|
||||
BOOST_LOG_SEV(logger, boost::log::trivial::warning) << "Unknown debug level \"" << severity << "\" defaulting to warning";
|
||||
}
|
||||
|
||||
loggingCore->set_filter(
|
||||
boost::log::trivial::severity >= severityVal
|
||||
);
|
||||
Tracker::setupLogging(var_map, logger);
|
||||
|
||||
#ifdef linux
|
||||
if (!var_map.count("interactive"))
|
||||
|
@ -234,7 +165,7 @@ int main(int argc, char *argv[])
|
|||
if ("install" == action)
|
||||
{
|
||||
std::cerr << "Installing service..." << std::endl;
|
||||
svc.install();
|
||||
svc.install(var_map["config"].as<std::string>());
|
||||
std::cerr << "Installed." << std::endl;
|
||||
}
|
||||
else if ("uninstall" == action)
|
||||
|
@ -254,7 +185,7 @@ int main(int argc, char *argv[])
|
|||
}
|
||||
catch (const UDPT::OSError& ex)
|
||||
{
|
||||
std::cerr << "An operating system error occurred: " << ex.getErrorCode() << std::endl;
|
||||
std::cerr << "An operating system error occurred: " << ex.what() << std::endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
@ -264,6 +195,7 @@ int main(int argc, char *argv[])
|
|||
try
|
||||
{
|
||||
svc.setup();
|
||||
return 0;
|
||||
}
|
||||
catch (const OSError& err)
|
||||
{
|
||||
|
|
112
src/service.cpp
112
src/service.cpp
|
@ -17,11 +17,15 @@
|
|||
* along with UDPT. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "service.hpp"
|
||||
#include <filesystem>
|
||||
|
||||
#ifdef WIN32
|
||||
|
||||
namespace UDPT
|
||||
{
|
||||
SERVICE_STATUS_HANDLE Service::s_hServiceStatus = nullptr;
|
||||
SERVICE_STATUS Service::s_serviceStatus = { 0 };
|
||||
|
||||
Service::Service(const boost::program_options::variables_map& conf) : m_conf(conf)
|
||||
{
|
||||
|
||||
|
@ -32,10 +36,10 @@ namespace UDPT
|
|||
|
||||
}
|
||||
|
||||
void Service::install()
|
||||
void Service::install(const std::string& config_path)
|
||||
{
|
||||
std::string& binaryPath = getFilename();
|
||||
binaryPath = "\"" + binaryPath + "\"";
|
||||
binaryPath = "\"" + binaryPath + "\" -c \"" + config_path + "\"";
|
||||
std::shared_ptr<void> svcMgr = getServiceManager(SC_MANAGER_CREATE_SERVICE);
|
||||
{
|
||||
SC_HANDLE installedService = ::CreateService(reinterpret_cast<SC_HANDLE>(svcMgr.get()),
|
||||
|
@ -87,15 +91,119 @@ namespace UDPT
|
|||
{ const_cast<char*>(m_conf["service.name"].as<std::string>().c_str()), reinterpret_cast<LPSERVICE_MAIN_FUNCTION>(&Service::serviceMain) },
|
||||
{0, 0}
|
||||
};
|
||||
|
||||
if (FALSE == ::StartServiceCtrlDispatcher(service))
|
||||
{
|
||||
throw OSError();
|
||||
}
|
||||
}
|
||||
|
||||
DWORD Service::handler(DWORD controlCode, DWORD dwEventType, LPVOID eventData, LPVOID context)
|
||||
{
|
||||
switch (controlCode)
|
||||
{
|
||||
case SERVICE_CONTROL_INTERROGATE:
|
||||
return NO_ERROR;
|
||||
|
||||
case SERVICE_CONTROL_STOP:
|
||||
{
|
||||
reportServiceStatus(SERVICE_STOP_PENDING, 0, 3000);
|
||||
Tracker::getInstance().stop();
|
||||
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
default:
|
||||
return ERROR_CALL_NOT_IMPLEMENTED;
|
||||
}
|
||||
}
|
||||
|
||||
void Service::reportServiceStatus(DWORD currentState, DWORD dwExitCode, DWORD dwWaitHint)
|
||||
{
|
||||
static DWORD checkpoint = 1;
|
||||
|
||||
if (currentState == SERVICE_STOPPED || currentState == SERVICE_RUNNING)
|
||||
{
|
||||
checkpoint = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
++checkpoint;
|
||||
}
|
||||
|
||||
switch (currentState)
|
||||
{
|
||||
case SERVICE_RUNNING:
|
||||
s_serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
|
||||
break;
|
||||
|
||||
default:
|
||||
s_serviceStatus.dwControlsAccepted = 0;
|
||||
}
|
||||
|
||||
s_serviceStatus.dwCheckPoint = checkpoint;
|
||||
s_serviceStatus.dwCurrentState = currentState;
|
||||
s_serviceStatus.dwWin32ExitCode = dwExitCode;
|
||||
s_serviceStatus.dwWaitHint = dwWaitHint;
|
||||
|
||||
::SetServiceStatus(s_hServiceStatus, &s_serviceStatus);
|
||||
}
|
||||
|
||||
VOID Service::serviceMain(DWORD argc, LPCSTR argv[])
|
||||
{
|
||||
boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "service");
|
||||
|
||||
wchar_t *commandLine = ::GetCommandLineW();
|
||||
int argCount = 0;
|
||||
std::shared_ptr<LPWSTR> args(::CommandLineToArgvW(commandLine, &argCount), ::LocalFree);
|
||||
if (nullptr == args)
|
||||
{
|
||||
BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed parse command-line.";
|
||||
::exit(-1);
|
||||
}
|
||||
|
||||
if (3 != argCount)
|
||||
{
|
||||
BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Bad command-line length (must have exactly 2 arguments).";
|
||||
::exit(-1);
|
||||
}
|
||||
|
||||
if (std::wstring(args.get()[1]) != L"-c")
|
||||
{
|
||||
BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Argument 1 must be \"-c\".";
|
||||
::exit(-1);
|
||||
}
|
||||
|
||||
std::wstring wFilename(args.get()[2]);
|
||||
std::string cFilename(wFilename.begin(), wFilename.end());
|
||||
|
||||
boost::program_options::options_description& configOptions = UDPT::Tracker::getConfigOptions();
|
||||
boost::program_options::variables_map config;
|
||||
boost::program_options::basic_parsed_options<wchar_t> parsed_options = boost::program_options::parse_config_file<wchar_t>(cFilename.c_str(), configOptions);
|
||||
boost::program_options::store(parsed_options, config);
|
||||
|
||||
s_hServiceStatus = ::RegisterServiceCtrlHandlerEx(config["service.name"].as<std::string>().c_str(), Service::handler, NULL);
|
||||
if (nullptr == s_hServiceStatus)
|
||||
{
|
||||
BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed to register service control handler.";
|
||||
::exit(-1);
|
||||
}
|
||||
|
||||
s_serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
|
||||
s_serviceStatus.dwServiceSpecificExitCode = 0;
|
||||
|
||||
reportServiceStatus(SERVICE_START_PENDING, 0, 0);
|
||||
|
||||
{
|
||||
UDPT::Tracker& tracker = UDPT::Tracker::getInstance();
|
||||
tracker.start(config);
|
||||
|
||||
reportServiceStatus(SERVICE_RUNNING, 0, 0);
|
||||
|
||||
tracker.wait();
|
||||
|
||||
reportServiceStatus(SERVICE_STOPPED, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<void> Service::getService(DWORD access)
|
||||
|
|
|
@ -18,9 +18,12 @@
|
|||
*/
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <boost/program_options.hpp>
|
||||
#include "multiplatform.h"
|
||||
#include "exceptions.h"
|
||||
#include "tracker.hpp"
|
||||
|
||||
#ifdef WIN32
|
||||
namespace UDPT
|
||||
|
@ -33,7 +36,7 @@ namespace UDPT
|
|||
virtual ~Service();
|
||||
|
||||
|
||||
void install();
|
||||
void install(const std::string& config_path);
|
||||
|
||||
void uninstall();
|
||||
|
||||
|
@ -45,9 +48,15 @@ namespace UDPT
|
|||
private:
|
||||
const boost::program_options::variables_map& m_conf;
|
||||
|
||||
static SERVICE_STATUS_HANDLE s_hServiceStatus;
|
||||
|
||||
static SERVICE_STATUS s_serviceStatus;
|
||||
|
||||
std::shared_ptr<void> getService(DWORD access);
|
||||
|
||||
static VOID WINAPI handler(DWORD controlCode);
|
||||
static DWORD WINAPI handler(DWORD controlCode, DWORD dwEventType, LPVOID eventData, LPVOID context);
|
||||
|
||||
static void reportServiceStatus(DWORD currentState, DWORD dwExitCode, DWORD dwWaitHint);
|
||||
|
||||
static VOID WINAPI serviceMain(DWORD argc, LPCSTR argv[]);
|
||||
|
||||
|
|
|
@ -70,4 +70,76 @@ namespace UDPT
|
|||
|
||||
return s_tracker;
|
||||
}
|
||||
|
||||
boost::program_options::options_description Tracker::getConfigOptions()
|
||||
{
|
||||
boost::program_options::options_description configOptions("Configuration options");
|
||||
configOptions.add_options()
|
||||
("db.driver", boost::program_options::value<std::string>()->default_value("sqlite3"), "database driver to use")
|
||||
("db.param", boost::program_options::value<std::string>()->default_value("/var/lib/udpt.db"), "database connection parameters")
|
||||
|
||||
("tracker.is_dynamic", boost::program_options::value<bool>()->default_value(true), "Sets if the tracker is dynamic")
|
||||
("tracker.port", boost::program_options::value<unsigned short>()->default_value(6969), "UDP port to listen on")
|
||||
("tracker.threads", boost::program_options::value<unsigned>()->default_value(5), "threads to run (UDP only)")
|
||||
("tracker.allow_remotes", boost::program_options::value<bool>()->default_value(true), "allows clients to report remote IPs")
|
||||
("tracker.allow_iana_ips", boost::program_options::value<bool>()->default_value(false), "allows IANA reserved IPs to connect (useful for debugging)")
|
||||
("tracker.announce_interval", boost::program_options::value<unsigned>()->default_value(1800), "announce interval")
|
||||
("tracker.cleanup_interval", boost::program_options::value<unsigned>()->default_value(120), "sets database cleanup interval")
|
||||
|
||||
("apiserver.enable", boost::program_options::value<bool>()->default_value(0), "Enable API server?")
|
||||
("apiserver.threads", boost::program_options::value<unsigned short>()->default_value(1), "threads for API server")
|
||||
("apiserver.port", boost::program_options::value<unsigned short>()->default_value(6969), "TCP port to listen on")
|
||||
|
||||
("logging.filename", boost::program_options::value<std::string>()->default_value("/var/log/udpt.log"), "file to write logs to")
|
||||
("logging.level", boost::program_options::value<std::string>()->default_value("warning"), "log level (fatal/error/warning/info/debug/trace)")
|
||||
|
||||
#ifdef linux
|
||||
("daemon.chdir", boost::program_options::value<std::string>()->default_value("/"), "home directory for daemon")
|
||||
#endif
|
||||
#ifdef WIN32
|
||||
("service.name", boost::program_options::value<std::string>()->default_value("udpt"), "service name to use")
|
||||
#endif
|
||||
;
|
||||
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
void Tracker::setupLogging(const boost::program_options::variables_map& config, boost::log::sources::severity_channel_logger_mt<>& logger)
|
||||
{
|
||||
boost::log::add_common_attributes();
|
||||
boost::shared_ptr<boost::log::sinks::text_file_backend> logBackend = boost::make_shared<boost::log::sinks::text_file_backend>(
|
||||
boost::log::keywords::file_name = config["logging.filename"].as<std::string>(),
|
||||
boost::log::keywords::auto_flush = true,
|
||||
boost::log::keywords::open_mode = std::ios::out | std::ios::app
|
||||
);
|
||||
typedef boost::log::sinks::asynchronous_sink<boost::log::sinks::text_file_backend> udptSink_t;
|
||||
boost::shared_ptr<udptSink_t> async_sink(new udptSink_t(logBackend));
|
||||
async_sink->set_formatter(
|
||||
boost::log::expressions::stream
|
||||
<< boost::log::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S") << " "
|
||||
<< boost::log::expressions::attr<int>("Severity")
|
||||
<< " [" << boost::log::expressions::attr<std::string>("Channel") << "] \t"
|
||||
<< boost::log::expressions::smessage
|
||||
);
|
||||
auto loggingCore = boost::log::core::get();
|
||||
loggingCore->add_sink(async_sink);
|
||||
|
||||
std::string severity = config["logging.level"].as<std::string>();
|
||||
std::transform(severity.begin(), severity.end(), severity.begin(), ::tolower);
|
||||
int severityVal = boost::log::trivial::warning;
|
||||
if ("fatal" == severity) severityVal = boost::log::trivial::fatal;
|
||||
else if ("error" == severity) severityVal = boost::log::trivial::error;
|
||||
else if ("warning" == severity) severityVal = boost::log::trivial::warning;
|
||||
else if ("info" == severity) severityVal = boost::log::trivial::info;
|
||||
else if ("debug" == severity) severityVal = boost::log::trivial::debug;
|
||||
else if ("trace" == severity) severityVal = boost::log::trivial::trace;
|
||||
else
|
||||
{
|
||||
BOOST_LOG_SEV(logger, boost::log::trivial::warning) << "Unknown debug level \"" << severity << "\" defaulting to warning";
|
||||
}
|
||||
|
||||
loggingCore->set_filter(
|
||||
boost::log::trivial::severity >= severityVal
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -23,6 +23,14 @@
|
|||
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/log/sources/severity_channel_logger.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_types.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/log/sinks/text_file_backend.hpp>
|
||||
#include <boost/log/sinks/async_frontend.hpp>
|
||||
#include <boost/log/keywords/format.hpp>
|
||||
#include <boost/log/expressions.hpp>
|
||||
#include <boost/log/support/date_time.hpp>
|
||||
#include <boost/log/utility/setup/common_attributes.hpp>
|
||||
|
||||
#include "multiplatform.h"
|
||||
#include "udpTracker.hpp"
|
||||
|
@ -45,6 +53,10 @@ namespace UDPT
|
|||
|
||||
static Tracker& getInstance();
|
||||
|
||||
static boost::program_options::options_description getConfigOptions();
|
||||
|
||||
static void setupLogging(const boost::program_options::variables_map& config, boost::log::sources::severity_channel_logger_mt<>& logger);
|
||||
|
||||
private:
|
||||
std::shared_ptr<UDPT::UDPTracker> m_udpTracker;
|
||||
std::shared_ptr<UDPT::Server::HTTPServer> m_apiSrv;
|
||||
|
|
|
@ -59,7 +59,8 @@
|
|||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>ws2_32.lib;sqlite3.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;sqlite3.lib;advapi32.lib;shell32.lib</AdditionalDependencies>
|
||||
<SubSystem>Console</SubSystem>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
|
@ -77,7 +78,8 @@
|
|||
</EnableCOMDATFolding>
|
||||
<OptimizeReferences>
|
||||
</OptimizeReferences>
|
||||
<AdditionalDependencies>ws2_32.lib;sqlite3.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;sqlite3.lib;advapi32.lib;shell32.lib</AdditionalDependencies>
|
||||
<SubSystem>Console</SubSystem>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
|
|
Loading…
Reference in a new issue