Whitespace fix

What does this change?
* Remove use of spaces for formatting
These could be found by using `grep -r -l -P '^\t+ +[^*]'
* Removal of training whitespaces
* A few lines longer than 120 chars
This commit is contained in:
Jean Flach 2017-12-19 15:50:05 +01:00
parent df88da5836
commit 2636e6a77a
314 changed files with 2968 additions and 2984 deletions

View File

@ -194,16 +194,13 @@ namespace Icinga
string master_host, master_port; string master_host, master_port;
GetMasterHostPort(out master_host, out master_port); GetMasterHostPort(out master_host, out master_port);
args += " --master_host " + master_host args += " --master_host " + master_host + "," + master_port;
+ "," + master_port;
foreach (ListViewItem lvi in lvwEndpoints.Items) { foreach (ListViewItem lvi in lvwEndpoints.Items) {
args += " --endpoint " + lvi.SubItems[0].Text.Trim(); args += " --endpoint " + lvi.SubItems[0].Text.Trim();
if (lvi.SubItems.Count > 1) { if (lvi.SubItems.Count > 1)
args += "," + lvi.SubItems[1].Text.Trim() args += "," + lvi.SubItems[1].Text.Trim() + "," + lvi.SubItems[2].Text.Trim();
+ "," + lvi.SubItems[2].Text.Trim();
}
} }
}); });

View File

@ -4,7 +4,7 @@
#include "i2tcl.hpp" #include "i2tcl.hpp"
%} %}
%typemap(in,numinputs=0) Tcl_Interp *interp { %typemap(in,numinputs=0) Tcl_Interp *interp {
$1 = interp; $1 = interp;
} }

View File

@ -108,7 +108,7 @@ static int Main(void)
autoindex = Convert::ToLong(argv[2]); autoindex = Convert::ToLong(argv[2]);
} catch (const std::invalid_argument&) { } catch (const std::invalid_argument&) {
Log(LogCritical, "icinga-app") Log(LogCritical, "icinga-app")
<< "Invalid index for --autocomplete: " << argv[2]; << "Invalid index for --autocomplete: " << argv[2];
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -209,7 +209,7 @@ static int Main(void)
("library,l", po::value<std::vector<std::string> >(), "load a library") ("library,l", po::value<std::vector<std::string> >(), "load a library")
("include,I", po::value<std::vector<std::string> >(), "add include search directory") ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
("log-level,x", po::value<std::string>(), "specify the log level for the console log.\n" ("log-level,x", po::value<std::string>(), "specify the log level for the console log.\n"
"The valid value is either debug, notice, information (default), warning, or critical") "The valid value is either debug, notice, information (default), warning, or critical")
("script-debugger,X", "whether to enable the script debugger"); ("script-debugger,X", "whether to enable the script debugger");
po::options_description hiddenDesc("Hidden options"); po::options_description hiddenDesc("Hidden options");
@ -227,10 +227,10 @@ static int Main(void)
try { try {
CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc, CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
vm, cmdname, command, autocomplete); vm, cmdname, command, autocomplete);
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "icinga-app") Log(LogCritical, "icinga-app")
<< "Error while parsing command-line options: " << ex.what(); << "Error while parsing command-line options: " << ex.what();
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -365,11 +365,11 @@ static int Main(void)
(void) Loader::LoadExtensionLibrary(libraryName); (void) Loader::LoadExtensionLibrary(libraryName);
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "icinga-app") Log(LogCritical, "icinga-app")
<< "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex); << "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
} }
if (!command || vm.count("help") || vm.count("version")) { if (!command || vm.count("help") || vm.count("version")) {
String appName; String appName;
@ -385,17 +385,17 @@ static int Main(void)
appName = appName.SubStr(3, appName.GetLength() - 3); appName = appName.SubStr(3, appName.GetLength() - 3);
std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: " std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
<< ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal) << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
<< Application::GetAppVersion() << Application::GetAppVersion()
#ifdef I2_DEBUG #ifdef I2_DEBUG
<< "; debug" << "; debug"
#endif /* I2_DEBUG */ #endif /* I2_DEBUG */
<< ConsoleColorTag(Console_Normal) << ConsoleColorTag(Console_Normal)
<< ")" << std::endl << std::endl; << ")" << std::endl << std::endl;
if ((!command || vm.count("help")) && !vm.count("version")) { if ((!command || vm.count("help")) && !vm.count("version")) {
std::cout << "Usage:" << std::endl std::cout << "Usage:" << std::endl
<< " " << Utility::BaseName(argv[0]) << " "; << " " << Utility::BaseName(argv[0]) << " ";
if (cmdname.IsEmpty()) if (cmdname.IsEmpty())
std::cout << "<command>"; std::cout << "<command>";
@ -406,7 +406,7 @@ static int Main(void)
if (command) { if (command) {
std::cout << std::endl std::cout << std::endl
<< command->GetDescription() << std::endl; << command->GetDescription() << std::endl;
} }
} }
@ -443,7 +443,7 @@ static int Main(void)
if (autocomplete) { if (autocomplete) {
CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc, CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
&GlobalArgumentCompletion, true, autoindex); &GlobalArgumentCompletion, true, autoindex);
rc = 0; rc = 0;
} else if (command) { } else if (command) {
Logger::DisableTimestamp(true); Logger::DisableTimestamp(true);
@ -463,11 +463,11 @@ static int Main(void)
if (!gr) { if (!gr) {
if (errno == 0) { if (errno == 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Invalid group specified: " << group; << "Invalid group specified: " << group;
return EXIT_FAILURE; return EXIT_FAILURE;
} else { } else {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
@ -475,15 +475,15 @@ static int Main(void)
if (getgid() != gr->gr_gid) { if (getgid() != gr->gr_gid) {
if (!vm.count("reload-internal") && setgroups(0, nullptr) < 0) { if (!vm.count("reload-internal") && setgroups(0, nullptr) < 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Please re-run this command as a privileged user or using the \"" << user << "\" account."; << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
if (setgid(gr->gr_gid) < 0) { if (setgid(gr->gr_gid) < 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
@ -494,11 +494,11 @@ static int Main(void)
if (!pw) { if (!pw) {
if (errno == 0) { if (errno == 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Invalid user specified: " << user; << "Invalid user specified: " << user;
return EXIT_FAILURE; return EXIT_FAILURE;
} else { } else {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
@ -507,17 +507,17 @@ static int Main(void)
if (getuid() != pw->pw_uid) { if (getuid() != pw->pw_uid) {
if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) { if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Please re-run this command as a privileged user or using the \"" << user << "\" account."; << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
if (setuid(pw->pw_uid) < 0) { if (setuid(pw->pw_uid) < 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Please re-run this command as a privileged user or using the \"" << user << "\" account."; << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
@ -532,15 +532,15 @@ static int Main(void)
if (static_cast<int>(args.size()) < command->GetMinArguments()) { if (static_cast<int>(args.size()) < command->GetMinArguments()) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Too few arguments. Command needs at least " << command->GetMinArguments() << "Too few arguments. Command needs at least " << command->GetMinArguments()
<< " argument" << (command->GetMinArguments() != 1 ? "s" : "") << "."; << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
if (command->GetMaxArguments() >= 0 && static_cast<int>(args.size()) > command->GetMaxArguments()) { if (command->GetMaxArguments() >= 0 && static_cast<int>(args.size()) > command->GetMaxArguments()) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Too many arguments. At most " << command->GetMaxArguments() << "Too many arguments. At most " << command->GetMaxArguments()
<< " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified."; << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -710,7 +710,7 @@ static VOID ReportSvcStatus(DWORD dwCurrentState,
l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
if ((dwCurrentState == SERVICE_RUNNING) || if ((dwCurrentState == SERVICE_RUNNING) ||
(dwCurrentState == SERVICE_STOPPED)) (dwCurrentState == SERVICE_STOPPED))
l_SvcStatus.dwCheckPoint = 0; l_SvcStatus.dwCheckPoint = 0;
else else
l_SvcStatus.dwCheckPoint = dwCheckPoint++; l_SvcStatus.dwCheckPoint = dwCheckPoint++;

View File

@ -59,7 +59,7 @@ ConnectForm::ConnectForm(wxWindow *parent, const Url::Ptr& url)
Url::Ptr ConnectForm::GetUrl(void) const Url::Ptr ConnectForm::GetUrl(void) const
{ {
wxString url = "https://" + m_UserText->GetValue() + ":" + m_PasswordText->GetValue() wxString url = "https://" + m_UserText->GetValue() + ":" + m_PasswordText->GetValue()
+ "@" + m_HostText->GetValue() + ":" + m_PortText->GetValue() + "/"; + "@" + m_HostText->GetValue() + ":" + m_PortText->GetValue() + "/";
return new Url(url.ToStdString()); return new Url(url.ToStdString());
} }

View File

@ -114,7 +114,7 @@ void MainForm::OnTypeSelected(wxTreeEvent& event)
attrs.push_back("__name"); attrs.push_back("__name");
m_ApiClient->GetObjects(type->PluralName, std::bind(&MainForm::ObjectsCompletionHandler, this, _1, _2, true), m_ApiClient->GetObjects(type->PluralName, std::bind(&MainForm::ObjectsCompletionHandler, this, _1, _2, true),
std::vector<String>(), attrs); std::vector<String>(), attrs);
} }
static bool ApiObjectLessComparer(const ApiObject::Ptr& o1, const ApiObject::Ptr& o2) static bool ApiObjectLessComparer(const ApiObject::Ptr& o1, const ApiObject::Ptr& o2)
@ -173,7 +173,7 @@ void MainForm::OnObjectSelected(wxListEvent& event)
names.push_back(objectName); names.push_back(objectName);
m_ApiClient->GetObjects(type->PluralName, std::bind(&MainForm::ObjectDetailsCompletionHandler, this, _1, _2, true), m_ApiClient->GetObjects(type->PluralName, std::bind(&MainForm::ObjectDetailsCompletionHandler, this, _1, _2, true),
names, std::vector<String>(), std::vector<String>(), true); names, std::vector<String>(), std::vector<String>(), true);
} }
wxPGProperty *MainForm::ValueToProperty(const String& name, const Value& value) wxPGProperty *MainForm::ValueToProperty(const String& name, const Value& value)

View File

@ -188,7 +188,7 @@ void Application::SetResourceLimits(void)
if (fileLimit != 0) { if (fileLimit != 0) {
if (fileLimit < GetDefaultRLimitFiles()) { if (fileLimit < GetDefaultRLimitFiles()) {
Log(LogWarning, "Application") Log(LogWarning, "Application")
<< "The user-specified value for RLimitFiles cannot be smaller than the default value (" << GetDefaultRLimitFiles() << "). Using the default value instead."; << "The user-specified value for RLimitFiles cannot be smaller than the default value (" << GetDefaultRLimitFiles() << "). Using the default value instead.";
fileLimit = GetDefaultRLimitFiles(); fileLimit = GetDefaultRLimitFiles();
} }
@ -208,7 +208,7 @@ void Application::SetResourceLimits(void)
if (processLimit != 0) { if (processLimit != 0) {
if (processLimit < GetDefaultRLimitProcesses()) { if (processLimit < GetDefaultRLimitProcesses()) {
Log(LogWarning, "Application") Log(LogWarning, "Application")
<< "The user-specified value for RLimitProcesses cannot be smaller than the default value (" << GetDefaultRLimitProcesses() << "). Using the default value instead."; << "The user-specified value for RLimitProcesses cannot be smaller than the default value (" << GetDefaultRLimitProcesses() << "). Using the default value instead.";
processLimit = GetDefaultRLimitProcesses(); processLimit = GetDefaultRLimitProcesses();
} }
@ -246,7 +246,7 @@ void Application::SetResourceLimits(void)
if (stackLimit != 0) { if (stackLimit != 0) {
if (stackLimit < GetDefaultRLimitStack()) { if (stackLimit < GetDefaultRLimitStack()) {
Log(LogWarning, "Application") Log(LogWarning, "Application")
<< "The user-specified value for RLimitStack cannot be smaller than the default value (" << GetDefaultRLimitStack() << "). Using the default value instead."; << "The user-specified value for RLimitStack cannot be smaller than the default value (" << GetDefaultRLimitStack() << "). Using the default value instead.";
stackLimit = GetDefaultRLimitStack(); stackLimit = GetDefaultRLimitStack();
} }
@ -334,9 +334,9 @@ mainloop:
if (std::fabs(timeDiff) > 15) { if (std::fabs(timeDiff) > 15) {
/* We made a significant jump in time. */ /* We made a significant jump in time. */
Log(LogInformation, "Application") Log(LogInformation, "Application")
<< "We jumped " << "We jumped "
<< (timeDiff < 0 ? "forward" : "backward") << (timeDiff < 0 ? "forward" : "backward")
<< " in time: " << std::fabs(timeDiff) << " seconds"; << " in time: " << std::fabs(timeDiff) << " seconds";
Timer::AdjustTimers(-timeDiff); Timer::AdjustTimers(-timeDiff);
} }
@ -467,8 +467,8 @@ String Application::GetExePath(const String& argv0)
char buffer[MAXPATHLEN]; char buffer[MAXPATHLEN];
if (!getcwd(buffer, sizeof(buffer))) { if (!getcwd(buffer, sizeof(buffer))) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("getcwd") << boost::errinfo_api_function("getcwd")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
String workingDirectory = buffer; String workingDirectory = buffer;
@ -512,9 +512,9 @@ String Application::GetExePath(const String& argv0)
if (!realpath(executablePath.CStr(), buffer)) { if (!realpath(executablePath.CStr(), buffer)) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("realpath") << boost::errinfo_api_function("realpath")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(executablePath)); << boost::errinfo_file_name(executablePath));
} }
return buffer; return buffer;
@ -523,8 +523,8 @@ String Application::GetExePath(const String& argv0)
if (!GetModuleFileName(nullptr, FullExePath, sizeof(FullExePath))) if (!GetModuleFileName(nullptr, FullExePath, sizeof(FullExePath)))
BOOST_THROW_EXCEPTION(win32_error() BOOST_THROW_EXCEPTION(win32_error()
<< boost::errinfo_api_function("GetModuleFileName") << boost::errinfo_api_function("GetModuleFileName")
<< errinfo_win32_error(GetLastError())); << errinfo_win32_error(GetLastError()));
return FullExePath; return FullExePath;
#endif /* _WIN32 */ #endif /* _WIN32 */
@ -541,28 +541,28 @@ void Application::DisplayInfoMessage(std::ostream& os, bool skipVersion)
os << " Application version: " << GetAppVersion() << "\n"; os << " Application version: " << GetAppVersion() << "\n";
os << " Installation root: " << GetPrefixDir() << "\n" os << " Installation root: " << GetPrefixDir() << "\n"
<< " Sysconf directory: " << GetSysconfDir() << "\n" << " Sysconf directory: " << GetSysconfDir() << "\n"
<< " Run directory: " << GetRunDir() << "\n" << " Run directory: " << GetRunDir() << "\n"
<< " Local state directory: " << GetLocalStateDir() << "\n" << " Local state directory: " << GetLocalStateDir() << "\n"
<< " Package data directory: " << GetPkgDataDir() << "\n" << " Package data directory: " << GetPkgDataDir() << "\n"
<< " State path: " << GetStatePath() << "\n" << " State path: " << GetStatePath() << "\n"
<< " Modified attributes path: " << GetModAttrPath() << "\n" << " Modified attributes path: " << GetModAttrPath() << "\n"
<< " Objects path: " << GetObjectsPath() << "\n" << " Objects path: " << GetObjectsPath() << "\n"
<< " Vars path: " << GetVarsPath() << "\n" << " Vars path: " << GetVarsPath() << "\n"
<< " PID path: " << GetPidPath() << "\n"; << " PID path: " << GetPidPath() << "\n";
os << "\n" os << "\n"
<< "System information:" << "\n" << "System information:" << "\n"
<< " Platform: " << Utility::GetPlatformName() << "\n" << " Platform: " << Utility::GetPlatformName() << "\n"
<< " Platform version: " << Utility::GetPlatformVersion() << "\n" << " Platform version: " << Utility::GetPlatformVersion() << "\n"
<< " Kernel: " << Utility::GetPlatformKernel() << "\n" << " Kernel: " << Utility::GetPlatformKernel() << "\n"
<< " Kernel version: " << Utility::GetPlatformKernelVersion() << "\n" << " Kernel version: " << Utility::GetPlatformKernelVersion() << "\n"
<< " Architecture: " << Utility::GetPlatformArchitecture() << "\n"; << " Architecture: " << Utility::GetPlatformArchitecture() << "\n";
os << "\n" os << "\n"
<< "Build information:" << "\n" << "Build information:" << "\n"
<< " Compiler: " << ScriptGlobal::Get("BuildCompilerName") << " " << ScriptGlobal::Get("BuildCompilerVersion") << "\n" << " Compiler: " << ScriptGlobal::Get("BuildCompilerName") << " " << ScriptGlobal::Get("BuildCompilerVersion") << "\n"
<< " Build host: " << ScriptGlobal::Get("BuildHostName") << "\n"; << " Build host: " << ScriptGlobal::Get("BuildHostName") << "\n";
} }
/** /**
@ -571,10 +571,10 @@ void Application::DisplayInfoMessage(std::ostream& os, bool skipVersion)
void Application::DisplayBugMessage(std::ostream& os) void Application::DisplayBugMessage(std::ostream& os)
{ {
os << "***" << "\n" os << "***" << "\n"
<< "* This would indicate a runtime problem or configuration error. If you believe this is a bug in Icinga 2" << "\n" << "* This would indicate a runtime problem or configuration error. If you believe this is a bug in Icinga 2" << "\n"
<< "* please submit a bug report at https://github.com/Icinga/icinga2 and include this stack trace as well as any other" << "\n" << "* please submit a bug report at https://github.com/Icinga/icinga2 and include this stack trace as well as any other" << "\n"
<< "* information that might be useful in order to reproduce this problem." << "\n" << "* information that might be useful in order to reproduce this problem." << "\n"
<< "***" << "\n"; << "***" << "\n";
} }
String Application::GetCrashReportFilename(void) String Application::GetCrashReportFilename(void)
@ -596,8 +596,8 @@ void Application::AttachDebugger(const String& filename, bool interactive)
if (pid < 0) { if (pid < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("fork") << boost::errinfo_api_function("fork")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
if (pid == 0) { if (pid == 0) {
@ -606,9 +606,9 @@ void Application::AttachDebugger(const String& filename, bool interactive)
if (fd < 0) { if (fd < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("open") << boost::errinfo_api_function("open")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(filename)); << boost::errinfo_file_name(filename));
} }
if (fd != 1) { if (fd != 1) {
@ -666,8 +666,8 @@ void Application::AttachDebugger(const String& filename, bool interactive)
int status; int status;
if (waitpid(pid, &status, 0) < 0) { if (waitpid(pid, &status, 0) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("waitpid") << boost::errinfo_api_function("waitpid")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
#ifdef __linux__ #ifdef __linux__
@ -727,8 +727,8 @@ void Application::SigAbrtHandler(int)
#endif /* _WIN32 */ #endif /* _WIN32 */
std::cerr << "Caught SIGABRT." << std::endl std::cerr << "Caught SIGABRT." << std::endl
<< "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << std::endl << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << std::endl
<< std::endl; << std::endl;
String fname = GetCrashReportFilename(); String fname = GetCrashReportFilename();
String dirName = Utility::DirName(fname); String dirName = Utility::DirName(fname);
@ -750,7 +750,7 @@ void Application::SigAbrtHandler(int)
ofs.open(fname.CStr()); ofs.open(fname.CStr());
Log(LogCritical, "Application") Log(LogCritical, "Application")
<< "Icinga 2 has terminated unexpectedly. Additional information can be found in '" << fname << "'" << "\n"; << "Icinga 2 has terminated unexpectedly. Additional information can be found in '" << fname << "'" << "\n";
DisplayInfoMessage(ofs); DisplayInfoMessage(ofs);
@ -860,8 +860,8 @@ void Application::ExceptionHandler(void)
ofs.open(fname.CStr()); ofs.open(fname.CStr());
ofs << "Caught unhandled exception." << "\n" ofs << "Caught unhandled exception." << "\n"
<< "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n" << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n"
<< "\n"; << "\n";
DisplayInfoMessage(ofs); DisplayInfoMessage(ofs);
@ -869,13 +869,13 @@ void Application::ExceptionHandler(void)
RethrowUncaughtException(); RethrowUncaughtException();
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "Application") Log(LogCritical, "Application")
<< DiagnosticInformation(ex, false) << "\n" << DiagnosticInformation(ex, false) << "\n"
<< "\n" << "\n"
<< "Additional information is available in '" << fname << "'" << "\n"; << "Additional information is available in '" << fname << "'" << "\n";
ofs << "\n" ofs << "\n"
<< DiagnosticInformation(ex) << DiagnosticInformation(ex)
<< "\n"; << "\n";
} }
DisplayBugMessage(ofs); DisplayBugMessage(ofs);
@ -913,13 +913,13 @@ LONG CALLBACK Application::SEHUnhandledExceptionFilter(PEXCEPTION_POINTERS exi)
ofs.open(fname.CStr()); ofs.open(fname.CStr());
Log(LogCritical, "Application") Log(LogCritical, "Application")
<< "Icinga 2 has terminated unexpectedly. Additional information can be found in '" << fname << "'"; << "Icinga 2 has terminated unexpectedly. Additional information can be found in '" << fname << "'";
DisplayInfoMessage(ofs); DisplayInfoMessage(ofs);
ofs << "Caught unhandled SEH exception." << "\n" ofs << "Caught unhandled SEH exception." << "\n"
<< "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n" << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n"
<< "\n"; << "\n";
StackTrace trace(exi); StackTrace trace(exi);
ofs << "Stacktrace:" << "\n"; ofs << "Stacktrace:" << "\n";
@ -972,7 +972,7 @@ int Application::Run(void)
UpdatePidFile(GetPidPath()); UpdatePidFile(GetPidPath());
} catch (const std::exception&) { } catch (const std::exception&) {
Log(LogCritical, "Application") Log(LogCritical, "Application")
<< "Cannot update PID file '" << GetPidPath() << "'. Aborting."; << "Cannot update PID file '" << GetPidPath() << "'. Aborting.";
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -1004,7 +1004,7 @@ void Application::UpdatePidFile(const String& filename, pid_t pid)
if (!m_PidFile) { if (!m_PidFile) {
Log(LogCritical, "Application") Log(LogCritical, "Application")
<< "Could not open PID file '" << filename << "'."; << "Could not open PID file '" << filename << "'.";
BOOST_THROW_EXCEPTION(std::runtime_error("Could not open PID file '" + filename + "'")); BOOST_THROW_EXCEPTION(std::runtime_error("Could not open PID file '" + filename + "'"));
} }
@ -1028,11 +1028,11 @@ void Application::UpdatePidFile(const String& filename, pid_t pid)
if (ftruncate(fd, 0) < 0) { if (ftruncate(fd, 0) < 0) {
Log(LogCritical, "Application") Log(LogCritical, "Application")
<< "ftruncate() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "ftruncate() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("ftruncate") << boost::errinfo_api_function("ftruncate")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
#endif /* _WIN32 */ #endif /* _WIN32 */
@ -1086,8 +1086,8 @@ pid_t Application::ReadPidFile(const String& filename)
int error = errno; int error = errno;
fclose(pidfile); fclose(pidfile);
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("fcntl") << boost::errinfo_api_function("fcntl")
<< boost::errinfo_errno(error)); << boost::errinfo_errno(error));
} }
if (lock.l_type == F_UNLCK) { if (lock.l_type == F_UNLCK) {

View File

@ -179,11 +179,9 @@ protected:
private: private:
static Application::Ptr m_Instance; /**< The application instance. */ static Application::Ptr m_Instance; /**< The application instance. */
static bool m_ShuttingDown; /**< Whether the application is in the process of static bool m_ShuttingDown; /**< Whether the application is in the process of shutting down. */
shutting down. */
static bool m_RequestRestart; /**< A restart was requested through SIGHUP */ static bool m_RequestRestart; /**< A restart was requested through SIGHUP */
static pid_t m_ReloadProcess; /**< The PID of a subprocess doing a reload, static pid_t m_ReloadProcess; /**< The PID of a subprocess doing a reload, only valid when l_Restarting==true */
only valid when l_Restarting==true */
static bool m_RequestReopenLogs; /**< Whether we should re-open log files. */ static bool m_RequestReopenLogs; /**< Whether we should re-open log files. */
static int m_ArgC; /**< The number of command-line arguments. */ static int m_ArgC; /**< The number of command-line arguments. */

View File

@ -201,7 +201,7 @@ Array::Ptr Array::ShallowClone(void) const
/** /**
* Makes a deep clone of an array * Makes a deep clone of an array
* and its elements. * and its elements.
* *
* @returns a copy of the array. * @returns a copy of the array.
*/ */
Object::Ptr Array::Clone(void) const Object::Ptr Array::Clone(void) const

View File

@ -51,7 +51,7 @@ public:
{ } { }
Array(std::initializer_list<Value> init) Array(std::initializer_list<Value> init)
: m_Data(init) : m_Data(init)
{ } { }
~Array(void) ~Array(void)

View File

@ -46,7 +46,7 @@ String Base64::Encode(const String& input)
String Base64::Decode(const String& input) String Base64::Decode(const String& input)
{ {
BIO *biomem = BIO_new_mem_buf( BIO *biomem = BIO_new_mem_buf(
const_cast<char*>(input.CStr()), input.GetLength()); const_cast<char*>(input.CStr()), input.GetLength());
BIO *bio64 = BIO_new(BIO_f_base64()); BIO *bio64 = BIO_new(BIO_f_base64());
BIO_push(bio64, biomem); BIO_push(bio64, biomem);
BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL); BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);

View File

@ -491,7 +491,7 @@ void ConfigObject::SetAuthority(bool authority)
void ConfigObject::DumpObjects(const String& filename, int attributeTypes) void ConfigObject::DumpObjects(const String& filename, int attributeTypes)
{ {
Log(LogInformation, "ConfigObject") Log(LogInformation, "ConfigObject")
<< "Dumping program state to file '" << filename << "'"; << "Dumping program state to file '" << filename << "'";
std::fstream fp; std::fstream fp;
String tempFilename = Utility::CreateTempFile(filename + ".XXXXXX", 0600, fp); String tempFilename = Utility::CreateTempFile(filename + ".XXXXXX", 0600, fp);
@ -537,9 +537,9 @@ void ConfigObject::DumpObjects(const String& filename, int attributeTypes)
if (rename(tempFilename.CStr(), filename.CStr()) < 0) { if (rename(tempFilename.CStr(), filename.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempFilename)); << boost::errinfo_file_name(tempFilename));
} }
} }
@ -557,7 +557,7 @@ void ConfigObject::RestoreObject(const String& message, int attributeTypes)
#ifdef I2_DEBUG #ifdef I2_DEBUG
Log(LogDebug, "ConfigObject") Log(LogDebug, "ConfigObject")
<< "Restoring object '" << name << "' of type '" << type << "'."; << "Restoring object '" << name << "' of type '" << type << "'.";
#endif /* I2_DEBUG */ #endif /* I2_DEBUG */
Dictionary::Ptr update = persistentObject->Get("update"); Dictionary::Ptr update = persistentObject->Get("update");
Deserialize(object, update, false, attributeTypes); Deserialize(object, update, false, attributeTypes);
@ -571,7 +571,7 @@ void ConfigObject::RestoreObjects(const String& filename, int attributeTypes)
return; return;
Log(LogInformation, "ConfigObject") Log(LogInformation, "ConfigObject")
<< "Restoring program state from file '" << filename << "'"; << "Restoring program state from file '" << filename << "'";
std::fstream fp; std::fstream fp;
fp.open(filename.CStr(), std::ios_base::in); fp.open(filename.CStr(), std::ios_base::in);
@ -621,7 +621,7 @@ void ConfigObject::RestoreObjects(const String& filename, int attributeTypes)
} }
Log(LogInformation, "ConfigObject") Log(LogInformation, "ConfigObject")
<< "Restored " << restored << " objects. Loaded " << no_state << " new objects without state."; << "Restored " << restored << " objects. Loaded " << no_state << " new objects without state.";
} }
void ConfigObject::StopObjects(void) void ConfigObject::StopObjects(void)

View File

@ -54,8 +54,8 @@ void ConfigType::RegisterObject(const ConfigObject::Ptr& object)
Type *type = dynamic_cast<Type *>(this); Type *type = dynamic_cast<Type *>(this);
BOOST_THROW_EXCEPTION(ScriptError("An object with type '" + type->GetName() + "' and name '" + name + "' already exists (" + BOOST_THROW_EXCEPTION(ScriptError("An object with type '" + type->GetName() + "' and name '" + name + "' already exists (" +
Convert::ToString(it->second->GetDebugInfo()) + "), new declaration: " + Convert::ToString(object->GetDebugInfo()), Convert::ToString(it->second->GetDebugInfo()) + "), new declaration: " + Convert::ToString(object->GetDebugInfo()),
object->GetDebugInfo())); object->GetDebugInfo()));
} }
m_ObjectMap[name] = object; m_ObjectMap[name] = object;

View File

@ -73,7 +73,7 @@ void ConfigWriter::EmitArrayItems(std::ostream& fp, int indentLevel, const Array
} }
void ConfigWriter::EmitScope(std::ostream& fp, int indentLevel, const Dictionary::Ptr& val, void ConfigWriter::EmitScope(std::ostream& fp, int indentLevel, const Dictionary::Ptr& val,
const Array::Ptr& imports, bool splitDot) const Array::Ptr& imports, bool splitDot)
{ {
fp << "{"; fp << "{";
@ -176,7 +176,7 @@ void ConfigWriter::EmitIdentifier(std::ostream& fp, const String& identifier, bo
} }
void ConfigWriter::EmitConfigItem(std::ostream& fp, const String& type, const String& name, bool isTemplate, void ConfigWriter::EmitConfigItem(std::ostream& fp, const String& type, const String& name, bool isTemplate,
bool ignoreOnError, const Array::Ptr& imports, const Dictionary::Ptr& attrs) bool ignoreOnError, const Array::Ptr& imports, const Dictionary::Ptr& attrs)
{ {
if (isTemplate) if (isTemplate)
fp << "template "; fp << "template ";
@ -270,7 +270,7 @@ const std::vector<String>& ConfigWriter::GetKeywords(void)
} }
ConfigIdentifier::ConfigIdentifier(const String& identifier) ConfigIdentifier::ConfigIdentifier(const String& identifier)
: m_Name(identifier) : m_Name(identifier)
{ } { }
String ConfigIdentifier::GetName(void) const String ConfigIdentifier::GetName(void) const

View File

@ -61,14 +61,14 @@ public:
static void EmitArray(std::ostream& fp, int indentLevel, const Array::Ptr& val); static void EmitArray(std::ostream& fp, int indentLevel, const Array::Ptr& val);
static void EmitArrayItems(std::ostream& fp, int indentLevel, const Array::Ptr& val); static void EmitArrayItems(std::ostream& fp, int indentLevel, const Array::Ptr& val);
static void EmitScope(std::ostream& fp, int indentLevel, const Dictionary::Ptr& val, static void EmitScope(std::ostream& fp, int indentLevel, const Dictionary::Ptr& val,
const Array::Ptr& imports = nullptr, bool splitDot = false); const Array::Ptr& imports = nullptr, bool splitDot = false);
static void EmitValue(std::ostream& fp, int indentLevel, const Value& val); static void EmitValue(std::ostream& fp, int indentLevel, const Value& val);
static void EmitRaw(std::ostream& fp, const String& val); static void EmitRaw(std::ostream& fp, const String& val);
static void EmitIndent(std::ostream& fp, int indentLevel); static void EmitIndent(std::ostream& fp, int indentLevel);
static void EmitIdentifier(std::ostream& fp, const String& identifier, bool inAssignment); static void EmitIdentifier(std::ostream& fp, const String& identifier, bool inAssignment);
static void EmitConfigItem(std::ostream& fp, const String& type, const String& name, bool isTemplate, static void EmitConfigItem(std::ostream& fp, const String& type, const String& name, bool isTemplate,
bool ignoreOnError, const Array::Ptr& imports, const Dictionary::Ptr& attrs); bool ignoreOnError, const Array::Ptr& imports, const Dictionary::Ptr& attrs);
static void EmitComment(std::ostream& fp, const String& text); static void EmitComment(std::ostream& fp, const String& text);
static void EmitFunctionCall(std::ostream& fp, const String& name, const Array::Ptr& arguments); static void EmitFunctionCall(std::ostream& fp, const String& name, const Array::Ptr& arguments);

View File

@ -37,9 +37,9 @@ DebugInfo::DebugInfo(void)
std::ostream& icinga::operator<<(std::ostream& out, const DebugInfo& val) std::ostream& icinga::operator<<(std::ostream& out, const DebugInfo& val)
{ {
out << "in " << val.Path << ": " out << "in " << val.Path << ": "
<< val.FirstLine << ":" << val.FirstColumn << val.FirstLine << ":" << val.FirstColumn
<< "-" << "-"
<< val.LastLine << ":" << val.LastColumn; << val.LastLine << ":" << val.LastColumn;
return out; return out;
} }

View File

@ -27,7 +27,7 @@ using namespace icinga;
REGISTER_TYPE_WITH_PROTOTYPE(Function, Function::GetPrototype()); REGISTER_TYPE_WITH_PROTOTYPE(Function, Function::GetPrototype());
Function::Function(const String& name, const Callback& function, const std::vector<String>& args, Function::Function(const String& name, const Callback& function, const std::vector<String>& args,
bool side_effect_free, bool deprecated) bool side_effect_free, bool deprecated)
: m_Callback(function) : m_Callback(function)
{ {
SetName(name, true); SetName(name, true);

View File

@ -44,8 +44,8 @@ public:
template<typename F> template<typename F>
Function(const String& name, F function, const std::vector<String>& args = std::vector<String>(), Function(const String& name, F function, const std::vector<String>& args = std::vector<String>(),
bool side_effect_free = false, bool deprecated = false) bool side_effect_free = false, bool deprecated = false)
: Function(name, WrapFunction(function), args, side_effect_free, deprecated) : Function(name, WrapFunction(function), args, side_effect_free, deprecated)
{ } { }
Value Invoke(const std::vector<Value>& arguments = std::vector<Value>()); Value Invoke(const std::vector<Value>& arguments = std::vector<Value>());
@ -69,7 +69,7 @@ private:
Callback m_Callback; Callback m_Callback;
Function(const String& name, const Callback& function, const std::vector<String>& args, Function(const String& name, const Callback& function, const std::vector<String>& args,
bool side_effect_free, bool deprecated); bool side_effect_free, bool deprecated);
}; };
#define REGISTER_SCRIPTFUNCTION_NS(ns, name, callback, args) \ #define REGISTER_SCRIPTFUNCTION_NS(ns, name, callback, args) \

View File

@ -89,8 +89,7 @@ private:
public: public:
template <typename FuncType, int Arity> template <typename FuncType, int Arity>
auto operator() (FuncType f, const std::vector<Value>& args) auto operator() (FuncType f, const std::vector<Value>& args) -> decltype(Invoke(f, args, BuildIndices<Arity>{}))
-> decltype(Invoke(f, args, BuildIndices<Arity>{}))
{ {
return Invoke(f, args, BuildIndices<Arity>{}); return Invoke(f, args, BuildIndices<Arity>{});
} }
@ -117,8 +116,8 @@ struct FunctionWrapper<FuncType, Arity, void>
template<typename FuncType> template<typename FuncType>
typename std::enable_if< typename std::enable_if<
std::is_function<typename std::remove_pointer<FuncType>::type>::value && !std::is_same<FuncType, Value(*)(const std::vector<Value>&)>::value, std::is_function<typename std::remove_pointer<FuncType>::type>::value && !std::is_same<FuncType, Value(*)(const std::vector<Value>&)>::value,
std::function<Value (const std::vector<Value>&)>>::type std::function<Value (const std::vector<Value>&)>>::type
WrapFunction(FuncType function) WrapFunction(FuncType function)
{ {
return [function](const std::vector<Value>& arguments) { return [function](const std::vector<Value>& arguments) {

View File

@ -41,16 +41,16 @@ void Loader::LoadExtensionLibrary(const String& library)
#endif /* _WIN32 */ #endif /* _WIN32 */
Log(LogNotice, "Loader") Log(LogNotice, "Loader")
<< "Loading library '" << path << "'"; << "Loading library '" << path << "'";
#ifdef _WIN32 #ifdef _WIN32
HMODULE hModule = LoadLibrary(path.CStr()); HMODULE hModule = LoadLibrary(path.CStr());
if (!hModule) { if (!hModule) {
BOOST_THROW_EXCEPTION(win32_error() BOOST_THROW_EXCEPTION(win32_error()
<< boost::errinfo_api_function("LoadLibrary") << boost::errinfo_api_function("LoadLibrary")
<< errinfo_win32_error(GetLastError()) << errinfo_win32_error(GetLastError())
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
} }
#else /* _WIN32 */ #else /* _WIN32 */
void *hModule = dlopen(path.CStr(), RTLD_NOW | RTLD_GLOBAL); void *hModule = dlopen(path.CStr(), RTLD_NOW | RTLD_GLOBAL);

View File

@ -32,7 +32,7 @@ struct DeferredInitializer
{ {
public: public:
DeferredInitializer(const std::function<void (void)>& callback, int priority) DeferredInitializer(const std::function<void (void)>& callback, int priority)
: m_Callback(callback), m_Priority(priority) : m_Callback(callback), m_Priority(priority)
{ } { }
bool operator<(const DeferredInitializer& other) const bool operator<(const DeferredInitializer& other) const

View File

@ -81,7 +81,7 @@ std::set<Logger::Ptr> Logger::GetLoggers(void)
* @param message The message. * @param message The message.
*/ */
void icinga::IcingaLog(LogSeverity severity, const String& facility, void icinga::IcingaLog(LogSeverity severity, const String& facility,
const String& message) const String& message)
{ {
LogEntry entry; LogEntry entry;
entry.Timestamp = Utility::GetTime(); entry.Timestamp = Utility::GetTime();

View File

@ -247,7 +247,7 @@ static void TypeInfoTimerHandler(void)
continue; continue;
Log(LogInformation, "TypeInfo") Log(LogInformation, "TypeInfo")
<< kv.second << " " << kv.first << " objects"; << kv.second << " " << kv.first << " objects";
kv.second = 0; kv.second = 0;
} }

View File

@ -36,8 +36,8 @@ PerfdataValue::PerfdataValue(void)
{ } { }
PerfdataValue::PerfdataValue(String label, double value, bool counter, PerfdataValue::PerfdataValue(String label, double value, bool counter,
const String& unit, const Value& warn, const Value& crit, const Value& min, const String& unit, const Value& warn, const Value& crit, const Value& min,
const Value& max) const Value& max)
{ {
SetLabel(label, true); SetLabel(label, true);
SetValue(value, true); SetValue(value, true);
@ -189,7 +189,7 @@ Value PerfdataValue::ParseWarnCritMinMaxToken(const std::vector<String>& tokens,
else { else {
if (tokens.size() > index && tokens[index] != "") if (tokens.size() > index && tokens[index] != "")
Log(LogDebug, "PerfdataValue") Log(LogDebug, "PerfdataValue")
<< "Ignoring unsupported perfdata " << description << " range, value: '" << tokens[index] << "'."; << "Ignoring unsupported perfdata " << description << " range, value: '" << tokens[index] << "'.";
return Empty; return Empty;
} }
} }

View File

@ -39,15 +39,15 @@ public:
PerfdataValue(void); PerfdataValue(void);
PerfdataValue(String label, double value, bool counter = false, const String& unit = "", PerfdataValue(String label, double value, bool counter = false, const String& unit = "",
const Value& warn = Empty, const Value& crit = Empty, const Value& warn = Empty, const Value& crit = Empty,
const Value& min = Empty, const Value& max = Empty); const Value& min = Empty, const Value& max = Empty);
static PerfdataValue::Ptr Parse(const String& perfdata); static PerfdataValue::Ptr Parse(const String& perfdata);
String Format(void) const; String Format(void) const;
private: private:
static Value ParseWarnCritMinMaxToken(const std::vector<String>& tokens, static Value ParseWarnCritMinMaxToken(const std::vector<String>& tokens,
std::vector<String>::size_type index, const String& description); std::vector<String>::size_type index, const String& description);
}; };
} }

View File

@ -325,8 +325,8 @@ static void ProcessHandler(void)
if (send(l_ProcessControlFD, jresponse.CStr(), jresponse.GetLength(), 0) < 0) { if (send(l_ProcessControlFD, jresponse.CStr(), jresponse.GetLength(), 0) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("send") << boost::errinfo_api_function("send")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
} }
@ -345,16 +345,16 @@ static void StartSpawnProcessHelper(void)
int controlFDs[2]; int controlFDs[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, controlFDs) < 0) { if (socketpair(AF_UNIX, SOCK_STREAM, 0, controlFDs) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("socketpair") << boost::errinfo_api_function("socketpair")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
pid_t pid = fork(); pid_t pid = fork();
if (pid < 0) { if (pid < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("fork") << boost::errinfo_api_function("fork")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
if (pid == 0) { if (pid == 0) {
@ -516,8 +516,8 @@ static void InitializeProcess(void)
# endif /* HAVE_PIPE2 */ # endif /* HAVE_PIPE2 */
if (pipe(l_EventFDs[tid]) < 0) { if (pipe(l_EventFDs[tid]) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("pipe") << boost::errinfo_api_function("pipe")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
Utility::SetCloExec(l_EventFDs[tid][0]); Utility::SetCloExec(l_EventFDs[tid][0]);
@ -755,7 +755,7 @@ String Process::PrettyPrintArguments(const Process::Arguments& arguments)
#ifdef _WIN32 #ifdef _WIN32
static BOOL CreatePipeOverlapped(HANDLE *outReadPipe, HANDLE *outWritePipe, static BOOL CreatePipeOverlapped(HANDLE *outReadPipe, HANDLE *outWritePipe,
SECURITY_ATTRIBUTES *securityAttributes, DWORD size, DWORD readMode, DWORD writeMode) SECURITY_ATTRIBUTES *securityAttributes, DWORD size, DWORD readMode, DWORD writeMode)
{ {
static LONG pipeIndex = 0; static LONG pipeIndex = 0;
@ -768,7 +768,7 @@ static BOOL CreatePipeOverlapped(HANDLE *outReadPipe, HANDLE *outWritePipe,
sprintf(pipeName, "\\\\.\\Pipe\\OverlappedPipe.%d.%d", (int)GetCurrentProcessId(), (int)currentIndex); sprintf(pipeName, "\\\\.\\Pipe\\OverlappedPipe.%d.%d", (int)GetCurrentProcessId(), (int)currentIndex);
*outReadPipe = CreateNamedPipe(pipeName, PIPE_ACCESS_INBOUND | readMode, *outReadPipe = CreateNamedPipe(pipeName, PIPE_ACCESS_INBOUND | readMode,
PIPE_TYPE_BYTE | PIPE_WAIT, 1, size, size, 60 * 1000, securityAttributes); PIPE_TYPE_BYTE | PIPE_WAIT, 1, size, size, 60 * 1000, securityAttributes);
if (*outReadPipe == INVALID_HANDLE_VALUE) if (*outReadPipe == INVALID_HANDLE_VALUE)
return FALSE; return FALSE;
@ -813,7 +813,7 @@ void Process::Run(const std::function<void(const ProcessResult&)>& callback)
HANDLE outWritePipeDup; HANDLE outWritePipeDup;
if (!DuplicateHandle(GetCurrentProcess(), outWritePipe, GetCurrentProcess(), if (!DuplicateHandle(GetCurrentProcess(), outWritePipe, GetCurrentProcess(),
&outWritePipeDup, 0, TRUE, DUPLICATE_SAME_ACCESS)) &outWritePipeDup, 0, TRUE, DUPLICATE_SAME_ACCESS))
BOOST_THROW_EXCEPTION(win32_error() BOOST_THROW_EXCEPTION(win32_error()
<< boost::errinfo_api_function("DuplicateHandle") << boost::errinfo_api_function("DuplicateHandle")
<< errinfo_win32_error(GetLastError())); << errinfo_win32_error(GetLastError()));
@ -839,7 +839,7 @@ void Process::Run(const std::function<void(const ProcessResult&)>& callback)
rgHandles[2] = GetStdHandle(STD_INPUT_HANDLE); rgHandles[2] = GetStdHandle(STD_INPUT_HANDLE);
if (!UpdateProcThreadAttribute(lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, if (!UpdateProcThreadAttribute(lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
rgHandles, sizeof(rgHandles), nullptr, nullptr)) rgHandles, sizeof(rgHandles), nullptr, nullptr))
BOOST_THROW_EXCEPTION(win32_error() BOOST_THROW_EXCEPTION(win32_error()
<< boost::errinfo_api_function("UpdateProcThreadAttribute") << boost::errinfo_api_function("UpdateProcThreadAttribute")
<< errinfo_win32_error(GetLastError())); << errinfo_win32_error(GetLastError()));
@ -912,7 +912,7 @@ void Process::Run(const std::function<void(const ProcessResult&)>& callback)
envp[offset] = '\0'; envp[offset] = '\0';
if (!CreateProcess(nullptr, args, nullptr, nullptr, TRUE, if (!CreateProcess(nullptr, args, nullptr, nullptr, TRUE,
0 /*EXTENDED_STARTUPINFO_PRESENT*/, envp, nullptr, &si.StartupInfo, &pi)) { 0 /*EXTENDED_STARTUPINFO_PRESENT*/, envp, nullptr, &si.StartupInfo, &pi)) {
DWORD error = GetLastError(); DWORD error = GetLastError();
CloseHandle(outWritePipe); CloseHandle(outWritePipe);
CloseHandle(outWritePipeDup); CloseHandle(outWritePipeDup);
@ -947,7 +947,7 @@ void Process::Run(const std::function<void(const ProcessResult&)>& callback)
m_PID = pi.dwProcessId; m_PID = pi.dwProcessId;
Log(LogNotice, "Process") Log(LogNotice, "Process")
<< "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID; << "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID;
#else /* _WIN32 */ #else /* _WIN32 */
int outfds[2]; int outfds[2];
@ -958,8 +958,8 @@ void Process::Run(const std::function<void(const ProcessResult&)>& callback)
#endif /* HAVE_PIPE2 */ #endif /* HAVE_PIPE2 */
if (pipe(outfds) < 0) { if (pipe(outfds) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("pipe") << boost::errinfo_api_function("pipe")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
Utility::SetCloExec(outfds[0]); Utility::SetCloExec(outfds[0]);
@ -987,7 +987,7 @@ void Process::Run(const std::function<void(const ProcessResult&)>& callback)
} }
Log(LogNotice, "Process") Log(LogNotice, "Process")
<< "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID; << "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID;
(void)close(outfds[1]); (void)close(outfds[1]);
@ -1028,8 +1028,8 @@ bool Process::DoEvents(void)
if (timeout < Utility::GetTime()) { if (timeout < Utility::GetTime()) {
Log(LogWarning, "Process") Log(LogWarning, "Process")
<< "Killing process group " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << "Killing process group " << m_PID << " (" << PrettyPrintArguments(m_Arguments)
<< ") after timeout of " << m_Timeout << " seconds"; << ") after timeout of " << m_Timeout << " seconds";
m_OutputStream << "<Timeout exceeded.>"; m_OutputStream << "<Timeout exceeded.>";
#ifdef _WIN32 #ifdef _WIN32
@ -1038,8 +1038,8 @@ bool Process::DoEvents(void)
int error = ProcessKill(-m_Process, SIGKILL); int error = ProcessKill(-m_Process, SIGKILL);
if (error) { if (error) {
Log(LogWarning, "Process") Log(LogWarning, "Process")
<< "Couldn't kill the process group " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << "Couldn't kill the process group " << m_PID << " (" << PrettyPrintArguments(m_Arguments)
<< "): [errno " << error << "] " << strerror(error); << "): [errno " << error << "] " << strerror(error);
could_not_kill = true; could_not_kill = true;
} }
#endif /* _WIN32 */ #endif /* _WIN32 */
@ -1084,7 +1084,7 @@ bool Process::DoEvents(void)
GetExitCodeProcess(m_Process, &exitcode); GetExitCodeProcess(m_Process, &exitcode);
Log(LogNotice, "Process") Log(LogNotice, "Process")
<< "PID " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << ") terminated with exit code " << exitcode; << "PID " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << ") terminated with exit code " << exitcode;
#else /* _WIN32 */ #else /* _WIN32 */
int status, exitcode; int status, exitcode;
if (could_not_kill || m_PID == -1) { if (could_not_kill || m_PID == -1) {
@ -1093,12 +1093,12 @@ bool Process::DoEvents(void)
exitcode = 128; exitcode = 128;
Log(LogWarning, "Process") Log(LogWarning, "Process")
<< "PID " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << ") died mysteriously: waitpid failed"; << "PID " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << ") died mysteriously: waitpid failed";
} else if (WIFEXITED(status)) { } else if (WIFEXITED(status)) {
exitcode = WEXITSTATUS(status); exitcode = WEXITSTATUS(status);
Log(LogNotice, "Process") Log(LogNotice, "Process")
<< "PID " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << ") terminated with exit code " << exitcode; << "PID " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << ") terminated with exit code " << exitcode;
} else if (WIFSIGNALED(status)) { } else if (WIFSIGNALED(status)) {
int signum = WTERMSIG(status); int signum = WTERMSIG(status);
const char *zsigname = strsignal(signum); const char *zsigname = strsignal(signum);
@ -1112,7 +1112,7 @@ bool Process::DoEvents(void)
} }
Log(LogWarning, "Process") Log(LogWarning, "Process")
<< "PID " << m_PID << " was terminated by signal " << signame; << "PID " << m_PID << " was terminated by signal " << signame;
std::ostringstream outputbuf; std::ostringstream outputbuf;
outputbuf << "<Terminated by signal " << signame << ".>"; outputbuf << "<Terminated by signal " << signame << ".>";

View File

@ -373,7 +373,7 @@ Array::Ptr ScriptUtils::Range(const std::vector<Value>& arguments)
Array::Ptr result = new Array(); Array::Ptr result = new Array();
if ((start < end && increment <= 0) || if ((start < end && increment <= 0) ||
(start > end && increment >= 0)) (start > end && increment >= 0))
return result; return result;
for (double i = start; (increment > 0 ? i < end : i > end); i += increment) for (double i = start; (increment > 0 ? i < end : i > end); i += increment)

View File

@ -130,21 +130,21 @@ String Socket::GetAddressFromSockaddr(sockaddr *address, socklen_t len)
char service[NI_MAXSERV]; char service[NI_MAXSERV];
if (getnameinfo(address, len, host, sizeof(host), service, if (getnameinfo(address, len, host, sizeof(host), service,
sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0) { sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
#ifndef _WIN32 #ifndef _WIN32
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "getnameinfo() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "getnameinfo() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("getnameinfo") << boost::errinfo_api_function("getnameinfo")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
#else /* _WIN32 */ #else /* _WIN32 */
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "getnameinfo() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; << "getnameinfo() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("getnameinfo") << boost::errinfo_api_function("getnameinfo")
<< errinfo_win32_error(WSAGetLastError())); << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */ #endif /* _WIN32 */
} }
@ -168,18 +168,18 @@ String Socket::GetClientAddress(void)
if (getsockname(GetFD(), (sockaddr *)&sin, &len) < 0) { if (getsockname(GetFD(), (sockaddr *)&sin, &len) < 0) {
#ifndef _WIN32 #ifndef _WIN32
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "getsockname() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "getsockname() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("getsockname") << boost::errinfo_api_function("getsockname")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
#else /* _WIN32 */ #else /* _WIN32 */
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "getsockname() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; << "getsockname() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("getsockname") << boost::errinfo_api_function("getsockname")
<< errinfo_win32_error(WSAGetLastError())); << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */ #endif /* _WIN32 */
} }
@ -208,18 +208,18 @@ String Socket::GetPeerAddress(void)
if (getpeername(GetFD(), (sockaddr *)&sin, &len) < 0) { if (getpeername(GetFD(), (sockaddr *)&sin, &len) < 0) {
#ifndef _WIN32 #ifndef _WIN32
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "getpeername() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "getpeername() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("getpeername") << boost::errinfo_api_function("getpeername")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
#else /* _WIN32 */ #else /* _WIN32 */
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "getpeername() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; << "getpeername() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("getpeername") << boost::errinfo_api_function("getpeername")
<< errinfo_win32_error(WSAGetLastError())); << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */ #endif /* _WIN32 */
} }
@ -241,18 +241,18 @@ void Socket::Listen(void)
if (listen(GetFD(), SOMAXCONN) < 0) { if (listen(GetFD(), SOMAXCONN) < 0) {
#ifndef _WIN32 #ifndef _WIN32
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "listen() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "listen() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("listen") << boost::errinfo_api_function("listen")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
#else /* _WIN32 */ #else /* _WIN32 */
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "listen() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; << "listen() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("listen") << boost::errinfo_api_function("listen")
<< errinfo_win32_error(WSAGetLastError())); << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */ #endif /* _WIN32 */
} }
} }
@ -273,18 +273,18 @@ size_t Socket::Write(const void *buffer, size_t count)
if (rc < 0) { if (rc < 0) {
#ifndef _WIN32 #ifndef _WIN32
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "send() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "send() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("send") << boost::errinfo_api_function("send")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
#else /* _WIN32 */ #else /* _WIN32 */
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "send() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; << "send() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("send") << boost::errinfo_api_function("send")
<< errinfo_win32_error(WSAGetLastError())); << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */ #endif /* _WIN32 */
} }
@ -307,18 +307,18 @@ size_t Socket::Read(void *buffer, size_t count)
if (rc < 0) { if (rc < 0) {
#ifndef _WIN32 #ifndef _WIN32
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "recv() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "recv() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("recv") << boost::errinfo_api_function("recv")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
#else /* _WIN32 */ #else /* _WIN32 */
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "recv() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; << "recv() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("recv") << boost::errinfo_api_function("recv")
<< errinfo_win32_error(WSAGetLastError())); << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */ #endif /* _WIN32 */
} }
@ -380,11 +380,11 @@ bool Socket::Poll(bool read, bool write, struct timeval *timeout)
if (rc < 0) { if (rc < 0) {
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "select() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; << "select() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("select") << boost::errinfo_api_function("select")
<< errinfo_win32_error(WSAGetLastError())); << errinfo_win32_error(WSAGetLastError()));
} }
#else /* _WIN32 */ #else /* _WIN32 */
pollfd pfd; pollfd pfd;
@ -396,11 +396,11 @@ bool Socket::Poll(bool read, bool write, struct timeval *timeout)
if (rc < 0) { if (rc < 0) {
Log(LogCritical, "Socket") Log(LogCritical, "Socket")
<< "poll() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "poll() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("poll") << boost::errinfo_api_function("poll")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
#endif /* _WIN32 */ #endif /* _WIN32 */
@ -420,7 +420,7 @@ void Socket::SocketPair(SOCKET s[2])
{ {
if (dumb_socketpair(s, 0) < 0) if (dumb_socketpair(s, 0) < 0)
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("socketpair") << boost::errinfo_api_function("socketpair")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }

View File

@ -125,8 +125,8 @@ void SocketEventEngineEpoll::ThreadProc(int tid)
event.Descriptor.EventInterface->OnEvent(event.REvents); event.Descriptor.EventInterface->OnEvent(event.REvents);
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "SocketEvents") Log(LogCritical, "SocketEvents")
<< "Exception thrown in socket I/O handler:\n" << "Exception thrown in socket I/O handler:\n"
<< DiagnosticInformation(ex); << DiagnosticInformation(ex);
} catch (...) { } catch (...) {
Log(LogCritical, "SocketEvents", "Exception of unknown type thrown in socket I/O handler."); Log(LogCritical, "SocketEvents", "Exception of unknown type thrown in socket I/O handler.");
} }

View File

@ -117,8 +117,8 @@ void SocketEventEnginePoll::ThreadProc(int tid)
event.Descriptor.EventInterface->OnEvent(event.REvents); event.Descriptor.EventInterface->OnEvent(event.REvents);
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "SocketEvents") Log(LogCritical, "SocketEvents")
<< "Exception thrown in socket I/O handler:\n" << "Exception thrown in socket I/O handler:\n"
<< DiagnosticInformation(ex); << DiagnosticInformation(ex);
} catch (...) { } catch (...) {
Log(LogCritical, "SocketEvents", "Exception of unknown type thrown in socket I/O handler."); Log(LogCritical, "SocketEvents", "Exception of unknown type thrown in socket I/O handler.");
} }

View File

@ -96,7 +96,7 @@ void SocketEvents::InitializeEngine(void)
#endif /* __linux__ */ #endif /* __linux__ */
else { else {
Log(LogWarning, "SocketEvents") Log(LogWarning, "SocketEvents")
<< "Invalid event engine selected: " << eventEngine << " - Falling back to 'poll'"; << "Invalid event engine selected: " << eventEngine << " - Falling back to 'poll'";
eventEngine = "poll"; eventEngine = "poll";

View File

@ -75,8 +75,8 @@ StackTrace::StackTrace(PEXCEPTION_POINTERS exi)
m_Count = 0; m_Count = 0;
while (StackWalk64(architecture, GetCurrentProcess(), GetCurrentThread(), while (StackWalk64(architecture, GetCurrentProcess(), GetCurrentThread(),
&frame, exi->ContextRecord, nullptr, &SymFunctionTableAccess64, &frame, exi->ContextRecord, nullptr, &SymFunctionTableAccess64,
&SymGetModuleBase64, nullptr) && m_Count < sizeof(m_Frames) / sizeof(m_Frames[0])) { &SymGetModuleBase64, nullptr) && m_Count < sizeof(m_Frames) / sizeof(m_Frames[0])) {
m_Frames[m_Count] = reinterpret_cast<void *>(frame.AddrPC.Offset); m_Frames[m_Count] = reinterpret_cast<void *>(frame.AddrPC.Offset);
m_Count++; m_Count++;
} }
@ -95,7 +95,7 @@ INITIALIZE_ONCE([]() {
* *
* @param fp The stream. * @param fp The stream.
* @param ignoreFrames The number of stackframes to ignore (in addition to * @param ignoreFrames The number of stackframes to ignore (in addition to
* the one this function is executing in). * the one this function is executing in).
* @returns true if the stacktrace was printed, false otherwise. * @returns true if the stacktrace was printed, false otherwise.
*/ */
void StackTrace::Print(std::ostream& fp, int ignoreFrames) const void StackTrace::Print(std::ostream& fp, int ignoreFrames) const
@ -143,9 +143,7 @@ void StackTrace::Print(std::ostream& fp, int ignoreFrames) const
# endif /* HAVE_BACKTRACE_SYMBOLS */ # endif /* HAVE_BACKTRACE_SYMBOLS */
#else /* _WIN32 */ #else /* _WIN32 */
for (int i = ignoreFrames + 1; i < m_Count; i++) { for (int i = ignoreFrames + 1; i < m_Count; i++) {
fp << "\t(" << i - ignoreFrames - 1 << "): " fp << "\t(" << i - ignoreFrames - 1 << "): " << Utility::GetSymbolName(m_Frames[i]) << std::endl;
<< Utility::GetSymbolName(m_Frames[i])
<< std::endl;
} }
#endif /* _WIN32 */ #endif /* _WIN32 */
} }

View File

@ -59,15 +59,15 @@ void TcpSocket::Bind(const String& node, const String& service, int family)
hints.ai_flags = AI_PASSIVE; hints.ai_flags = AI_PASSIVE;
int rc = getaddrinfo(node.IsEmpty() ? nullptr : node.CStr(), int rc = getaddrinfo(node.IsEmpty() ? nullptr : node.CStr(),
service.CStr(), &hints, &result); service.CStr(), &hints, &result);
if (rc != 0) { if (rc != 0) {
Log(LogCritical, "TcpSocket") Log(LogCritical, "TcpSocket")
<< "getaddrinfo() failed with error code " << rc << ", \"" << gai_strerror(rc) << "\""; << "getaddrinfo() failed with error code " << rc << ", \"" << gai_strerror(rc) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("getaddrinfo") << boost::errinfo_api_function("getaddrinfo")
<< errinfo_getaddrinfo_error(rc)); << errinfo_getaddrinfo_error(rc));
} }
int fd = INVALID_SOCKET; int fd = INVALID_SOCKET;
@ -76,7 +76,7 @@ void TcpSocket::Bind(const String& node, const String& service, int family)
fd = socket(info->ai_family, info->ai_socktype, info->ai_protocol); fd = socket(info->ai_family, info->ai_socktype, info->ai_protocol);
if (fd == INVALID_SOCKET) { if (fd == INVALID_SOCKET) {
#ifdef _WIN32 #ifdef _WIN32
error = WSAGetLastError(); error = WSAGetLastError();
#else /* _WIN32 */ #else /* _WIN32 */
error = errno; error = errno;
@ -118,16 +118,16 @@ void TcpSocket::Bind(const String& node, const String& service, int family)
if (GetFD() == INVALID_SOCKET) { if (GetFD() == INVALID_SOCKET) {
Log(LogCritical, "TcpSocket") Log(LogCritical, "TcpSocket")
<< "Invalid socket: " << Utility::FormatErrorNumber(error); << "Invalid socket: " << Utility::FormatErrorNumber(error);
#ifndef _WIN32 #ifndef _WIN32
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function(func) << boost::errinfo_api_function(func)
<< boost::errinfo_errno(error)); << boost::errinfo_errno(error));
#else /* _WIN32 */ #else /* _WIN32 */
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function(func) << boost::errinfo_api_function(func)
<< errinfo_win32_error(error)); << errinfo_win32_error(error));
#endif /* _WIN32 */ #endif /* _WIN32 */
} }
} }
@ -154,11 +154,11 @@ void TcpSocket::Connect(const String& node, const String& service)
if (rc != 0) { if (rc != 0) {
Log(LogCritical, "TcpSocket") Log(LogCritical, "TcpSocket")
<< "getaddrinfo() failed with error code " << rc << ", \"" << gai_strerror(rc) << "\""; << "getaddrinfo() failed with error code " << rc << ", \"" << gai_strerror(rc) << "\"";
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function("getaddrinfo") << boost::errinfo_api_function("getaddrinfo")
<< errinfo_getaddrinfo_error(rc)); << errinfo_getaddrinfo_error(rc));
} }
SOCKET fd = INVALID_SOCKET; SOCKET fd = INVALID_SOCKET;
@ -185,7 +185,7 @@ void TcpSocket::Connect(const String& node, const String& service)
error = errno; error = errno;
#endif /* _WIN32 */ #endif /* _WIN32 */
Log(LogWarning, "TcpSocket") Log(LogWarning, "TcpSocket")
<< "setsockopt() unable to enable TCP keep-alives with error code " << rc; << "setsockopt() unable to enable TCP keep-alives with error code " << rc;
} }
rc = connect(fd, info->ai_addr, info->ai_addrlen); rc = connect(fd, info->ai_addr, info->ai_addrlen);
@ -212,16 +212,16 @@ void TcpSocket::Connect(const String& node, const String& service)
if (GetFD() == INVALID_SOCKET) { if (GetFD() == INVALID_SOCKET) {
Log(LogCritical, "TcpSocket") Log(LogCritical, "TcpSocket")
<< "Invalid socket: " << Utility::FormatErrorNumber(error); << "Invalid socket: " << Utility::FormatErrorNumber(error);
#ifndef _WIN32 #ifndef _WIN32
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function(func) << boost::errinfo_api_function(func)
<< boost::errinfo_errno(error)); << boost::errinfo_errno(error));
#else /* _WIN32 */ #else /* _WIN32 */
BOOST_THROW_EXCEPTION(socket_error() BOOST_THROW_EXCEPTION(socket_error()
<< boost::errinfo_api_function(func) << boost::errinfo_api_function(func)
<< errinfo_win32_error(error)); << errinfo_win32_error(error));
#endif /* _WIN32 */ #endif /* _WIN32 */
} }
} }

View File

@ -137,8 +137,8 @@ void ThreadPool::WorkerThread::ThreadProc(Queue& queue)
wi.Callback(); wi.Callback();
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "ThreadPool") Log(LogCritical, "ThreadPool")
<< "Exception thrown in event handler:\n" << "Exception thrown in event handler:\n"
<< DiagnosticInformation(ex); << DiagnosticInformation(ex);
} catch (...) { } catch (...) {
Log(LogCritical, "ThreadPool", "Exception of unknown type thrown in event handler."); Log(LogCritical, "ThreadPool", "Exception of unknown type thrown in event handler.");
} }
@ -159,10 +159,10 @@ void ThreadPool::WorkerThread::ThreadProc(Queue& queue)
(void) getrusage(RUSAGE_THREAD, &usage_end); (void) getrusage(RUSAGE_THREAD, &usage_end);
double duser = (usage_end.ru_utime.tv_sec - usage_start.ru_utime.tv_sec) + double duser = (usage_end.ru_utime.tv_sec - usage_start.ru_utime.tv_sec) +
(usage_end.ru_utime.tv_usec - usage_start.ru_utime.tv_usec) / 1000000.0; (usage_end.ru_utime.tv_usec - usage_start.ru_utime.tv_usec) / 1000000.0;
double dsys = (usage_end.ru_stime.tv_sec - usage_start.ru_stime.tv_sec) + double dsys = (usage_end.ru_stime.tv_sec - usage_start.ru_stime.tv_sec) +
(usage_end.ru_stime.tv_usec - usage_start.ru_stime.tv_usec) / 1000000.0; (usage_end.ru_stime.tv_usec - usage_start.ru_stime.tv_usec) / 1000000.0;
double dwait = (et - st) - (duser + dsys); double dwait = (et - st) - (duser + dsys);
@ -175,9 +175,9 @@ void ThreadPool::WorkerThread::ThreadProc(Queue& queue)
if (et - st > 0.5) { if (et - st > 0.5) {
Log(LogWarning, "ThreadPool") Log(LogWarning, "ThreadPool")
# ifdef RUSAGE_THREAD # ifdef RUSAGE_THREAD
<< "Event call took user:" << duser << "s, system:" << dsys << "s, wait:" << dwait << "s, minor_faults:" << dminfaults << ", major_faults:" << dmajfaults << ", voluntary_csw:" << dvctx << ", involuntary_csw:" << divctx; << "Event call took user:" << duser << "s, system:" << dsys << "s, wait:" << dwait << "s, minor_faults:" << dminfaults << ", major_faults:" << dmajfaults << ", voluntary_csw:" << dvctx << ", involuntary_csw:" << divctx;
# else # else
<< "Event call took " << (et - st) << "s"; << "Event call took " << (et - st) << "s";
# endif /* RUSAGE_THREAD */ # endif /* RUSAGE_THREAD */
} }
#endif /* I2_DEBUG */ #endif /* I2_DEBUG */
@ -292,7 +292,7 @@ void ThreadPool::ManagerThreadProc(void)
if (tthreads != 0) { if (tthreads != 0) {
Log(LogNotice, "ThreadPool") Log(LogNotice, "ThreadPool")
<< "Thread pool; current: " << alive << "; adjustment: " << tthreads; << "Thread pool; current: " << alive << "; adjustment: " << tthreads;
} }
for (int i = 0; i < -tthreads; i++) for (int i = 0; i < -tthreads; i++)
@ -318,10 +318,10 @@ void ThreadPool::ManagerThreadProc(void)
lastStats = now; lastStats = now;
Log(LogNotice, "ThreadPool") Log(LogNotice, "ThreadPool")
<< "Pool #" << m_ID << ": Pending tasks: " << total_pending << "; Average latency: " << "Pool #" << m_ID << ": Pending tasks: " << total_pending << "; Average latency: "
<< (long)(total_avg_latency * 1000 / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "ms" << (long)(total_avg_latency * 1000 / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "ms"
<< "; Threads: " << total_alive << "; Threads: " << total_alive
<< "; Pool utilization: " << (total_utilization / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "%"; << "; Pool utilization: " << (total_utilization / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "%";
} }
} }
} }

View File

@ -90,14 +90,14 @@ Timer::~Timer(void)
void Timer::Uninitialize(void) void Timer::Uninitialize(void)
{ {
{ {
boost::mutex::scoped_lock lock(l_TimerMutex); boost::mutex::scoped_lock lock(l_TimerMutex);
l_StopTimerThread = true; l_StopTimerThread = true;
l_TimerCV.notify_all(); l_TimerCV.notify_all();
} }
if (l_TimerThread.joinable()) if (l_TimerThread.joinable())
l_TimerThread.join(); l_TimerThread.join();
} }
/** /**
@ -198,7 +198,7 @@ void Timer::Reschedule(double next)
* *
* @param completed Whether the timer has just completed its callback. * @param completed Whether the timer has just completed its callback.
* @param next The time when this timer should be called again. Use -1 to let * @param next The time when this timer should be called again. Use -1 to let
* the timer figure out a suitable time based on the interval. * the timer figure out a suitable time based on the interval.
*/ */
void Timer::InternalReschedule(bool completed, double next) void Timer::InternalReschedule(bool completed, double next)
{ {
@ -257,7 +257,7 @@ void Timer::AdjustTimers(double adjustment)
for (Timer *timer : idx) { for (Timer *timer : idx) {
if (std::fabs(now - (timer->m_Next + adjustment)) < if (std::fabs(now - (timer->m_Next + adjustment)) <
std::fabs(now - timer->m_Next)) { std::fabs(now - timer->m_Next)) {
timer->m_Next += adjustment; timer->m_Next += adjustment;
timers.push_back(timer); timers.push_back(timer);
} }

View File

@ -40,8 +40,8 @@ bool I2_EXPORT TlsStream::m_SSLIndexInitialized = false;
*/ */
TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<SSL_CTX>& sslContext) TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<SSL_CTX>& sslContext)
: SocketEvents(socket, this), m_Eof(false), m_HandshakeOK(false), m_VerifyOK(true), m_ErrorCode(0), : SocketEvents(socket, this), m_Eof(false), m_HandshakeOK(false), m_VerifyOK(true), m_ErrorCode(0),
m_ErrorOccurred(false), m_Socket(socket), m_Role(role), m_SendQ(new FIFO()), m_RecvQ(new FIFO()), m_ErrorOccurred(false), m_Socket(socket), m_Role(role), m_SendQ(new FIFO()), m_RecvQ(new FIFO()),
m_CurrentAction(TlsActionNone), m_Retry(false), m_Shutdown(false) m_CurrentAction(TlsActionNone), m_Retry(false), m_Shutdown(false)
{ {
std::ostringstream msgbuf; std::ostringstream msgbuf;
char errbuf[120]; char errbuf[120];
@ -273,8 +273,8 @@ void TlsStream::HandleError(void) const
{ {
if (m_ErrorOccurred) { if (m_ErrorOccurred) {
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("TlsStream::OnEvent") << boost::errinfo_api_function("TlsStream::OnEvent")
<< errinfo_openssl_error(m_ErrorCode)); << errinfo_openssl_error(m_ErrorCode));
} }
} }

View File

@ -114,41 +114,41 @@ std::shared_ptr<SSL_CTX> MakeSSLContext(const String& pubkey, const String& priv
if (!pubkey.IsEmpty()) { if (!pubkey.IsEmpty()) {
if (!SSL_CTX_use_certificate_chain_file(sslContext.get(), pubkey.CStr())) { if (!SSL_CTX_use_certificate_chain_file(sslContext.get(), pubkey.CStr())) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error with public key file '" << pubkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error with public key file '" << pubkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SSL_CTX_use_certificate_chain_file") << boost::errinfo_api_function("SSL_CTX_use_certificate_chain_file")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(pubkey)); << boost::errinfo_file_name(pubkey));
} }
} }
if (!privkey.IsEmpty()) { if (!privkey.IsEmpty()) {
if (!SSL_CTX_use_PrivateKey_file(sslContext.get(), privkey.CStr(), SSL_FILETYPE_PEM)) { if (!SSL_CTX_use_PrivateKey_file(sslContext.get(), privkey.CStr(), SSL_FILETYPE_PEM)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error with private key file '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error with private key file '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SSL_CTX_use_PrivateKey_file") << boost::errinfo_api_function("SSL_CTX_use_PrivateKey_file")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(privkey)); << boost::errinfo_file_name(privkey));
} }
if (!SSL_CTX_check_private_key(sslContext.get())) { if (!SSL_CTX_check_private_key(sslContext.get())) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error checking private key '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error checking private key '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SSL_CTX_check_private_key") << boost::errinfo_api_function("SSL_CTX_check_private_key")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
} }
if (!cakey.IsEmpty()) { if (!cakey.IsEmpty()) {
if (!SSL_CTX_load_verify_locations(sslContext.get(), cakey.CStr(), nullptr)) { if (!SSL_CTX_load_verify_locations(sslContext.get(), cakey.CStr(), nullptr)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error loading and verifying locations in ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error loading and verifying locations in ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SSL_CTX_load_verify_locations") << boost::errinfo_api_function("SSL_CTX_load_verify_locations")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(cakey)); << boost::errinfo_file_name(cakey));
} }
STACK_OF(X509_NAME) *cert_names; STACK_OF(X509_NAME) *cert_names;
@ -156,11 +156,11 @@ std::shared_ptr<SSL_CTX> MakeSSLContext(const String& pubkey, const String& priv
cert_names = SSL_load_client_CA_file(cakey.CStr()); cert_names = SSL_load_client_CA_file(cakey.CStr());
if (!cert_names) { if (!cert_names) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error loading client ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error loading client ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SSL_load_client_CA_file") << boost::errinfo_api_function("SSL_load_client_CA_file")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(cakey)); << boost::errinfo_file_name(cakey));
} }
SSL_CTX_set_client_CA_list(sslContext.get(), cert_names); SSL_CTX_set_client_CA_list(sslContext.get(), cert_names);
@ -180,15 +180,15 @@ void SetCipherListToSSLContext(const std::shared_ptr<SSL_CTX>& context, const St
if (SSL_CTX_set_cipher_list(context.get(), cipherList.CStr()) == 0) { if (SSL_CTX_set_cipher_list(context.get(), cipherList.CStr()) == 0) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Cipher list '" << "Cipher list '"
<< cipherList << cipherList
<< "' does not specify any usable ciphers: " << "' does not specify any usable ciphers: "
<< ERR_peek_error() << ", \"" << ERR_peek_error() << ", \""
<< ERR_error_string(ERR_peek_error(), errbuf) << "\""; << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SSL_CTX_set_cipher_list") << boost::errinfo_api_function("SSL_CTX_set_cipher_list")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
} }
@ -236,19 +236,19 @@ void AddCRLToSSLContext(const std::shared_ptr<SSL_CTX>& context, const String& c
if (!lookup) { if (!lookup) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error adding X509 store lookup: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error adding X509 store lookup: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("X509_STORE_add_lookup") << boost::errinfo_api_function("X509_STORE_add_lookup")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (X509_LOOKUP_load_file(lookup, crlPath.CStr(), X509_FILETYPE_PEM) != 1) { if (X509_LOOKUP_load_file(lookup, crlPath.CStr(), X509_FILETYPE_PEM) != 1) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error loading crl file '" << crlPath << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error loading crl file '" << crlPath << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("X509_LOOKUP_load_file") << boost::errinfo_api_function("X509_LOOKUP_load_file")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(crlPath)); << boost::errinfo_file_name(crlPath));
} }
X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new(); X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
@ -266,10 +266,10 @@ static String GetX509NameCN(X509_NAME *name)
if (rc == -1) { if (rc == -1) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error with x509 NAME getting text by NID: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error with x509 NAME getting text by NID: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("X509_NAME_get_text_by_NID") << boost::errinfo_api_function("X509_NAME_get_text_by_NID")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
return buffer; return buffer;
@ -300,29 +300,29 @@ std::shared_ptr<X509> GetX509Certificate(const String& pemfile)
if (!fpcert) { if (!fpcert) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error creating new BIO: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error creating new BIO: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("BIO_new") << boost::errinfo_api_function("BIO_new")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (BIO_read_filename(fpcert, pemfile.CStr()) < 0) { if (BIO_read_filename(fpcert, pemfile.CStr()) < 0) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("BIO_read_filename") << boost::errinfo_api_function("BIO_read_filename")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(pemfile)); << boost::errinfo_file_name(pemfile));
} }
cert = PEM_read_bio_X509_AUX(fpcert, nullptr, nullptr, nullptr); cert = PEM_read_bio_X509_AUX(fpcert, nullptr, nullptr, nullptr);
if (!cert) { if (!cert) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on bio X509 AUX reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on bio X509 AUX reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("PEM_read_bio_X509_AUX") << boost::errinfo_api_function("PEM_read_bio_X509_AUX")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(pemfile)); << boost::errinfo_file_name(pemfile));
} }
BIO_free(fpcert); BIO_free(fpcert);
@ -343,10 +343,10 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile,
EC_KEY_free(eckey); EC_KEY_free(eckey);
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error while generating EC key pair: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error while generating EC key pair: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("EC_KEY_generate_key") << boost::errinfo_api_function("EC_KEY_generate_key")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
EVP_PKEY *key = EVP_PKEY_new(); EVP_PKEY *key = EVP_PKEY_new();
@ -356,14 +356,14 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile,
EC_KEY_free(eckey); EC_KEY_free(eckey);
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error while assigning EC key to EVP_PKEY structure: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error while assigning EC key to EVP_PKEY structure: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("EC_KEY_generate_key") << boost::errinfo_api_function("EC_KEY_generate_key")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
Log(LogInformation, "base") Log(LogInformation, "base")
<< "Writing private key to '" << keyfile << "'."; << "Writing private key to '" << keyfile << "'.";
BIO *bio = BIO_new_file(const_cast<char *>(keyfile.CStr()), "w"); BIO *bio = BIO_new_file(const_cast<char *>(keyfile.CStr()), "w");
@ -372,11 +372,11 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile,
EC_KEY_free(eckey); EC_KEY_free(eckey);
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error while opening private key file '" << keyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error while opening private key file '" << keyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("BIO_new_file") << boost::errinfo_api_function("BIO_new_file")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(keyfile)); << boost::errinfo_file_name(keyfile));
} }
if (!PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, 0, nullptr)) { if (!PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, 0, nullptr)) {
@ -385,11 +385,11 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile,
BIO_free(bio); BIO_free(bio);
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error while writing private key to file '" << keyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error while writing private key to file '" << keyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("PEM_write_bio_PrivateKey") << boost::errinfo_api_function("PEM_write_bio_PrivateKey")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(keyfile)); << boost::errinfo_file_name(keyfile));
} }
BIO_free(bio); BIO_free(bio);
@ -407,26 +407,26 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile,
X509_NAME_free(subject); X509_NAME_free(subject);
Log(LogInformation, "base") Log(LogInformation, "base")
<< "Writing X509 certificate to '" << certfile << "'."; << "Writing X509 certificate to '" << certfile << "'.";
bio = BIO_new_file(const_cast<char *>(certfile.CStr()), "w"); bio = BIO_new_file(const_cast<char *>(certfile.CStr()), "w");
if (!bio) { if (!bio) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error while opening certificate file '" << certfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error while opening certificate file '" << certfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("BIO_new_file") << boost::errinfo_api_function("BIO_new_file")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(certfile)); << boost::errinfo_file_name(certfile));
} }
if (!PEM_write_bio_X509(bio, cert.get())) { if (!PEM_write_bio_X509(bio, cert.get())) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error while writing certificate to file '" << certfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error while writing certificate to file '" << certfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("PEM_write_bio_X509") << boost::errinfo_api_function("PEM_write_bio_X509")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(certfile)); << boost::errinfo_file_name(certfile));
} }
BIO_free(bio); BIO_free(bio);
@ -459,26 +459,26 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile,
X509_REQ_sign(req, key, EVP_sha256()); X509_REQ_sign(req, key, EVP_sha256());
Log(LogInformation, "base") Log(LogInformation, "base")
<< "Writing certificate signing request to '" << csrfile << "'."; << "Writing certificate signing request to '" << csrfile << "'.";
bio = BIO_new_file(const_cast<char *>(csrfile.CStr()), "w"); bio = BIO_new_file(const_cast<char *>(csrfile.CStr()), "w");
if (!bio) { if (!bio) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error while opening CSR file '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error while opening CSR file '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("BIO_new_file") << boost::errinfo_api_function("BIO_new_file")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(csrfile)); << boost::errinfo_file_name(csrfile));
} }
if (!PEM_write_bio_X509_REQ(bio, req)) { if (!PEM_write_bio_X509_REQ(bio, req)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error while writing CSR to file '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error while writing CSR to file '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("PEM_write_bio_X509") << boost::errinfo_api_function("PEM_write_bio_X509")
<< errinfo_openssl_error(ERR_peek_error()) << errinfo_openssl_error(ERR_peek_error())
<< boost::errinfo_file_name(csrfile)); << boost::errinfo_file_name(csrfile));
} }
BIO_free(bio); BIO_free(bio);
@ -510,26 +510,26 @@ std::shared_ptr<X509> CreateCert(EVP_PKEY *pubkey, X509_NAME *subject, X509_NAME
if (!SHA1_Init(&context)) { if (!SHA1_Init(&context)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA1 Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA1 Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA1_Init") << boost::errinfo_api_function("SHA1_Init")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (!SHA1_Update(&context, (unsigned char*)id.CStr(), id.GetLength())) { if (!SHA1_Update(&context, (unsigned char*)id.CStr(), id.GetLength())) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA1 Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA1 Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA1_Update") << boost::errinfo_api_function("SHA1_Update")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (!SHA1_Final(digest, &context)) { if (!SHA1_Final(digest, &context)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA1 Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA1 Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA1_Final") << boost::errinfo_api_function("SHA1_Final")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
BIGNUM *bn = BN_new(); BIGNUM *bn = BN_new();
@ -588,7 +588,7 @@ std::shared_ptr<X509> CreateCertIcingaCA(EVP_PKEY *pubkey, X509_NAME *subject)
if (!cakeybio) { if (!cakeybio) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Could not open CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Could not open CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
return std::shared_ptr<X509>(); return std::shared_ptr<X509>();
} }
@ -596,7 +596,7 @@ std::shared_ptr<X509> CreateCertIcingaCA(EVP_PKEY *pubkey, X509_NAME *subject)
if (!privkey) { if (!privkey) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Could not read private key from CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Could not read private key from CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
return std::shared_ptr<X509>(); return std::shared_ptr<X509>();
} }
@ -649,7 +649,7 @@ String PBKDF2_SHA1(const String& password, const String& salt, int iterations)
{ {
unsigned char digest[SHA_DIGEST_LENGTH]; unsigned char digest[SHA_DIGEST_LENGTH];
PKCS5_PBKDF2_HMAC_SHA1(password.CStr(), password.GetLength(), reinterpret_cast<const unsigned char *>(salt.CStr()), salt.GetLength(), PKCS5_PBKDF2_HMAC_SHA1(password.CStr(), password.GetLength(), reinterpret_cast<const unsigned char *>(salt.CStr()), salt.GetLength(),
iterations, sizeof(digest), digest); iterations, sizeof(digest), digest);
char output[SHA_DIGEST_LENGTH*2+1]; char output[SHA_DIGEST_LENGTH*2+1];
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) for (int i = 0; i < SHA_DIGEST_LENGTH; i++)
@ -666,26 +666,26 @@ String SHA1(const String& s, bool binary)
if (!SHA1_Init(&context)) { if (!SHA1_Init(&context)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA1_Init") << boost::errinfo_api_function("SHA1_Init")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (!SHA1_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) { if (!SHA1_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA1_Update") << boost::errinfo_api_function("SHA1_Update")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (!SHA1_Final(digest, &context)) { if (!SHA1_Final(digest, &context)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA1_Final") << boost::errinfo_api_function("SHA1_Final")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (binary) if (binary)
@ -706,26 +706,26 @@ String SHA256(const String& s)
if (!SHA256_Init(&context)) { if (!SHA256_Init(&context)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA256 Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA256 Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA256_Init") << boost::errinfo_api_function("SHA256_Init")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (!SHA256_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) { if (!SHA256_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA256 Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA256 Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA256_Update") << boost::errinfo_api_function("SHA256_Update")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
if (!SHA256_Final(digest, &context)) { if (!SHA256_Final(digest, &context)) {
Log(LogCritical, "SSL") Log(LogCritical, "SSL")
<< "Error on SHA256 Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; << "Error on SHA256 Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error() BOOST_THROW_EXCEPTION(openssl_error()
<< boost::errinfo_api_function("SHA256_Final") << boost::errinfo_api_function("SHA256_Final")
<< errinfo_openssl_error(ERR_peek_error())); << errinfo_openssl_error(ERR_peek_error()));
} }
char output[SHA256_DIGEST_LENGTH*2+1]; char output[SHA256_DIGEST_LENGTH*2+1];

View File

@ -82,7 +82,7 @@ String Type::GetPluralName(void) const
String name = GetName(); String name = GetName();
if (name.GetLength() >= 2 && name[name.GetLength() - 1] == 'y' && if (name.GetLength() >= 2 && name[name.GetLength() - 1] == 'y' &&
name.SubStr(name.GetLength() - 2, 1).FindFirstOf("aeiou") == String::NPos) name.SubStr(name.GetLength() - 2, 1).FindFirstOf("aeiou") == String::NPos)
return name.SubStr(0, name.GetLength() - 1) + "ies"; return name.SubStr(0, name.GetLength() - 1) + "ies";
else else
return name + "s"; return name + "s";

View File

@ -26,7 +26,7 @@
using namespace icinga; using namespace icinga;
static void InvokeAttributeHandlerHelper(const Function::Ptr& callback, static void InvokeAttributeHandlerHelper(const Function::Ptr& callback,
const Object::Ptr& object, const Value& cookie) const Object::Ptr& object, const Value& cookie)
{ {
callback->Invoke({ object }); callback->Invoke({ object });
} }

View File

@ -50,7 +50,8 @@ typedef int SOCKET;
#ifndef SUN_LEN #ifndef SUN_LEN
/* TODO: Ideally this should take into the account how /* TODO: Ideally this should take into the account how
long the socket path really is. */ * long the socket path really is.
*/
# define SUN_LEN(sun) (sizeof(sockaddr_un)) # define SUN_LEN(sun) (sizeof(sockaddr_un))
#endif /* SUN_LEN */ #endif /* SUN_LEN */

View File

@ -29,8 +29,8 @@ UnixSocket::UnixSocket(void)
if (fd < 0) { if (fd < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("socket") << boost::errinfo_api_function("socket")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
SetFD(fd); SetFD(fd);
@ -48,8 +48,8 @@ void UnixSocket::Bind(const String& path)
if (bind(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0) { if (bind(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("bind") << boost::errinfo_api_function("bind")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
} }
@ -63,8 +63,8 @@ void UnixSocket::Connect(const String& path)
if (connect(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0 && errno != EINPROGRESS) { if (connect(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0 && errno != EINPROGRESS) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("connect") << boost::errinfo_api_function("connect")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
} }
#endif /* _WIN32 */ #endif /* _WIN32 */

View File

@ -290,8 +290,8 @@ String Utility::DirName(const String& path)
free(dir); free(dir);
BOOST_THROW_EXCEPTION(win32_error() BOOST_THROW_EXCEPTION(win32_error()
<< boost::errinfo_api_function("PathRemoveFileSpec") << boost::errinfo_api_function("PathRemoveFileSpec")
<< errinfo_win32_error(GetLastError())); << errinfo_win32_error(GetLastError()));
} }
result = dir; result = dir;
@ -558,9 +558,9 @@ bool Utility::Glob(const String& pathSpec, const std::function<void (const Strin
return false; return false;
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("glob") << boost::errinfo_api_function("glob")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(pathSpec)); << boost::errinfo_file_name(pathSpec));
} }
if (gr.gl_pathc == 0) { if (gr.gl_pathc == 0) {
@ -630,9 +630,9 @@ bool Utility::GlobRecursive(const String& path, const String& pattern, const std
return false; return false;
BOOST_THROW_EXCEPTION(win32_error() BOOST_THROW_EXCEPTION(win32_error()
<< boost::errinfo_api_function("FindFirstFile") << boost::errinfo_api_function("FindFirstFile")
<< errinfo_win32_error(errorCode) << errinfo_win32_error(errorCode)
<< boost::errinfo_file_name(pathSpec)); << boost::errinfo_file_name(pathSpec));
} }
do { do {
@ -656,8 +656,8 @@ bool Utility::GlobRecursive(const String& path, const String& pattern, const std
if (!FindClose(handle)) { if (!FindClose(handle)) {
BOOST_THROW_EXCEPTION(win32_error() BOOST_THROW_EXCEPTION(win32_error()
<< boost::errinfo_api_function("FindClose") << boost::errinfo_api_function("FindClose")
<< errinfo_win32_error(GetLastError())); << errinfo_win32_error(GetLastError()));
} }
#else /* _WIN32 */ #else /* _WIN32 */
DIR *dirp; DIR *dirp;
@ -666,9 +666,9 @@ bool Utility::GlobRecursive(const String& path, const String& pattern, const std
if (!dirp) if (!dirp)
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("opendir") << boost::errinfo_api_function("opendir")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
while (dirp) { while (dirp) {
dirent *pent; dirent *pent;
@ -679,9 +679,9 @@ bool Utility::GlobRecursive(const String& path, const String& pattern, const std
closedir(dirp); closedir(dirp);
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("readdir") << boost::errinfo_api_function("readdir")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
} }
if (!pent) if (!pent)
@ -743,9 +743,9 @@ void Utility::MkDir(const String& path, int mode)
#endif /* _WIN32 */ #endif /* _WIN32 */
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("mkdir") << boost::errinfo_api_function("mkdir")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
} }
} }
@ -773,15 +773,16 @@ void Utility::RemoveDirRecursive(const String& path)
Utility::GlobRecursive(path, "*", std::bind(&Utility::CollectPaths, _1, std::ref(paths)), GlobFile | GlobDirectory); Utility::GlobRecursive(path, "*", std::bind(&Utility::CollectPaths, _1, std::ref(paths)), GlobFile | GlobDirectory);
/* This relies on the fact that GlobRecursive lists the parent directory /* This relies on the fact that GlobRecursive lists the parent directory
first before recursing into subdirectories. */ * first before recursing into subdirectories.
*/
std::reverse(paths.begin(), paths.end()); std::reverse(paths.begin(), paths.end());
for (const String& path : paths) { for (const String& path : paths) {
if (remove(path.CStr()) < 0) if (remove(path.CStr()) < 0)
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("remove") << boost::errinfo_api_function("remove")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
} }
#ifndef _WIN32 #ifndef _WIN32
@ -790,9 +791,9 @@ void Utility::RemoveDirRecursive(const String& path)
if (_rmdir(path.CStr()) < 0) if (_rmdir(path.CStr()) < 0)
#endif /* _WIN32 */ #endif /* _WIN32 */
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rmdir") << boost::errinfo_api_function("rmdir")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
} }
void Utility::CollectPaths(const String& path, std::vector<String>& paths) void Utility::CollectPaths(const String& path, std::vector<String>& paths)
@ -824,11 +825,11 @@ bool Utility::SetFileOwnership(const String& file, const String& user, const Str
if (!pw) { if (!pw) {
if (errno == 0) { if (errno == 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Invalid user specified: " << user; << "Invalid user specified: " << user;
return false; return false;
} else { } else {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return false; return false;
} }
} }
@ -839,18 +840,18 @@ bool Utility::SetFileOwnership(const String& file, const String& user, const Str
if (!gr) { if (!gr) {
if (errno == 0) { if (errno == 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Invalid group specified: " << group; << "Invalid group specified: " << group;
return false; return false;
} else { } else {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return false; return false;
} }
} }
if (chown(file.CStr(), pw->pw_uid, gr->gr_gid) < 0) { if (chown(file.CStr(), pw->pw_uid, gr->gr_gid) < 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "chown() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "chown() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return false; return false;
} }
#endif /* _WIN32 */ #endif /* _WIN32 */
@ -865,8 +866,8 @@ void Utility::SetNonBlocking(int fd, bool nb)
if (flags < 0) { if (flags < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("fcntl") << boost::errinfo_api_function("fcntl")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
if (nb) if (nb)
@ -876,8 +877,8 @@ void Utility::SetNonBlocking(int fd, bool nb)
if (fcntl(fd, F_SETFL, flags) < 0) { if (fcntl(fd, F_SETFL, flags) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("fcntl") << boost::errinfo_api_function("fcntl")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
} }
@ -887,8 +888,8 @@ void Utility::SetCloExec(int fd, bool cloexec)
if (flags < 0) { if (flags < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("fcntl") << boost::errinfo_api_function("fcntl")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
if (cloexec) if (cloexec)
@ -898,8 +899,8 @@ void Utility::SetCloExec(int fd, bool cloexec)
if (fcntl(fd, F_SETFD, flags) < 0) { if (fcntl(fd, F_SETFD, flags) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("fcntl") << boost::errinfo_api_function("fcntl")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
} }
#endif /* _WIN32 */ #endif /* _WIN32 */
@ -1019,16 +1020,16 @@ String Utility::FormatDateTime(const char *format, double ts)
if (!temp) { if (!temp) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("localtime") << boost::errinfo_api_function("localtime")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
tmthen = *temp; tmthen = *temp;
#else /* _MSC_VER */ #else /* _MSC_VER */
if (!localtime_r(&tempts, &tmthen)) { if (!localtime_r(&tempts, &tmthen)) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("localtime_r") << boost::errinfo_api_function("localtime_r")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
#endif /* _MSC_VER */ #endif /* _MSC_VER */
@ -1090,10 +1091,10 @@ String Utility::EscapeShellCmd(const String& s)
#endif /* _WIN32 */ #endif /* _WIN32 */
if (ch == '#' || ch == '&' || ch == ';' || ch == '`' || ch == '|' || if (ch == '#' || ch == '&' || ch == ';' || ch == '`' || ch == '|' ||
ch == '*' || ch == '?' || ch == '~' || ch == '<' || ch == '>' || ch == '*' || ch == '?' || ch == '~' || ch == '<' || ch == '>' ||
ch == '^' || ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '^' || ch == '(' || ch == ')' || ch == '[' || ch == ']' ||
ch == '{' || ch == '}' || ch == '$' || ch == '\\' || ch == '\x0A' || ch == '{' || ch == '}' || ch == '$' || ch == '\\' || ch == '\x0A' ||
ch == '\xFF') ch == '\xFF')
escape = true; escape = true;
if (escape) if (escape)
@ -1333,8 +1334,8 @@ tm Utility::LocalTime(time_t ts)
if (!result) { if (!result) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("localtime") << boost::errinfo_api_function("localtime")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
return *result; return *result;
@ -1343,8 +1344,8 @@ tm Utility::LocalTime(time_t ts)
if (!localtime_r(&ts, &result)) { if (!localtime_r(&ts, &result)) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("localtime_r") << boost::errinfo_api_function("localtime_r")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
return result; return result;
@ -1392,9 +1393,9 @@ void Utility::SaveJsonFile(const String& path, int mode, const Value& value)
if (rename(tempFilename.CStr(), path.CStr()) < 0) { if (rename(tempFilename.CStr(), path.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempFilename)); << boost::errinfo_file_name(tempFilename));
} }
} }
@ -1735,7 +1736,7 @@ String Utility::ValidateUTF8(const String& input)
} }
if ((input[i] & 0xE0) == 0xC0 && length > i + 1 && if ((input[i] & 0xE0) == 0xC0 && length > i + 1 &&
(input[i + 1] & 0xC0) == 0x80) { (input[i + 1] & 0xC0) == 0x80) {
output += input[i]; output += input[i];
output += input[i + 1]; output += input[i + 1];
i++; i++;
@ -1743,7 +1744,7 @@ String Utility::ValidateUTF8(const String& input)
} }
if ((input[i] & 0xF0) == 0xE0 && length > i + 2 && if ((input[i] & 0xF0) == 0xE0 && length > i + 2 &&
(input[i + 1] & 0xC0) == 0x80 && (input[i + 2] & 0xC0) == 0x80) { (input[i + 1] & 0xC0) == 0x80 && (input[i + 2] & 0xC0) == 0x80) {
output += input[i]; output += input[i];
output += input[i + 1]; output += input[i + 1];
output += input[i + 2]; output += input[i + 2];
@ -1773,9 +1774,9 @@ String Utility::CreateTempFile(const String& path, int mode, std::fstream& fp)
if (fd < 0) { if (fd < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("mkstemp") << boost::errinfo_api_function("mkstemp")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
} }
try { try {
@ -1791,9 +1792,9 @@ String Utility::CreateTempFile(const String& path, int mode, std::fstream& fp)
if (chmod(resultPath.CStr(), mode) < 0) { if (chmod(resultPath.CStr(), mode) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("chmod") << boost::errinfo_api_function("chmod")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(resultPath)); << boost::errinfo_file_name(resultPath));
} }
return resultPath; return resultPath;
@ -1801,12 +1802,13 @@ String Utility::CreateTempFile(const String& path, int mode, std::fstream& fp)
#ifdef _WIN32 #ifdef _WIN32
/* mkstemp extracted from libc/sysdeps/posix/tempname.c. Copyright /* mkstemp extracted from libc/sysdeps/posix/tempname.c. Copyright
(C) 1991-1999, 2000, 2001, 2006 Free Software Foundation, Inc. * (C) 1991-1999, 2000, 2001, 2006 Free Software Foundation, Inc.
*
The GNU C Library is free software; you can redistribute it and/or * The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. */ * version 2.1 of the License, or (at your option) any later version.
*/
#define _O_EXCL 0x0400 #define _O_EXCL 0x0400
#define _O_CREAT 0x0100 #define _O_CREAT 0x0100
@ -1818,9 +1820,10 @@ String Utility::CreateTempFile(const String& path, int mode, std::fstream& fp)
static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/* Generate a temporary file name based on TMPL. TMPL must match the /* Generate a temporary file name based on TMPL. TMPL must match the
rules for mk[s]temp (i.e. end in "XXXXXX"). The name constructed * rules for mk[s]temp (i.e. end in "XXXXXX"). The name constructed
does not exist at the time of the call to mkstemp. TMPL is * does not exist at the time of the call to mkstemp. TMPL is
overwritten with the result. */ * overwritten with the result.
*/
int Utility::MksTemp(char *tmpl) int Utility::MksTemp(char *tmpl)
{ {
int len; int len;
@ -1832,15 +1835,17 @@ int Utility::MksTemp(char *tmpl)
int save_errno = errno; int save_errno = errno;
/* A lower bound on the number of temporary files to attempt to /* A lower bound on the number of temporary files to attempt to
generate. The maximum total number of temporary file names that * generate. The maximum total number of temporary file names that
can exist for a given template is 62**6. It should never be * can exist for a given template is 62**6. It should never be
necessary to try all these combinations. Instead if a reasonable * necessary to try all these combinations. Instead if a reasonable
number of names is tried (we define reasonable as 62**3) fail to * number of names is tried (we define reasonable as 62**3) fail to
give the system administrator the chance to remove the problems. */ * give the system administrator the chance to remove the problems.
*/
#define ATTEMPTS_MIN (62 * 62 * 62) #define ATTEMPTS_MIN (62 * 62 * 62)
/* The number of times to attempt to generate a temporary file. To /* The number of times to attempt to generate a temporary file
conform to POSIX, this must be no smaller than TMP_MAX. */ * To conform to POSIX, this must be no smaller than TMP_MAX.
*/
#if ATTEMPTS_MIN < TMP_MAX #if ATTEMPTS_MIN < TMP_MAX
unsigned int attempts = TMP_MAX; unsigned int attempts = TMP_MAX;
#else #else
@ -1865,8 +1870,8 @@ int Utility::MksTemp(char *tmpl)
GetSystemTime(&stNow); GetSystemTime(&stNow);
stNow.wMilliseconds = 500; stNow.wMilliseconds = 500;
if (!SystemTimeToFileTime(&stNow, &ftNow)) { if (!SystemTimeToFileTime(&stNow, &ftNow)) {
errno = -1; errno = -1;
return -1; return -1;
} }
random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32) | (unsigned long long)ftNow.dwLowDateTime); random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32) | (unsigned long long)ftNow.dwLowDateTime);

View File

@ -32,7 +32,7 @@ boost::thread_specific_ptr<WorkQueue *> l_ThreadWorkQueue;
WorkQueue::WorkQueue(size_t maxItems, int threadCount) WorkQueue::WorkQueue(size_t maxItems, int threadCount)
: m_ID(m_NextID++), m_ThreadCount(threadCount), m_Spawned(false), m_MaxItems(maxItems), m_Stopped(false), : m_ID(m_NextID++), m_ThreadCount(threadCount), m_Spawned(false), m_MaxItems(maxItems), m_Stopped(false),
m_Processing(0), m_NextTaskID(0), m_TaskStats(15 * 60), m_PendingTasks(0), m_PendingTasksTimestamp(0) m_Processing(0), m_NextTaskID(0), m_TaskStats(15 * 60), m_PendingTasks(0), m_PendingTasksTimestamp(0)
{ {
/* Initialize logger. */ /* Initialize logger. */
m_StatusTimerTimeout = Utility::GetTime(); m_StatusTimerTimeout = Utility::GetTime();
@ -67,7 +67,7 @@ String WorkQueue::GetName(void) const
* immediately if it's being enqueued from within the WorkQueue thread. * immediately if it's being enqueued from within the WorkQueue thread.
*/ */
void WorkQueue::Enqueue(std::function<void (void)>&& function, WorkQueuePriority priority, void WorkQueue::Enqueue(std::function<void (void)>&& function, WorkQueuePriority priority,
bool allowInterleaved) bool allowInterleaved)
{ {
bool wq_thread = IsWorkerThread(); bool wq_thread = IsWorkerThread();
@ -81,7 +81,7 @@ void WorkQueue::Enqueue(std::function<void (void)>&& function, WorkQueuePriority
if (!m_Spawned) { if (!m_Spawned) {
Log(LogNotice, "WorkQueue") Log(LogNotice, "WorkQueue")
<< "Spawning WorkQueue threads for '" << m_Name << "'"; << "Spawning WorkQueue threads for '" << m_Name << "'";
for (int i = 0; i < m_ThreadCount; i++) { for (int i = 0; i < m_ThreadCount; i++) {
m_Threads.create_thread(std::bind(&WorkQueue::WorkerThreadProc, this)); m_Threads.create_thread(std::bind(&WorkQueue::WorkerThreadProc, this));
@ -122,7 +122,7 @@ void WorkQueue::Join(bool stop)
m_Spawned = false; m_Spawned = false;
Log(LogNotice, "WorkQueue") Log(LogNotice, "WorkQueue")
<< "Stopped WorkQueue threads for '" << m_Name << "'"; << "Stopped WorkQueue threads for '" << m_Name << "'";
} }
} }
@ -155,7 +155,7 @@ void WorkQueue::SetExceptionCallback(const ExceptionCallback& callback)
bool WorkQueue::HasExceptions(void) const bool WorkQueue::HasExceptions(void) const
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
return !m_Exceptions.empty(); return !m_Exceptions.empty();
} }
@ -166,7 +166,7 @@ bool WorkQueue::HasExceptions(void) const
std::vector<boost::exception_ptr> WorkQueue::GetExceptions(void) const std::vector<boost::exception_ptr> WorkQueue::GetExceptions(void) const
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
return m_Exceptions; return m_Exceptions;
} }
@ -176,11 +176,11 @@ void WorkQueue::ReportExceptions(const String& facility) const
for (const auto& eptr : exceptions) { for (const auto& eptr : exceptions) {
Log(LogCritical, facility) Log(LogCritical, facility)
<< DiagnosticInformation(eptr); << DiagnosticInformation(eptr);
} }
Log(LogCritical, facility) Log(LogCritical, facility)
<< exceptions.size() << " error" << (exceptions.size() != 1 ? "s" : ""); << exceptions.size() << " error" << (exceptions.size() != 1 ? "s" : "");
} }
size_t WorkQueue::GetLength(void) const size_t WorkQueue::GetLength(void) const
@ -218,11 +218,11 @@ void WorkQueue::StatusTimerHandler(void)
/* Log if there are pending items, or 5 minute timeout is reached. */ /* Log if there are pending items, or 5 minute timeout is reached. */
if (pending > 0 || m_StatusTimerTimeout < now) { if (pending > 0 || m_StatusTimerTimeout < now) {
Log(LogInformation, "WorkQueue") Log(LogInformation, "WorkQueue")
<< "#" << m_ID << " (" << m_Name << ") " << "#" << m_ID << " (" << m_Name << ") "
<< "items: " << pending << ", " << "items: " << pending << ", "
<< "rate: " << std::setw(2) << GetTaskCount(60) / 60.0 << "/s " << "rate: " << std::setw(2) << GetTaskCount(60) / 60.0 << "/s "
<< "(" << GetTaskCount(60) << "/min " << GetTaskCount(60 * 5) << "/5min " << GetTaskCount(60 * 15) << "/15min);" << "(" << GetTaskCount(60) << "/min " << GetTaskCount(60 * 5) << "/5min " << GetTaskCount(60 * 15) << "/15min);"
<< timeInfo; << timeInfo;
} }
/* Reschedule next log entry in 5 minutes. */ /* Reschedule next log entry in 5 minutes. */
@ -272,8 +272,7 @@ void WorkQueue::WorkerThreadProc(void)
m_ExceptionCallback(boost::current_exception()); m_ExceptionCallback(boost::current_exception());
} }
/* clear the task so whatever other resources it holds are released /* clear the task so whatever other resources it holds are released _before_ we re-acquire the mutex */
_before_ we re-acquire the mutex */
task = Task(); task = Task();
IncreaseTaskCount(); IncreaseTaskCount();

View File

@ -44,11 +44,11 @@ enum WorkQueuePriority
struct Task struct Task
{ {
Task(void) Task(void)
: Priority(PriorityNormal), ID(-1) : Priority(PriorityNormal), ID(-1)
{ } { }
Task(std::function<void (void)>&& function, WorkQueuePriority priority, int id) Task(std::function<void (void)>&& function, WorkQueuePriority priority, int id)
: Function(std::move(function)), Priority(priority), ID(id) : Function(std::move(function)), Priority(priority), ID(id)
{ } { }
std::function<void (void)> Function; std::function<void (void)> Function;
@ -88,7 +88,7 @@ public:
String GetName(void) const; String GetName(void) const;
void Enqueue(std::function<void (void)>&& function, WorkQueuePriority priority = PriorityNormal, void Enqueue(std::function<void (void)>&& function, WorkQueuePriority priority = PriorityNormal,
bool allowInterleaved = false); bool allowInterleaved = false);
void Join(bool stop = false); void Join(bool stop = false);
bool IsWorkerThread(void) const; bool IsWorkerThread(void) const;

View File

@ -60,7 +60,7 @@ void CheckerComponent::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr
} }
CheckerComponent::CheckerComponent(void) CheckerComponent::CheckerComponent(void)
: m_Stopped(false) : m_Stopped(false)
{ } { }
void CheckerComponent::OnConfigLoaded(void) void CheckerComponent::OnConfigLoaded(void)
@ -76,7 +76,7 @@ void CheckerComponent::Start(bool runtimeCreated)
ObjectImpl<CheckerComponent>::Start(runtimeCreated); ObjectImpl<CheckerComponent>::Start(runtimeCreated);
Log(LogInformation, "CheckerComponent") Log(LogInformation, "CheckerComponent")
<< "'" << GetName() << "' started."; << "'" << GetName() << "' started.";
m_Thread = std::thread(std::bind(&CheckerComponent::CheckThreadProc, this)); m_Thread = std::thread(std::bind(&CheckerComponent::CheckThreadProc, this));
@ -90,7 +90,7 @@ void CheckerComponent::Start(bool runtimeCreated)
void CheckerComponent::Stop(bool runtimeRemoved) void CheckerComponent::Stop(bool runtimeRemoved)
{ {
Log(LogInformation, "CheckerComponent") Log(LogInformation, "CheckerComponent")
<< "'" << GetName() << "' stopped."; << "'" << GetName() << "' stopped.";
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
@ -145,7 +145,7 @@ void CheckerComponent::CheckThreadProc(void)
if (!forced) { if (!forced) {
if (!checkable->IsReachable(DependencyCheckExecution)) { if (!checkable->IsReachable(DependencyCheckExecution)) {
Log(LogNotice, "CheckerComponent") Log(LogNotice, "CheckerComponent")
<< "Skipping check for object '" << checkable->GetName() << "': Dependency failed."; << "Skipping check for object '" << checkable->GetName() << "': Dependency failed.";
check = false; check = false;
} }
@ -155,12 +155,12 @@ void CheckerComponent::CheckThreadProc(void)
if (host && !service && (!checkable->GetEnableActiveChecks() || !IcingaApplication::GetInstance()->GetEnableHostChecks())) { if (host && !service && (!checkable->GetEnableActiveChecks() || !IcingaApplication::GetInstance()->GetEnableHostChecks())) {
Log(LogNotice, "CheckerComponent") Log(LogNotice, "CheckerComponent")
<< "Skipping check for host '" << host->GetName() << "': active host checks are disabled"; << "Skipping check for host '" << host->GetName() << "': active host checks are disabled";
check = false; check = false;
} }
if (host && service && (!checkable->GetEnableActiveChecks() || !IcingaApplication::GetInstance()->GetEnableServiceChecks())) { if (host && service && (!checkable->GetEnableActiveChecks() || !IcingaApplication::GetInstance()->GetEnableServiceChecks())) {
Log(LogNotice, "CheckerComponent") Log(LogNotice, "CheckerComponent")
<< "Skipping check for service '" << service->GetName() << "': active service checks are disabled"; << "Skipping check for service '" << service->GetName() << "': active service checks are disabled";
check = false; check = false;
} }
@ -168,8 +168,8 @@ void CheckerComponent::CheckThreadProc(void)
if (tp && !tp->IsInside(Utility::GetTime())) { if (tp && !tp->IsInside(Utility::GetTime())) {
Log(LogNotice, "CheckerComponent") Log(LogNotice, "CheckerComponent")
<< "Skipping check for object '" << checkable->GetName() << "Skipping check for object '" << checkable->GetName()
<< "': not in check period '" << tp->GetName() << "'"; << "': not in check period '" << tp->GetName() << "'";
check = false; check = false;
} }
} }
@ -196,7 +196,7 @@ void CheckerComponent::CheckThreadProc(void)
} }
Log(LogDebug, "CheckerComponent") Log(LogDebug, "CheckerComponent")
<< "Executing check for '" << checkable->GetName() << "'"; << "Executing check for '" << checkable->GetName() << "'";
Checkable::IncreasePendingChecks(); Checkable::IncreasePendingChecks();
@ -249,7 +249,7 @@ void CheckerComponent::ExecuteCheckHelper(const Checkable::Ptr& checkable)
} }
Log(LogDebug, "CheckerComponent") Log(LogDebug, "CheckerComponent")
<< "Check finished for object '" << checkable->GetName() << "'"; << "Check finished for object '" << checkable->GetName() << "'";
} }
void CheckerComponent::ResultTimerHandler(void) void CheckerComponent::ResultTimerHandler(void)
@ -260,7 +260,7 @@ void CheckerComponent::ResultTimerHandler(void)
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
msgbuf << "Pending checkables: " << m_PendingCheckables.size() << "; Idle checkables: " << m_IdleCheckables.size() << "; Checks/s: " msgbuf << "Pending checkables: " << m_PendingCheckables.size() << "; Idle checkables: " << m_IdleCheckables.size() << "; Checks/s: "
<< (CIB::GetActiveHostChecksStatistics(60) + CIB::GetActiveServiceChecksStatistics(60)) / 60.0; << (CIB::GetActiveHostChecksStatistics(60) + CIB::GetActiveServiceChecksStatistics(60)) / 60.0;
} }
Log(LogNotice, "CheckerComponent", msgbuf.str()); Log(LogNotice, "CheckerComponent", msgbuf.str());

View File

@ -40,7 +40,7 @@ using namespace icinga;
String ApiSetupUtility::GetConfdPath(void) String ApiSetupUtility::GetConfdPath(void)
{ {
return Application::GetSysconfDir() + "/icinga2/conf.d"; return Application::GetSysconfDir() + "/icinga2/conf.d";
} }
bool ApiSetupUtility::SetupMaster(const String& cn, bool prompt_restart) bool ApiSetupUtility::SetupMaster(const String& cn, bool prompt_restart)
@ -80,7 +80,7 @@ bool ApiSetupUtility::SetupMasterCertificates(const String& cn)
if (!Utility::SetFileOwnership(pki_path, user, group)) { if (!Utility::SetFileOwnership(pki_path, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << pki_path << "'."; << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << pki_path << "'.";
} }
String key = pki_path + "/" + cn + ".key"; String key = pki_path + "/" + cn + ".key";
@ -88,12 +88,12 @@ bool ApiSetupUtility::SetupMasterCertificates(const String& cn)
if (Utility::PathExists(key)) { if (Utility::PathExists(key)) {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Private key file '" << key << "' already exists, not generating new certificate."; << "Private key file '" << key << "' already exists, not generating new certificate.";
return true; return true;
} }
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Generating new CSR in '" << csr << "'."; << "Generating new CSR in '" << csr << "'.";
if (Utility::PathExists(key)) if (Utility::PathExists(key))
NodeUtility::CreateBackupFile(key, true); NodeUtility::CreateBackupFile(key, true);
@ -109,7 +109,7 @@ bool ApiSetupUtility::SetupMasterCertificates(const String& cn)
String cert = pki_path + "/" + cn + ".crt"; String cert = pki_path + "/" + cn + ".crt";
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Signing CSR with CA and writing certificate to '" << cert << "'."; << "Signing CSR with CA and writing certificate to '" << cert << "'.";
if (Utility::PathExists(cert)) if (Utility::PathExists(cert))
NodeUtility::CreateBackupFile(cert); NodeUtility::CreateBackupFile(cert);
@ -126,7 +126,7 @@ bool ApiSetupUtility::SetupMasterCertificates(const String& cn)
String target_ca = pki_path + "/ca.crt"; String target_ca = pki_path + "/ca.crt";
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Copying CA certificate to '" << target_ca << "'."; << "Copying CA certificate to '" << target_ca << "'.";
if (Utility::PathExists(target_ca)) if (Utility::PathExists(target_ca))
NodeUtility::CreateBackupFile(target_ca); NodeUtility::CreateBackupFile(target_ca);
@ -138,7 +138,7 @@ bool ApiSetupUtility::SetupMasterCertificates(const String& cn)
for (const String& file : { ca_path, ca, ca_key, target_ca, key, csr, cert }) { for (const String& file : { ca_path, ca, ca_key, target_ca, key, csr, cert }) {
if (!Utility::SetFileOwnership(file, user, group)) { if (!Utility::SetFileOwnership(file, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << file << "'."; << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << file << "'.";
} }
} }
@ -153,12 +153,12 @@ bool ApiSetupUtility::SetupMasterApiUser(void)
if (Utility::PathExists(apiUsersPath)) { if (Utility::PathExists(apiUsersPath)) {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "API user config file '" << apiUsersPath << "' already exists, not creating config file."; << "API user config file '" << apiUsersPath << "' already exists, not creating config file.";
return true; return true;
} }
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Adding new ApiUser '" << api_username << "' in '" << apiUsersPath << "'."; << "Adding new ApiUser '" << api_username << "' in '" << apiUsersPath << "'.";
NodeUtility::CreateBackupFile(apiUsersPath); NodeUtility::CreateBackupFile(apiUsersPath);
@ -166,14 +166,14 @@ bool ApiSetupUtility::SetupMasterApiUser(void)
String tempFilename = Utility::CreateTempFile(apiUsersPath + ".XXXXXX", 0644, fp); String tempFilename = Utility::CreateTempFile(apiUsersPath + ".XXXXXX", 0644, fp);
fp << "/**\n" fp << "/**\n"
<< " * The APIUser objects are used for authentication against the API.\n" << " * The APIUser objects are used for authentication against the API.\n"
<< " */\n" << " */\n"
<< "object ApiUser \"" << api_username << "\" {\n" << "object ApiUser \"" << api_username << "\" {\n"
<< " password = \"" << api_password << "\"\n" << " password = \"" << api_password << "\"\n"
<< " // client_cn = \"\"\n" << " // client_cn = \"\"\n"
<< "\n" << "\n"
<< " permissions = [ \"*\" ]\n" << " permissions = [ \"*\" ]\n"
<< "}\n"; << "}\n";
fp.close(); fp.close();
@ -183,9 +183,9 @@ bool ApiSetupUtility::SetupMasterApiUser(void)
if (rename(tempFilename.CStr(), apiUsersPath.CStr()) < 0) { if (rename(tempFilename.CStr(), apiUsersPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempFilename)); << boost::errinfo_file_name(tempFilename));
} }
return true; return true;

View File

@ -42,7 +42,7 @@ String CAListCommand::GetShortDescription(void) const
} }
void CAListCommand::InitParameters(boost::program_options::options_description& visibleDesc, void CAListCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("json", "encode output as JSON") ("json", "encode output as JSON")
@ -70,14 +70,14 @@ int CAListCommand::Run(const boost::program_options::variables_map& vm, const st
Dictionary::Ptr request = kv.second; Dictionary::Ptr request = kv.second;
std::cout << kv.first std::cout << kv.first
<< " | " << " | "
/* << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S", request->Get("timestamp")) */ /* << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S", request->Get("timestamp")) */
<< request->Get("timestamp") << request->Get("timestamp")
<< " | " << " | "
<< (request->Contains("cert_response") ? "*" : " ") << " " << (request->Contains("cert_response") ? "*" : " ") << " "
<< " | " << " | "
<< request->Get("subject") << request->Get("subject")
<< "\n"; << "\n";
} }
} }

View File

@ -38,7 +38,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
private: private:

View File

@ -44,7 +44,7 @@ int CASignCommand::GetMinArguments(void) const
ImpersonationLevel CASignCommand::GetImpersonationLevel(void) const ImpersonationLevel CASignCommand::GetImpersonationLevel(void) const
{ {
return ImpersonateIcinga; return ImpersonateIcinga;
} }
/** /**
@ -58,7 +58,7 @@ int CASignCommand::Run(const boost::program_options::variables_map& vm, const st
if (!Utility::PathExists(requestFile)) { if (!Utility::PathExists(requestFile)) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "No request exists for fingerprint '" << ap[0] << "'."; << "No request exists for fingerprint '" << ap[0] << "'.";
return 1; return 1;
} }
@ -90,7 +90,7 @@ int CASignCommand::Run(const boost::program_options::variables_map& vm, const st
if (!certResponse) { if (!certResponse) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Could not sign certificate for '" << subject << "'."; << "Could not sign certificate for '" << subject << "'.";
return 1; return 1;
} }
@ -99,7 +99,7 @@ int CASignCommand::Run(const boost::program_options::variables_map& vm, const st
Utility::SaveJsonFile(requestFile, 0600, request); Utility::SaveJsonFile(requestFile, 0600, request);
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Signed certificate for '" << subject << "'."; << "Signed certificate for '" << subject << "'.";
return 0; return 0;
} }

View File

@ -78,7 +78,7 @@ std::vector<String> icinga::GetFieldCompletionSuggestions(const Type::Ptr& type,
continue; continue;
if (strcmp(field.TypeName, "int") != 0 && strcmp(field.TypeName, "double") != 0 if (strcmp(field.TypeName, "int") != 0 && strcmp(field.TypeName, "double") != 0
&& strcmp(field.TypeName, "bool") != 0 && strcmp(field.TypeName, "String") != 0) && strcmp(field.TypeName, "bool") != 0 && strcmp(field.TypeName, "String") != 0)
continue; continue;
String fname = field.Name; String fname = field.Name;
@ -159,7 +159,7 @@ std::vector<String> CLICommand::GetPositionalSuggestions(const String& word) con
} }
void CLICommand::InitParameters(boost::program_options::options_description& visibleDesc, void CLICommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ } { }
ImpersonationLevel CLICommand::GetImpersonationLevel(void) const ImpersonationLevel CLICommand::GetImpersonationLevel(void) const
@ -168,9 +168,9 @@ ImpersonationLevel CLICommand::GetImpersonationLevel(void) const
} }
bool CLICommand::ParseCommand(int argc, char **argv, po::options_description& visibleDesc, bool CLICommand::ParseCommand(int argc, char **argv, po::options_description& visibleDesc,
po::options_description& hiddenDesc, po::options_description& hiddenDesc,
po::positional_options_description& positionalDesc, po::positional_options_description& positionalDesc,
po::variables_map& vm, String& cmdname, CLICommand::Ptr& command, bool autocomplete) po::variables_map& vm, String& cmdname, CLICommand::Ptr& command, bool autocomplete)
{ {
boost::mutex::scoped_lock lock(GetRegistryMutex()); boost::mutex::scoped_lock lock(GetRegistryMutex());
@ -226,8 +226,8 @@ found_command:
if (command && command->IsDeprecated()) { if (command && command->IsDeprecated()) {
std::cerr << ConsoleColorTag(Console_ForegroundRed | Console_Bold) std::cerr << ConsoleColorTag(Console_ForegroundRed | Console_Bold)
<< "Warning: CLI command '" << cmdname << "' is DEPRECATED! Please read the Changelog." << "Warning: CLI command '" << cmdname << "' is DEPRECATED! Please read the Changelog."
<< ConsoleColorTag(Console_Normal) << std::endl << std::endl; << ConsoleColorTag(Console_Normal) << std::endl << std::endl;
} }
po::store(po::command_line_parser(argc - arg_end, argv + arg_end).options(adesc).positional(positionalDesc).run(), vm); po::store(po::command_line_parser(argc - arg_end, argv + arg_end).options(adesc).positional(positionalDesc).run(), vm);
@ -237,9 +237,9 @@ found_command:
} }
void CLICommand::ShowCommands(int argc, char **argv, po::options_description *visibleDesc, void CLICommand::ShowCommands(int argc, char **argv, po::options_description *visibleDesc,
po::options_description *hiddenDesc, po::options_description *hiddenDesc,
ArgumentCompletionCallback globalArgCompletionCallback, ArgumentCompletionCallback globalArgCompletionCallback,
bool autocomplete, int autoindex) bool autocomplete, int autoindex)
{ {
boost::mutex::scoped_lock lock(GetRegistryMutex()); boost::mutex::scoped_lock lock(GetRegistryMutex());
@ -320,8 +320,8 @@ void CLICommand::ShowCommands(int argc, char **argv, po::options_description *vi
} }
} else { } else {
std::cout << " * " << boost::algorithm::join(vname, " ") std::cout << " * " << boost::algorithm::join(vname, " ")
<< " (" << kv.second->GetShortDescription() << ")" << " (" << kv.second->GetShortDescription() << ")"
<< (kv.second->IsDeprecated() ? " (DEPRECATED)" : "") << std::endl; << (kv.second->IsDeprecated() ? " (DEPRECATED)" : "") << std::endl;
} }
} }

View File

@ -61,7 +61,7 @@ public:
virtual bool IsHidden(void) const; virtual bool IsHidden(void) const;
virtual bool IsDeprecated(void) const; virtual bool IsDeprecated(void) const;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const; boost::program_options::options_description& hiddenDesc) const;
virtual ImpersonationLevel GetImpersonationLevel(void) const; virtual ImpersonationLevel GetImpersonationLevel(void) const;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const = 0; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const = 0;
virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const; virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const;
@ -72,16 +72,15 @@ public:
static void Unregister(const std::vector<String>& name); static void Unregister(const std::vector<String>& name);
static bool ParseCommand(int argc, char **argv, boost::program_options::options_description& visibleDesc, static bool ParseCommand(int argc, char **argv, boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc, boost::program_options::options_description& hiddenDesc,
boost::program_options::positional_options_description& positionalDesc, boost::program_options::positional_options_description& positionalDesc,
boost::program_options::variables_map& vm, String& cmdname, boost::program_options::variables_map& vm, String& cmdname, CLICommand::Ptr& command, bool autocomplete);
CLICommand::Ptr& command, bool autocomplete);
static void ShowCommands(int argc, char **argv, static void ShowCommands(int argc, char **argv,
boost::program_options::options_description *visibleDesc = nullptr, boost::program_options::options_description *visibleDesc = nullptr,
boost::program_options::options_description *hiddenDesc = nullptr, boost::program_options::options_description *hiddenDesc = nullptr,
ArgumentCompletionCallback globalArgCompletionCallback = nullptr, ArgumentCompletionCallback globalArgCompletionCallback = nullptr,
bool autocomplete = false, int autoindex = -1); bool autocomplete = false, int autoindex = -1);
private: private:
static boost::mutex& GetRegistryMutex(void); static boost::mutex& GetRegistryMutex(void);

View File

@ -132,7 +132,7 @@ void ConsoleCommand::BreakpointHandler(ScriptFrame& frame, ScriptError *ex, cons
ShowCodeLocation(std::cout, di); ShowCodeLocation(std::cout, di);
std::cout << "You can inspect expressions (such as variables) by entering them at the prompt.\n" std::cout << "You can inspect expressions (such as variables) by entering them at the prompt.\n"
<< "To leave the debugger and continue the program use \"$continue\".\n"; << "To leave the debugger and continue the program use \"$continue\".\n";
#ifdef HAVE_EDITLINE #ifdef HAVE_EDITLINE
rl_completion_entry_function = ConsoleCommand::ConsoleCompleteHelper; rl_completion_entry_function = ConsoleCommand::ConsoleCompleteHelper;
@ -163,7 +163,7 @@ ImpersonationLevel ConsoleCommand::GetImpersonationLevel(void) const
} }
void ConsoleCommand::InitParameters(boost::program_options::options_description& visibleDesc, void ConsoleCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("connect,c", po::value<std::string>(), "connect to an Icinga 2 instance") ("connect,c", po::value<std::string>(), "connect to an Icinga 2 instance")
@ -181,7 +181,7 @@ char *ConsoleCommand::ConsoleCompleteHelper(const char *word, int state)
if (state == 0) { if (state == 0) {
if (!l_ApiClient) if (!l_ApiClient)
matches = ConsoleHandler::GetAutocompletionSuggestions(word, *l_ScriptFrame); matches = ConsoleHandler::GetAutocompletionSuggestions(word, *l_ScriptFrame);
else { else {
boost::mutex mutex; boost::mutex mutex;
boost::condition_variable cv; boost::condition_variable cv;
@ -189,10 +189,10 @@ char *ConsoleCommand::ConsoleCompleteHelper(const char *word, int state)
Array::Ptr suggestions; Array::Ptr suggestions;
l_ApiClient->AutocompleteScript(l_Session, word, l_ScriptFrame->Sandboxed, l_ApiClient->AutocompleteScript(l_Session, word, l_ScriptFrame->Sandboxed,
std::bind(&ConsoleCommand::AutocompleteScriptCompletionHandler, std::bind(&ConsoleCommand::AutocompleteScriptCompletionHandler,
std::ref(mutex), std::ref(cv), std::ref(ready), std::ref(mutex), std::ref(cv), std::ref(ready),
_1, _2, _1, _2,
std::ref(suggestions))); std::ref(suggestions)));
{ {
boost::mutex::scoped_lock lock(mutex); boost::mutex::scoped_lock lock(mutex);
@ -419,10 +419,10 @@ incomplete:
boost::exception_ptr eptr; boost::exception_ptr eptr;
l_ApiClient->ExecuteScript(l_Session, command, scriptFrame.Sandboxed, l_ApiClient->ExecuteScript(l_Session, command, scriptFrame.Sandboxed,
std::bind(&ConsoleCommand::ExecuteScriptCompletionHandler, std::bind(&ConsoleCommand::ExecuteScriptCompletionHandler,
std::ref(mutex), std::ref(cv), std::ref(ready), std::ref(mutex), std::ref(cv), std::ref(ready),
_1, _2, _1, _2,
std::ref(result), std::ref(eptr))); std::ref(result), std::ref(eptr)));
{ {
boost::mutex::scoped_lock lock(mutex); boost::mutex::scoped_lock lock(mutex);
@ -502,7 +502,7 @@ incomplete:
} }
void ConsoleCommand::ExecuteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv, void ConsoleCommand::ExecuteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv,
bool& ready, boost::exception_ptr eptr, const Value& result, Value& resultOut, boost::exception_ptr& eptrOut) bool& ready, boost::exception_ptr eptr, const Value& result, Value& resultOut, boost::exception_ptr& eptrOut)
{ {
if (eptr) { if (eptr) {
try { try {
@ -511,7 +511,7 @@ void ConsoleCommand::ExecuteScriptCompletionHandler(boost::mutex& mutex, boost::
eptrOut = boost::current_exception(); eptrOut = boost::current_exception();
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "ConsoleCommand") Log(LogCritical, "ConsoleCommand")
<< "HTTP query failed: " << ex.what(); << "HTTP query failed: " << ex.what();
Application::Exit(EXIT_FAILURE); Application::Exit(EXIT_FAILURE);
} }
} }
@ -526,14 +526,14 @@ void ConsoleCommand::ExecuteScriptCompletionHandler(boost::mutex& mutex, boost::
} }
void ConsoleCommand::AutocompleteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv, void ConsoleCommand::AutocompleteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv,
bool& ready, boost::exception_ptr eptr, const Array::Ptr& result, Array::Ptr& resultOut) bool& ready, boost::exception_ptr eptr, const Array::Ptr& result, Array::Ptr& resultOut)
{ {
if (eptr) { if (eptr) {
try { try {
boost::rethrow_exception(eptr); boost::rethrow_exception(eptr);
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "ConsoleCommand") Log(LogCritical, "ConsoleCommand")
<< "HTTP query failed: " << ex.what(); << "HTTP query failed: " << ex.what();
Application::Exit(EXIT_FAILURE); Application::Exit(EXIT_FAILURE);
} }
} }

View File

@ -43,22 +43,22 @@ public:
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual ImpersonationLevel GetImpersonationLevel(void) const override; virtual ImpersonationLevel GetImpersonationLevel(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
static int RunScriptConsole(ScriptFrame& scriptFrame, const String& addr = String(), static int RunScriptConsole(ScriptFrame& scriptFrame, const String& addr = String(),
const String& session = String(), const String& commandOnce = String(), const String& commandOnceFileName = String(), const String& session = String(), const String& commandOnce = String(), const String& commandOnceFileName = String(),
bool syntaxOnly = false); bool syntaxOnly = false);
private: private:
mutable boost::mutex m_Mutex; mutable boost::mutex m_Mutex;
mutable boost::condition_variable m_CV; mutable boost::condition_variable m_CV;
static void ExecuteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv, static void ExecuteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv,
bool& ready, boost::exception_ptr eptr, const Value& result, Value& resultOut, bool& ready, boost::exception_ptr eptr, const Value& result, Value& resultOut,
boost::exception_ptr& eptrOut); boost::exception_ptr& eptrOut);
static void AutocompleteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv, static void AutocompleteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv,
bool& ready, boost::exception_ptr eptr, const Array::Ptr& result, Array::Ptr& resultOut); bool& ready, boost::exception_ptr eptr, const Array::Ptr& result, Array::Ptr& resultOut);
#ifdef HAVE_EDITLINE #ifdef HAVE_EDITLINE
static char *ConsoleCompleteHelper(const char *word, int state); static char *ConsoleCompleteHelper(const char *word, int state);

View File

@ -81,7 +81,7 @@ static bool Daemonize(void)
_exit(EXIT_FAILURE); _exit(EXIT_FAILURE);
} else if (ret == -1) { } else if (ret == -1) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "waitpid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "waitpid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
_exit(EXIT_FAILURE); _exit(EXIT_FAILURE);
} }
@ -180,7 +180,7 @@ String DaemonCommand::GetShortDescription(void) const
} }
void DaemonCommand::InitParameters(boost::program_options::options_description& visibleDesc, void DaemonCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("config,c", po::value<std::vector<std::string> >(), "parse a configuration file") ("config,c", po::value<std::vector<std::string> >(), "parse a configuration file")
@ -217,17 +217,17 @@ int DaemonCommand::Run(const po::variables_map& vm, const std::vector<std::strin
Logger::DisableTimestamp(false); Logger::DisableTimestamp(false);
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Icinga application loader (version: " << Application::GetAppVersion() << "Icinga application loader (version: " << Application::GetAppVersion()
#ifdef I2_DEBUG #ifdef I2_DEBUG
<< "; debug" << "; debug"
#endif /* I2_DEBUG */ #endif /* I2_DEBUG */
<< ")"; << ")";
if (!vm.count("validate") && !vm.count("reload-internal")) { if (!vm.count("validate") && !vm.count("reload-internal")) {
pid_t runningpid = Application::ReadPidFile(Application::GetPidPath()); pid_t runningpid = Application::ReadPidFile(Application::GetPidPath());
if (runningpid > 0) { if (runningpid > 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Another instance of Icinga already running with PID " << runningpid; << "Another instance of Icinga already running with PID " << runningpid;
return EXIT_FAILURE; return EXIT_FAILURE;
} }
} }
@ -253,7 +253,7 @@ int DaemonCommand::Run(const po::variables_map& vm, const std::vector<std::strin
if (vm.count("reload-internal")) { if (vm.count("reload-internal")) {
int parentpid = vm["reload-internal"].as<int>(); int parentpid = vm["reload-internal"].as<int>();
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Terminating previous instance of Icinga (PID " << parentpid << ")"; << "Terminating previous instance of Icinga (PID " << parentpid << ")";
TerminateAndWaitForEnd(parentpid); TerminateAndWaitForEnd(parentpid);
Log(LogInformation, "cli", "Previous instance has ended, taking over now."); Log(LogInformation, "cli", "Previous instance has ended, taking over now.");
} }
@ -275,7 +275,7 @@ int DaemonCommand::Run(const po::variables_map& vm, const std::vector<std::strin
ConfigObject::RestoreObjects(Application::GetStatePath()); ConfigObject::RestoreObjects(Application::GetStatePath());
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Failed to restore state file: " << DiagnosticInformation(ex); << "Failed to restore state file: " << DiagnosticInformation(ex);
return EXIT_FAILURE; return EXIT_FAILURE;
} }

View File

@ -38,7 +38,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override; virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
}; };

View File

@ -70,7 +70,7 @@ static void IncludeNonLocalZone(const String& zonePath, const String& package, b
*/ */
if (ConfigCompiler::HasZoneConfigAuthority(zoneName) || Utility::PathExists(zonePath + "/.authoritative")) { if (ConfigCompiler::HasZoneConfigAuthority(zoneName) || Utility::PathExists(zonePath + "/.authoritative")) {
Log(LogNotice, "config") Log(LogNotice, "config")
<< "Ignoring non local config include for zone '" << zoneName << "': We already have an authoritative copy included."; << "Ignoring non local config include for zone '" << zoneName << "': We already have an authoritative copy included.";
return; return;
} }
@ -89,7 +89,7 @@ static void IncludePackage(const String& packagePath, bool& success)
if (Utility::PathExists(packagePath + "/include.conf")) { if (Utility::PathExists(packagePath + "/include.conf")) {
std::unique_ptr<Expression> expr = ConfigCompiler::CompileFile(packagePath + "/include.conf", std::unique_ptr<Expression> expr = ConfigCompiler::CompileFile(packagePath + "/include.conf",
String(), packageName); String(), packageName);
if (!ExecuteExpression(&*expr)) if (!ExecuteExpression(&*expr))
success = false; success = false;
@ -160,8 +160,8 @@ bool DaemonUtility::ValidateConfigFiles(const std::vector<std::string>& configs,
} }
bool DaemonUtility::LoadConfigFiles(const std::vector<std::string>& configs, bool DaemonUtility::LoadConfigFiles(const std::vector<std::string>& configs,
std::vector<ConfigItem::Ptr>& newItems, std::vector<ConfigItem::Ptr>& newItems,
const String& objectsFile, const String& varsfile) const String& objectsFile, const String& varsfile)
{ {
ActivationScope ascope; ActivationScope ascope;

View File

@ -36,7 +36,7 @@ class I2_CLI_API DaemonUtility
public: public:
static bool ValidateConfigFiles(const std::vector<std::string>& configs, const String& objectsFile = String()); static bool ValidateConfigFiles(const std::vector<std::string>& configs, const String& objectsFile = String());
static bool LoadConfigFiles(const std::vector<std::string>& configs, std::vector<ConfigItem::Ptr>& newItems, static bool LoadConfigFiles(const std::vector<std::string>& configs, std::vector<ConfigItem::Ptr>& newItems,
const String& objectsFile = String(), const String& varsfile = String()); const String& objectsFile = String(), const String& varsfile = String());
}; };
} }

View File

@ -62,13 +62,13 @@ int FeatureUtility::EnableFeatures(const std::vector<std::string>& features)
if (!Utility::PathExists(features_available_dir) ) { if (!Utility::PathExists(features_available_dir) ) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot parse available features. Path '" << features_available_dir << "' does not exist."; << "Cannot parse available features. Path '" << features_available_dir << "' does not exist.";
return 1; return 1;
} }
if (!Utility::PathExists(features_enabled_dir) ) { if (!Utility::PathExists(features_enabled_dir) ) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot enable features. Path '" << features_enabled_dir << "' does not exist."; << "Cannot enable features. Path '" << features_enabled_dir << "' does not exist.";
return 1; return 1;
} }
@ -79,7 +79,7 @@ int FeatureUtility::EnableFeatures(const std::vector<std::string>& features)
if (!Utility::PathExists(source) ) { if (!Utility::PathExists(source) ) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot enable feature '" << feature << "'. Source file '" << source + "' does not exist."; << "Cannot enable feature '" << feature << "'. Source file '" << source + "' does not exist.";
errors.push_back(feature); errors.push_back(feature);
continue; continue;
} }
@ -88,20 +88,20 @@ int FeatureUtility::EnableFeatures(const std::vector<std::string>& features)
if (Utility::PathExists(target) ) { if (Utility::PathExists(target) ) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Feature '" << feature << "' already enabled."; << "Feature '" << feature << "' already enabled.";
continue; continue;
} }
std::cout << "Enabling feature " << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << feature std::cout << "Enabling feature " << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << feature
<< ConsoleColorTag(Console_Normal) << ". Make sure to restart Icinga 2 for these changes to take effect.\n"; << ConsoleColorTag(Console_Normal) << ". Make sure to restart Icinga 2 for these changes to take effect.\n";
#ifndef _WIN32 #ifndef _WIN32
String relativeSource = "../features-available/" + feature + ".conf"; String relativeSource = "../features-available/" + feature + ".conf";
if (symlink(relativeSource.CStr(), target.CStr()) < 0) { if (symlink(relativeSource.CStr(), target.CStr()) < 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot enable feature '" << feature << "'. Linking source '" << relativeSource << "' to target file '" << target << "Cannot enable feature '" << feature << "'. Linking source '" << relativeSource << "' to target file '" << target
<< "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"."; << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\".";
errors.push_back(feature); errors.push_back(feature);
continue; continue;
} }
@ -113,7 +113,7 @@ int FeatureUtility::EnableFeatures(const std::vector<std::string>& features)
if (fp.fail()) { if (fp.fail()) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot enable feature '" << feature << "'. Failed to open file '" << target << "'."; << "Cannot enable feature '" << feature << "'. Failed to open file '" << target << "'.";
errors.push_back(feature); errors.push_back(feature);
continue; continue;
} }
@ -122,7 +122,7 @@ int FeatureUtility::EnableFeatures(const std::vector<std::string>& features)
if (!errors.empty()) { if (!errors.empty()) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot enable feature(s): " << boost::algorithm::join(errors, " "); << "Cannot enable feature(s): " << boost::algorithm::join(errors, " ");
errors.clear(); errors.clear();
return 1; return 1;
} }
@ -136,7 +136,7 @@ int FeatureUtility::DisableFeatures(const std::vector<std::string>& features)
if (!Utility::PathExists(features_enabled_dir) ) { if (!Utility::PathExists(features_enabled_dir) ) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot disable features. Path '" << features_enabled_dir << "' does not exist."; << "Cannot disable features. Path '" << features_enabled_dir << "' does not exist.";
return 0; return 0;
} }
@ -147,25 +147,25 @@ int FeatureUtility::DisableFeatures(const std::vector<std::string>& features)
if (!Utility::PathExists(target) ) { if (!Utility::PathExists(target) ) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Feature '" << feature << "' already disabled."; << "Feature '" << feature << "' already disabled.";
continue; continue;
} }
if (unlink(target.CStr()) < 0) { if (unlink(target.CStr()) < 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot disable feature '" << feature << "'. Unlinking target file '" << target << "Cannot disable feature '" << feature << "'. Unlinking target file '" << target
<< "' failed with error code " << errno << ", \"" + Utility::FormatErrorNumber(errno) << "\"."; << "' failed with error code " << errno << ", \"" + Utility::FormatErrorNumber(errno) << "\".";
errors.push_back(feature); errors.push_back(feature);
continue; continue;
} }
std::cout << "Disabling feature " << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << feature std::cout << "Disabling feature " << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << feature
<< ConsoleColorTag(Console_Normal) << ". Make sure to restart Icinga 2 for these changes to take effect.\n"; << ConsoleColorTag(Console_Normal) << ". Make sure to restart Icinga 2 for these changes to take effect.\n";
} }
if (!errors.empty()) { if (!errors.empty()) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot disable feature(s): " << boost::algorithm::join(errors, " "); << "Cannot disable feature(s): " << boost::algorithm::join(errors, " ");
errors.clear(); errors.clear();
return 1; return 1;
} }
@ -182,13 +182,13 @@ int FeatureUtility::ListFeatures(std::ostream& os)
return 1; return 1;
os << ConsoleColorTag(Console_ForegroundRed | Console_Bold) << "Disabled features: " << ConsoleColorTag(Console_Normal) os << ConsoleColorTag(Console_ForegroundRed | Console_Bold) << "Disabled features: " << ConsoleColorTag(Console_Normal)
<< boost::algorithm::join(disabled_features, " ") << "\n"; << boost::algorithm::join(disabled_features, " ") << "\n";
if (!FeatureUtility::GetFeatures(enabled_features, false)) if (!FeatureUtility::GetFeatures(enabled_features, false))
return 1; return 1;
os << ConsoleColorTag(Console_ForegroundGreen | Console_Bold) << "Enabled features: " << ConsoleColorTag(Console_Normal) os << ConsoleColorTag(Console_ForegroundGreen | Console_Bold) << "Enabled features: " << ConsoleColorTag(Console_Normal)
<< boost::algorithm::join(enabled_features, " ") << "\n"; << boost::algorithm::join(enabled_features, " ") << "\n";
return 0; return 0;
} }
@ -254,6 +254,6 @@ void FeatureUtility::CollectFeatures(const String& feature_file, std::vector<Str
boost::algorithm::replace_all(feature, ".conf", ""); boost::algorithm::replace_all(feature, ".conf", "");
Log(LogDebug, "cli") Log(LogDebug, "cli")
<< "Adding feature: " << feature; << "Adding feature: " << feature;
features.push_back(feature); features.push_back(feature);
} }

View File

@ -54,7 +54,7 @@ String NodeSetupCommand::GetShortDescription(void) const
} }
void NodeSetupCommand::InitParameters(boost::program_options::options_description& visibleDesc, void NodeSetupCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("zone", po::value<std::string>(), "The name of the local zone") ("zone", po::value<std::string>(), "The name of the local zone")
@ -98,7 +98,7 @@ int NodeSetupCommand::Run(const boost::program_options::variables_map& vm, const
{ {
if (!ap.empty()) { if (!ap.empty()) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Ignoring parameters: " << boost::algorithm::join(ap, " "); << "Ignoring parameters: " << boost::algorithm::join(ap, " ");
} }
if (vm.count("master")) if (vm.count("master"))
@ -125,23 +125,23 @@ int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& v
if (vm.count("accept-commands")) if (vm.count("accept-commands"))
Log(LogWarning, "cli", "Master for Node setup: Ignoring --accept-commands"); Log(LogWarning, "cli", "Master for Node setup: Ignoring --accept-commands");
String cn = Utility::GetFQDN(); String cn = Utility::GetFQDN();
if (vm.count("cn")) if (vm.count("cn"))
cn = vm["cn"].as<std::string>(); cn = vm["cn"].as<std::string>();
/* check whether the user wants to generate a new certificate or not */ /* check whether the user wants to generate a new certificate or not */
String existingPath = ApiListener::GetCertsDir() + "/" + cn + ".crt"; String existingPath = ApiListener::GetCertsDir() + "/" + cn + ".crt";
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Checking in existing certificates for common name '" << cn << "'..."; << "Checking in existing certificates for common name '" << cn << "'...";
if (Utility::PathExists(existingPath)) { if (Utility::PathExists(existingPath)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Certificate '" << existingPath << "' for CN '" << cn << "' already exists. Not generating new certificate."; << "Certificate '" << existingPath << "' for CN '" << cn << "' already exists. Not generating new certificate.";
} else { } else {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Certificates not yet generated. Running 'api setup' now."; << "Certificates not yet generated. Running 'api setup' now.";
ApiSetupUtility::SetupMasterCertificates(cn); ApiSetupUtility::SetupMasterCertificates(cn);
} }
@ -153,7 +153,7 @@ int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& v
ApiSetupUtility::SetupMasterEnableApi(); ApiSetupUtility::SetupMasterEnableApi();
} else { } else {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "'api' feature already enabled.\n"; << "'api' feature already enabled.\n";
} }
/* write zones.conf and update with zone + endpoint information */ /* write zones.conf and update with zone + endpoint information */
@ -171,9 +171,9 @@ int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& v
String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp); String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
fp << "/**\n" fp << "/**\n"
<< " * The API listener is used for distributed monitoring setups.\n" << " * The API listener is used for distributed monitoring setups.\n"
<< " */\n" << " */\n"
<< "object ApiListener \"api\" {\n"; << "object ApiListener \"api\" {\n";
if (vm.count("listen")) { if (vm.count("listen")) {
std::vector<String> tokens; std::vector<String> tokens;
@ -186,8 +186,8 @@ int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& v
} }
fp << "\n" fp << "\n"
<< " ticket_salt = TicketSalt\n" << " ticket_salt = TicketSalt\n"
<< "}\n"; << "}\n";
fp.close(); fp.close();
@ -197,9 +197,9 @@ int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& v
if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) { if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempApiPath)); << boost::errinfo_file_name(tempApiPath));
} }
/* update constants.conf with NodeName = CN + TicketSalt = random value */ /* update constants.conf with NodeName = CN + TicketSalt = random value */
@ -216,7 +216,7 @@ int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& v
NodeUtility::UpdateConstant("TicketSalt", salt); NodeUtility::UpdateConstant("TicketSalt", salt);
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Edit the api feature config file '" << apipath << "' and set a secure 'ticket_salt' attribute."; << "Edit the api feature config file '" << apipath << "' and set a secure 'ticket_salt' attribute.";
/* tell the user to reload icinga2 */ /* tell the user to reload icinga2 */
@ -245,10 +245,10 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
if (ticket.IsEmpty()) { if (ticket.IsEmpty()) {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Requesting certificate without a ticket."; << "Requesting certificate without a ticket.";
} else { } else {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Requesting certificate with ticket '" << ticket << "'."; << "Requesting certificate with ticket '" << ticket << "'.";
} }
/* require master host information for auto-signing requests */ /* require master host information for auto-signing requests */
@ -271,21 +271,21 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
master_port = tokens[1]; master_port = tokens[1];
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Verifying parent host connection information: host '" << master_host << "', port '" << master_port << "'."; << "Verifying parent host connection information: host '" << master_host << "', port '" << master_port << "'.";
/* trusted cert must be passed (retrieved by the user with 'pki save-cert' before) */ /* trusted cert must be passed (retrieved by the user with 'pki save-cert' before) */
if (!vm.count("trustedcert")) { if (!vm.count("trustedcert")) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Please pass the trusted cert retrieved from the parent node (master or satellite)\n" << "Please pass the trusted cert retrieved from the parent node (master or satellite)\n"
<< "(Hint: 'icinga2 pki save-cert --host <masterhost> --port <5665> --key local.key --cert local.crt --trustedcert master.crt')."; << "(Hint: 'icinga2 pki save-cert --host <masterhost> --port <5665> --key local.key --cert local.crt --trustedcert master.crt').";
return 1; return 1;
} }
std::shared_ptr<X509> trustedcert = GetX509Certificate(vm["trustedcert"].as<std::string>()); std::shared_ptr<X509> trustedcert = GetX509Certificate(vm["trustedcert"].as<std::string>());
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Verifying trusted certificate file '" << vm["trustedcert"].as<std::string>() << "'."; << "Verifying trusted certificate file '" << vm["trustedcert"].as<std::string>() << "'.";
/* retrieve CN and pass it (defaults to FQDN) */ /* retrieve CN and pass it (defaults to FQDN) */
String cn = Utility::GetFQDN(); String cn = Utility::GetFQDN();
@ -294,7 +294,7 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
cn = vm["cn"].as<std::string>(); cn = vm["cn"].as<std::string>();
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Using the following CN (defaults to FQDN): '" << cn << "'."; << "Using the following CN (defaults to FQDN): '" << cn << "'.";
/* pki request a signed certificate from the master */ /* pki request a signed certificate from the master */
@ -306,7 +306,7 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
if (!Utility::SetFileOwnership(pki_path, user, group)) { if (!Utility::SetFileOwnership(pki_path, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << pki_path << "'. Verify it yourself!"; << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << pki_path << "'. Verify it yourself!";
} }
String key = pki_path + "/" + cn + ".key"; String key = pki_path + "/" + cn + ".key";
@ -326,28 +326,28 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
/* fix permissions: root -> icinga daemon user */ /* fix permissions: root -> icinga daemon user */
if (!Utility::SetFileOwnership(key, user, group)) { if (!Utility::SetFileOwnership(key, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << key << "'. Verify it yourself!"; << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << key << "'. Verify it yourself!";
} }
Log(LogInformation, "cli", "Requesting a signed certificate from the parent Icinga node."); Log(LogInformation, "cli", "Requesting a signed certificate from the parent Icinga node.");
if (PkiUtility::RequestCertificate(master_host, master_port, key, cert, ca, trustedcert, ticket) > 0) { if (PkiUtility::RequestCertificate(master_host, master_port, key, cert, ca, trustedcert, ticket) > 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Failed to fetch signed certificate from parent Icinga node '" << "Failed to fetch signed certificate from parent Icinga node '"
<< master_host << ", " << master_host << ", "
<< master_port << "'. Please try again."; << master_port << "'. Please try again.";
return 1; return 1;
} }
if (!Utility::SetFileOwnership(ca, user, group)) { if (!Utility::SetFileOwnership(ca, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << ca << "'. Verify it yourself!"; << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << ca << "'. Verify it yourself!";
} }
/* fix permissions (again) when updating the signed certificate */ /* fix permissions (again) when updating the signed certificate */
if (!Utility::SetFileOwnership(cert, user, group)) { if (!Utility::SetFileOwnership(cert, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << cert << "'. Verify it yourself!"; << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << cert << "'. Verify it yourself!";
} }
/* disable the notifications feature */ /* disable the notifications feature */
@ -368,9 +368,9 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp); String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
fp << "/**\n" fp << "/**\n"
<< " * The API listener is used for distributed monitoring setups.\n" << " * The API listener is used for distributed monitoring setups.\n"
<< " */\n" << " */\n"
<< "object ApiListener \"api\" {\n"; << "object ApiListener \"api\" {\n";
if (vm.count("listen")) { if (vm.count("listen")) {
std::vector<String> tokens; std::vector<String> tokens;
@ -395,7 +395,7 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
fp << " accept_commands = false\n"; fp << " accept_commands = false\n";
fp << "\n" fp << "\n"
<< "}\n"; << "}\n";
fp.close(); fp.close();
@ -405,9 +405,9 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) { if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempApiPath)); << boost::errinfo_file_name(tempApiPath));
} }
/* generate local zones.conf with zone+endpoint */ /* generate local zones.conf with zone+endpoint */
@ -419,7 +419,7 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
/* update constants.conf with NodeName = CN */ /* update constants.conf with NodeName = CN */
if (cn != Utility::GetFQDN()) { if (cn != Utility::GetFQDN()) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "CN '" << cn << "' does not match the default FQDN '" << Utility::GetFQDN() << "'. Requires an update for the NodeName constant in constants.conf!"; << "CN '" << cn << "' does not match the default FQDN '" << Utility::GetFQDN() << "'. Requires an update for the NodeName constant in constants.conf!";
} }
NodeUtility::UpdateConstant("NodeName", cn); NodeUtility::UpdateConstant("NodeName", cn);
@ -432,9 +432,9 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
if (!Utility::SetFileOwnership(tempTicketPath, user, group)) { if (!Utility::SetFileOwnership(tempTicketPath, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "Cannot set ownership for user '" << user
<< "' group '" << group << "' group '" << group
<< "' on file '" << tempTicketPath << "'. Verify it yourself!"; << "' on file '" << tempTicketPath << "'. Verify it yourself!";
} }
fp << ticket; fp << ticket;
@ -447,9 +447,9 @@ int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm,
if (rename(tempTicketPath.CStr(), ticketPath.CStr()) < 0) { if (rename(tempTicketPath.CStr(), ticketPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempTicketPath)); << boost::errinfo_file_name(tempTicketPath));
} }
} }

View File

@ -38,7 +38,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override; virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override;
virtual ImpersonationLevel GetImpersonationLevel(void) const override; virtual ImpersonationLevel GetImpersonationLevel(void) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;

View File

@ -124,7 +124,7 @@ int NodeUtility::GenerateNodeIcingaConfig(const std::vector<std::string>& endpoi
myGlobalZone->Set("global", true); myGlobalZone->Set("global", true);
my_config->Add(myGlobalZone); my_config->Add(myGlobalZone);
} }
/* store the local config */ /* store the local config */
my_config->Add(my_endpoint); my_config->Add(my_endpoint);
@ -182,7 +182,7 @@ int NodeUtility::GenerateNodeMasterIcingaConfig(const std::vector<String>& globa
bool NodeUtility::WriteNodeConfigObjects(const String& filename, const Array::Ptr& objects) bool NodeUtility::WriteNodeConfigObjects(const String& filename, const Array::Ptr& objects)
{ {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Dumping config items to file '" << filename << "'."; << "Dumping config items to file '" << filename << "'.";
/* create a backup first */ /* create a backup first */
CreateBackupFile(filename); CreateBackupFile(filename);
@ -196,11 +196,11 @@ bool NodeUtility::WriteNodeConfigObjects(const String& filename, const Array::Pt
if (!Utility::SetFileOwnership(path, user, group)) { if (!Utility::SetFileOwnership(path, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "' group '" << group << "' on path '" << path << "'. Verify it yourself!"; << "Cannot set ownership for user '" << user << "' group '" << group << "' on path '" << path << "'. Verify it yourself!";
} }
if (!Utility::SetFileOwnership(filename, user, group)) { if (!Utility::SetFileOwnership(filename, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "' group '" << group << "' on path '" << path << "'. Verify it yourself!"; << "Cannot set ownership for user '" << user << "' group '" << group << "' on path '" << path << "'. Verify it yourself!";
} }
std::fstream fp; std::fstream fp;
@ -225,9 +225,9 @@ bool NodeUtility::WriteNodeConfigObjects(const String& filename, const Array::Pt
if (rename(tempFilename.CStr(), filename.CStr()) < 0) { if (rename(tempFilename.CStr(), filename.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempFilename)); << boost::errinfo_file_name(tempFilename));
} }
return true; return true;
@ -246,7 +246,7 @@ bool NodeUtility::CreateBackupFile(const String& target, bool is_private)
if (Utility::PathExists(backup)) { if (Utility::PathExists(backup)) {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Backup file '" << backup << "' already exists. Skipping backup."; << "Backup file '" << backup << "' already exists. Skipping backup.";
return false; return false;
} }
@ -258,7 +258,7 @@ bool NodeUtility::CreateBackupFile(const String& target, bool is_private)
#endif /* _WIN32 */ #endif /* _WIN32 */
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Created backup file '" << backup << "'."; << "Created backup file '" << backup << "'.";
return true; return true;
} }
@ -291,7 +291,7 @@ void NodeUtility::UpdateConstant(const String& name, const String& value)
String constantsConfPath = NodeUtility::GetConstantsConfPath(); String constantsConfPath = NodeUtility::GetConstantsConfPath();
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Updating '" << name << "' constant in '" << constantsConfPath << "'."; << "Updating '" << name << "' constant in '" << constantsConfPath << "'.";
NodeUtility::CreateBackupFile(constantsConfPath); NodeUtility::CreateBackupFile(constantsConfPath);

View File

@ -63,7 +63,7 @@ int NodeWizardCommand::GetMaxArguments(void) const
} }
void NodeWizardCommand::InitParameters(boost::program_options::options_description& visibleDesc, void NodeWizardCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("verbose", "increase log level"); ("verbose", "increase log level");
@ -75,7 +75,7 @@ void NodeWizardCommand::InitParameters(boost::program_options::options_descripti
* @returns An exit status. * @returns An exit status.
*/ */
int NodeWizardCommand::Run(const boost::program_options::variables_map& vm, int NodeWizardCommand::Run(const boost::program_options::variables_map& vm,
const std::vector<std::string>& ap) const const std::vector<std::string>& ap) const
{ {
if (!vm.count("verbose")) if (!vm.count("verbose"))
Logger::SetConsoleLogSeverity(LogCritical); Logger::SetConsoleLogSeverity(LogCritical);
@ -86,11 +86,11 @@ int NodeWizardCommand::Run(const boost::program_options::variables_map& vm,
*/ */
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundBlue) std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundBlue)
<< "Welcome to the Icinga 2 Setup Wizard!\n" << "Welcome to the Icinga 2 Setup Wizard!\n"
<< "\n" << "\n"
<< "We will guide you through all required configuration details.\n" << "We will guide you through all required configuration details.\n"
<< "\n" << "\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
/* 0. master or node setup? /* 0. master or node setup?
* 1. Ticket * 1. Ticket
@ -110,9 +110,9 @@ int NodeWizardCommand::Run(const boost::program_options::variables_map& vm,
std::string answer; std::string answer;
/* master or satellite/client setup */ /* master or satellite/client setup */
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Please specify if this is a satellite/client setup " << "Please specify if this is a satellite/client setup "
<< "('n' installs a master setup)" << ConsoleColorTag(Console_Normal) << "('n' installs a master setup)" << ConsoleColorTag(Console_Normal)
<< " [Y/n]: "; << " [Y/n]: ";
std::getline (std::cin, answer); std::getline (std::cin, answer);
boost::algorithm::to_lower(answer); boost::algorithm::to_lower(answer);
@ -133,12 +133,12 @@ int NodeWizardCommand::Run(const boost::program_options::variables_map& vm,
std::cout << "\n"; std::cout << "\n";
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen) std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen)
<< "Done.\n\n" << "Done.\n\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundRed) std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundRed)
<< "Now restart your Icinga 2 daemon to finish the installation!\n" << "Now restart your Icinga 2 daemon to finish the installation!\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
return 0; return 0;
} }
@ -153,9 +153,9 @@ int NodeWizardCommand::ClientSetup(void) const
/* CN */ /* CN */
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Please specify the common name (CN)" << "Please specify the common name (CN)"
<< ConsoleColorTag(Console_Normal) << ConsoleColorTag(Console_Normal)
<< " [" << Utility::GetFQDN() << "]: "; << " [" << Utility::GetFQDN() << "]: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -170,15 +170,15 @@ int NodeWizardCommand::ClientSetup(void) const
String endpointBuffer; String endpointBuffer;
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "\nPlease specify the parent endpoint(s) (master or satellite) where this node should connect to:" << "\nPlease specify the parent endpoint(s) (master or satellite) where this node should connect to:"
<< ConsoleColorTag(Console_Normal) << "\n"; << ConsoleColorTag(Console_Normal) << "\n";
String parentEndpointName; String parentEndpointName;
wizard_endpoint_loop_start: wizard_endpoint_loop_start:
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Master/Satellite Common Name" << ConsoleColorTag(Console_Normal) << "Master/Satellite Common Name" << ConsoleColorTag(Console_Normal)
<< " (CN from your master/satellite node): "; << " (CN from your master/satellite node): ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -191,8 +191,8 @@ wizard_endpoint_loop_start:
endpointBuffer = endpointBuffer.Trim(); endpointBuffer = endpointBuffer.Trim();
std::cout << "\nDo you want to establish a connection to the parent node " std::cout << "\nDo you want to establish a connection to the parent node "
<< ConsoleColorTag(Console_Bold) << "from this node?" << ConsoleColorTag(Console_Bold) << "from this node?"
<< ConsoleColorTag(Console_Normal) << " [Y/n]: "; << ConsoleColorTag(Console_Normal) << " [Y/n]: ";
std::getline (std::cin, answer); std::getline (std::cin, answer);
boost::algorithm::to_lower(answer); boost::algorithm::to_lower(answer);
@ -205,16 +205,16 @@ wizard_endpoint_loop_start:
Log(LogWarning, "cli", "Node to master/satellite connection setup skipped"); Log(LogWarning, "cli", "Node to master/satellite connection setup skipped");
std::cout << "Connection setup skipped. Please configure your parent node to\n" std::cout << "Connection setup skipped. Please configure your parent node to\n"
<< "connect to this node by setting the 'host' attribute for the node Endpoint object.\n"; << "connect to this node by setting the 'host' attribute for the node Endpoint object.\n";
} else { } else {
connectToParent = true; connectToParent = true;
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Please specify the master/satellite connection information:" << "Please specify the master/satellite connection information:"
<< ConsoleColorTag(Console_Normal) << "\n" << ConsoleColorTag(Console_Normal) << "\n"
<< ConsoleColorTag(Console_Bold) << "Master/Satellite endpoint host" << ConsoleColorTag(Console_Bold) << "Master/Satellite endpoint host"
<< ConsoleColorTag(Console_Normal) << " (IP address or FQDN): "; << ConsoleColorTag(Console_Normal) << " (IP address or FQDN): ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -230,8 +230,8 @@ wizard_endpoint_loop_start:
parentEndpointName = tmp; parentEndpointName = tmp;
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Master/Satellite endpoint port" << ConsoleColorTag(Console_Normal) << "Master/Satellite endpoint port" << ConsoleColorTag(Console_Normal)
<< " [" << parentEndpointPort << "]: "; << " [" << parentEndpointPort << "]: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -244,7 +244,7 @@ wizard_endpoint_loop_start:
endpoints.push_back(endpointBuffer); endpoints.push_back(endpointBuffer);
std::cout << ConsoleColorTag(Console_Bold) << "\nAdd more master/satellite endpoints?" std::cout << ConsoleColorTag(Console_Bold) << "\nAdd more master/satellite endpoints?"
<< ConsoleColorTag(Console_Normal) << " [y/N]: "; << ConsoleColorTag(Console_Normal) << " [y/N]: ";
std::getline (std::cin, answer); std::getline (std::cin, answer);
boost::algorithm::to_lower(answer); boost::algorithm::to_lower(answer);
@ -275,9 +275,9 @@ wizard_endpoint_loop_start:
if (!Utility::SetFileOwnership(certsDir, user, group)) { if (!Utility::SetFileOwnership(certsDir, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "Cannot set ownership for user '" << user
<< "' group '" << group << "' group '" << group
<< "' on file '" << certsDir << "'. Verify it yourself!"; << "' on file '" << certsDir << "'. Verify it yourself!";
} }
String nodeCert = certsDir + "/" + cn + ".crt"; String nodeCert = certsDir + "/" + cn + ".crt";
@ -290,17 +290,17 @@ wizard_endpoint_loop_start:
if (PkiUtility::NewCert(cn, nodeKey, Empty, nodeCert) > 0) { if (PkiUtility::NewCert(cn, nodeKey, Empty, nodeCert) > 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Failed to create new self-signed certificate for CN '" << "Failed to create new self-signed certificate for CN '"
<< cn << "'. Please try again."; << cn << "'. Please try again.";
return 1; return 1;
} }
/* fix permissions: root -> icinga daemon user */ /* fix permissions: root -> icinga daemon user */
if (!Utility::SetFileOwnership(nodeKey, user, group)) { if (!Utility::SetFileOwnership(nodeKey, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "Cannot set ownership for user '" << user
<< "' group '" << group << "' group '" << group
<< "' on file '" << nodeKey << "'. Verify it yourself!"; << "' on file '" << nodeKey << "'. Verify it yourself!";
} }
std::shared_ptr<X509> trustedParentCert; std::shared_ptr<X509> trustedParentCert;
@ -309,8 +309,8 @@ wizard_endpoint_loop_start:
if (connectToParent) { if (connectToParent) {
//save-cert and store the master certificate somewhere //save-cert and store the master certificate somewhere
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Fetching public certificate from master (" << "Fetching public certificate from master ("
<< parentHost << ", " << parentPort << "):\n"; << parentHost << ", " << parentPort << "):\n";
trustedParentCert = PkiUtility::FetchCert(parentHost, parentPort); trustedParentCert = PkiUtility::FetchCert(parentHost, parentPort);
if (!trustedParentCert) { if (!trustedParentCert) {
@ -319,9 +319,9 @@ wizard_endpoint_loop_start:
} }
std::cout << ConsoleColorTag(Console_Bold) << "Parent certificate information:\n" std::cout << ConsoleColorTag(Console_Bold) << "Parent certificate information:\n"
<< ConsoleColorTag(Console_Normal) << PkiUtility::GetCertificateInformation(trustedParentCert) << ConsoleColorTag(Console_Normal) << PkiUtility::GetCertificateInformation(trustedParentCert)
<< ConsoleColorTag(Console_Bold) << "\nIs this information correct?" << ConsoleColorTag(Console_Bold) << "\nIs this information correct?"
<< ConsoleColorTag(Console_Normal) << " [y/N]: "; << ConsoleColorTag(Console_Normal) << " [y/N]: ";
std::getline (std::cin, answer); std::getline (std::cin, answer);
boost::algorithm::to_lower(answer); boost::algorithm::to_lower(answer);
@ -340,19 +340,19 @@ wizard_ticket:
/* Check whether we can connect to the parent node and fetch the client and CA certificate. */ /* Check whether we can connect to the parent node and fetch the client and CA certificate. */
if (connectToParent) { if (connectToParent) {
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "\nPlease specify the request ticket generated on your Icinga 2 master " << "\nPlease specify the request ticket generated on your Icinga 2 master "
<< ConsoleColorTag(Console_Normal) << "(optional)" << ConsoleColorTag(Console_Normal) << "(optional)"
<< ConsoleColorTag(Console_Bold) << "." << ConsoleColorTag(Console_Bold) << "."
<< ConsoleColorTag(Console_Normal) << "\n" << ConsoleColorTag(Console_Normal) << "\n"
<< " (Hint: # icinga2 pki ticket --cn '" << cn << "'): "; << " (Hint: # icinga2 pki ticket --cn '" << cn << "'): ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
if (answer.empty()) { if (answer.empty()) {
std::cout << ConsoleColorTag(Console_Bold) << "\n" std::cout << ConsoleColorTag(Console_Bold) << "\n"
<< "No ticket was specified. Please approve the certificate signing request manually\n" << "No ticket was specified. Please approve the certificate signing request manually\n"
<< "on the master (see 'icinga2 ca list' and 'icinga2 ca sign --help' for details)." << "on the master (see 'icinga2 ca list' and 'icinga2 ca sign --help' for details)."
<< ConsoleColorTag(Console_Normal) << "\n"; << ConsoleColorTag(Console_Normal) << "\n";
} }
ticket = answer; ticket = answer;
@ -360,10 +360,10 @@ wizard_ticket:
if (ticket.IsEmpty()) { if (ticket.IsEmpty()) {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Requesting certificate without a ticket."; << "Requesting certificate without a ticket.";
} else { } else {
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Requesting certificate with ticket '" << ticket << "'."; << "Requesting certificate with ticket '" << ticket << "'.";
} }
if (Utility::PathExists(nodeCA)) if (Utility::PathExists(nodeCA))
@ -372,20 +372,20 @@ wizard_ticket:
NodeUtility::CreateBackupFile(nodeCert); NodeUtility::CreateBackupFile(nodeCert);
if (PkiUtility::RequestCertificate(parentHost, parentPort, nodeKey, if (PkiUtility::RequestCertificate(parentHost, parentPort, nodeKey,
nodeCert, nodeCA, trustedParentCert, ticket) > 0) { nodeCert, nodeCA, trustedParentCert, ticket) > 0) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Failed to fetch signed certificate from master '" << "Failed to fetch signed certificate from master '"
<< parentHost << ", " << parentHost << ", "
<< parentPort << "'. Please try again."; << parentPort << "'. Please try again.";
goto wizard_ticket; goto wizard_ticket;
} }
/* fix permissions (again) when updating the signed certificate */ /* fix permissions (again) when updating the signed certificate */
if (!Utility::SetFileOwnership(nodeCert, user, group)) { if (!Utility::SetFileOwnership(nodeCert, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "Cannot set ownership for user '" << user
<< "' group '" << group << "' on file '" << "' group '" << group << "' on file '"
<< nodeCert << "'. Verify it yourself!"; << nodeCert << "'. Verify it yourself!";
} }
} else { } else {
/* We cannot retrieve the parent certificate. /* We cannot retrieve the parent certificate.
@ -394,28 +394,28 @@ wizard_ticket:
*/ */
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "\nNo connection to the parent node was specified.\n\n" << "\nNo connection to the parent node was specified.\n\n"
<< "Please copy the public CA certificate from your master/satellite\n" << "Please copy the public CA certificate from your master/satellite\n"
<< "into '" << nodeCA << "' before starting Icinga 2.\n" << "into '" << nodeCA << "' before starting Icinga 2.\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
if (Utility::PathExists(nodeCA)) { if (Utility::PathExists(nodeCA)) {
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "\nFound public CA certificate in '" << nodeCA << "'.\n" << "\nFound public CA certificate in '" << nodeCA << "'.\n"
<< "Please verify that it is the same as on your master/satellite.\n" << "Please verify that it is the same as on your master/satellite.\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
} }
} }
/* apilistener config */ /* apilistener config */
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Please specify the API bind host/port " << "Please specify the API bind host/port "
<< ConsoleColorTag(Console_Normal) << "(optional)" << ConsoleColorTag(Console_Normal) << "(optional)"
<< ConsoleColorTag(Console_Bold) << ":\n"; << ConsoleColorTag(Console_Bold) << ":\n";
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Bind Host" << ConsoleColorTag(Console_Normal) << " []: "; << "Bind Host" << ConsoleColorTag(Console_Normal) << " []: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -423,7 +423,7 @@ wizard_ticket:
bindHost = bindHost.Trim(); bindHost = bindHost.Trim();
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Bind Port" << ConsoleColorTag(Console_Normal) << " []: "; << "Bind Port" << ConsoleColorTag(Console_Normal) << " []: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -431,8 +431,8 @@ wizard_ticket:
bindPort = bindPort.Trim(); bindPort = bindPort.Trim();
std::cout << ConsoleColorTag(Console_Bold) << "\n" std::cout << ConsoleColorTag(Console_Bold) << "\n"
<< "Accept config from parent node?" << ConsoleColorTag(Console_Normal) << "Accept config from parent node?" << ConsoleColorTag(Console_Normal)
<< " [y/N]: "; << " [y/N]: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
boost::algorithm::to_lower(answer); boost::algorithm::to_lower(answer);
choice = answer; choice = answer;
@ -440,8 +440,8 @@ wizard_ticket:
String acceptConfig = choice.Contains("y") ? "true" : "false"; String acceptConfig = choice.Contains("y") ? "true" : "false";
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Accept commands from parent node?" << ConsoleColorTag(Console_Normal) << "Accept commands from parent node?" << ConsoleColorTag(Console_Normal)
<< " [y/N]: "; << " [y/N]: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
boost::algorithm::to_lower(answer); boost::algorithm::to_lower(answer);
choice = answer; choice = answer;
@ -451,8 +451,8 @@ wizard_ticket:
std::cout << "\n"; std::cout << "\n";
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen) std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen)
<< "Reconfiguring Icinga...\n" << "Reconfiguring Icinga...\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
/* disable the notifications feature on client nodes */ /* disable the notifications feature on client nodes */
Log(LogInformation, "cli", "Disabling the Notification feature."); Log(LogInformation, "cli", "Disabling the Notification feature.");
@ -470,11 +470,11 @@ wizard_ticket:
String tempApiConfPath = Utility::CreateTempFile(apiConfPath + ".XXXXXX", 0644, fp); String tempApiConfPath = Utility::CreateTempFile(apiConfPath + ".XXXXXX", 0644, fp);
fp << "/**\n" fp << "/**\n"
<< " * The API listener is used for distributed monitoring setups.\n" << " * The API listener is used for distributed monitoring setups.\n"
<< " */\n" << " */\n"
<< "object ApiListener \"api\" {\n" << "object ApiListener \"api\" {\n"
<< " accept_config = " << acceptConfig << "\n" << " accept_config = " << acceptConfig << "\n"
<< " accept_commands = " << acceptCommands << "\n"; << " accept_commands = " << acceptCommands << "\n";
if (!bindHost.IsEmpty()) if (!bindHost.IsEmpty())
fp << " bind_host = \"" << bindHost << "\"\n"; fp << " bind_host = \"" << bindHost << "\"\n";
@ -491,9 +491,9 @@ wizard_ticket:
if (rename(tempApiConfPath.CStr(), apiConfPath.CStr()) < 0) { if (rename(tempApiConfPath.CStr(), apiConfPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempApiConfPath)); << boost::errinfo_file_name(tempApiConfPath));
} }
/* apilistener config */ /* apilistener config */
@ -503,8 +503,8 @@ wizard_ticket:
if (cn != Utility::GetFQDN()) { if (cn != Utility::GetFQDN()) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "CN '" << cn << "' does not match the default FQDN '" << "CN '" << cn << "' does not match the default FQDN '"
<< Utility::GetFQDN() << "'. Requires update for NodeName constant in constants.conf!"; << Utility::GetFQDN() << "'. Requires update for NodeName constant in constants.conf!";
} }
NodeUtility::UpdateConstant("NodeName", cn); NodeUtility::UpdateConstant("NodeName", cn);
@ -517,9 +517,9 @@ wizard_ticket:
if (!Utility::SetFileOwnership(tempTicketPath, user, group)) { if (!Utility::SetFileOwnership(tempTicketPath, user, group)) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "Cannot set ownership for user '" << user << "Cannot set ownership for user '" << user
<< "' group '" << group << "' group '" << group
<< "' on file '" << tempTicketPath << "'. Verify it yourself!"; << "' on file '" << tempTicketPath << "'. Verify it yourself!";
} }
fp << ticket; fp << ticket;
@ -532,9 +532,9 @@ wizard_ticket:
if (rename(tempTicketPath.CStr(), ticketPath.CStr()) < 0) { if (rename(tempTicketPath.CStr(), ticketPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempTicketPath)); << boost::errinfo_file_name(tempTicketPath));
} }
} }
@ -550,8 +550,8 @@ int NodeWizardCommand::MasterSetup(void) const
/* CN */ /* CN */
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Please specify the common name" << ConsoleColorTag(Console_Normal) << "Please specify the common name" << ConsoleColorTag(Console_Normal)
<< " (CN) [" << Utility::GetFQDN() << "]: "; << " (CN) [" << Utility::GetFQDN() << "]: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -562,26 +562,26 @@ int NodeWizardCommand::MasterSetup(void) const
cn = cn.Trim(); cn = cn.Trim();
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen) std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen)
<< "Reconfiguring Icinga...\n" << "Reconfiguring Icinga...\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
/* check whether the user wants to generate a new certificate or not */ /* check whether the user wants to generate a new certificate or not */
String existing_path = ApiListener::GetCertsDir() + "/" + cn + ".crt"; String existing_path = ApiListener::GetCertsDir() + "/" + cn + ".crt";
std::cout << ConsoleColorTag(Console_Normal) std::cout << ConsoleColorTag(Console_Normal)
<< "Checking for existing certificates for common name '" << cn << "'...\n"; << "Checking for existing certificates for common name '" << cn << "'...\n";
if (Utility::PathExists(existing_path)) { if (Utility::PathExists(existing_path)) {
std::cout << "Certificate '" << existing_path << "' for CN '" std::cout << "Certificate '" << existing_path << "' for CN '"
<< cn << "' already existing. Skipping certificate generation.\n"; << cn << "' already existing. Skipping certificate generation.\n";
} else { } else {
std::cout << "Certificates not yet generated. Running 'api setup' now.\n"; std::cout << "Certificates not yet generated. Running 'api setup' now.\n";
ApiSetupUtility::SetupMasterCertificates(cn); ApiSetupUtility::SetupMasterCertificates(cn);
} }
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Generating master configuration for Icinga 2.\n" << "Generating master configuration for Icinga 2.\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
ApiSetupUtility::SetupMasterApiUser(); ApiSetupUtility::SetupMasterApiUser();
if (!FeatureUtility::CheckFeatureEnabled("api")) if (!FeatureUtility::CheckFeatureEnabled("api"))
@ -593,12 +593,12 @@ int NodeWizardCommand::MasterSetup(void) const
/* apilistener config */ /* apilistener config */
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Please specify the API bind host/port " << "Please specify the API bind host/port "
<< ConsoleColorTag(Console_Normal) << "(optional)" << ConsoleColorTag(Console_Normal) << "(optional)"
<< ConsoleColorTag(Console_Bold) << ":\n"; << ConsoleColorTag(Console_Bold) << ":\n";
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Bind Host" << ConsoleColorTag(Console_Normal) << " []: "; << "Bind Host" << ConsoleColorTag(Console_Normal) << " []: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -606,7 +606,7 @@ int NodeWizardCommand::MasterSetup(void) const
bindHost = bindHost.Trim(); bindHost = bindHost.Trim();
std::cout << ConsoleColorTag(Console_Bold) std::cout << ConsoleColorTag(Console_Bold)
<< "Bind Port" << ConsoleColorTag(Console_Normal) << " []: "; << "Bind Port" << ConsoleColorTag(Console_Normal) << " []: ";
std::getline(std::cin, answer); std::getline(std::cin, answer);
@ -621,9 +621,9 @@ int NodeWizardCommand::MasterSetup(void) const
String tempApiConfPath = Utility::CreateTempFile(apiConfPath + ".XXXXXX", 0644, fp); String tempApiConfPath = Utility::CreateTempFile(apiConfPath + ".XXXXXX", 0644, fp);
fp << "/**\n" fp << "/**\n"
<< " * The API listener is used for distributed monitoring setups.\n" << " * The API listener is used for distributed monitoring setups.\n"
<< " */\n" << " */\n"
<< "object ApiListener \"api\" {\n"; << "object ApiListener \"api\" {\n";
if (!bindHost.IsEmpty()) if (!bindHost.IsEmpty())
fp << " bind_host = \"" << bindHost << "\"\n"; fp << " bind_host = \"" << bindHost << "\"\n";
@ -631,8 +631,8 @@ int NodeWizardCommand::MasterSetup(void) const
fp << " bind_port = " << bindPort << "\n"; fp << " bind_port = " << bindPort << "\n";
fp << "\n" fp << "\n"
<< " ticket_salt = TicketSalt\n" << " ticket_salt = TicketSalt\n"
<< "}\n"; << "}\n";
fp.close(); fp.close();
@ -642,16 +642,16 @@ int NodeWizardCommand::MasterSetup(void) const
if (rename(tempApiConfPath.CStr(), apiConfPath.CStr()) < 0) { if (rename(tempApiConfPath.CStr(), apiConfPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempApiConfPath)); << boost::errinfo_file_name(tempApiConfPath));
} }
/* update constants.conf with NodeName = CN + TicketSalt = random value */ /* update constants.conf with NodeName = CN + TicketSalt = random value */
if (cn != Utility::GetFQDN()) { if (cn != Utility::GetFQDN()) {
Log(LogWarning, "cli") Log(LogWarning, "cli")
<< "CN '" << cn << "' does not match the default FQDN '" << "CN '" << cn << "' does not match the default FQDN '"
<< Utility::GetFQDN() << "'. Requires an update for the NodeName constant in constants.conf!"; << Utility::GetFQDN() << "'. Requires an update for the NodeName constant in constants.conf!";
} }
NodeUtility::UpdateConstant("NodeName", cn); NodeUtility::UpdateConstant("NodeName", cn);

View File

@ -41,7 +41,7 @@ public:
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
virtual ImpersonationLevel GetImpersonationLevel(void) const override; virtual ImpersonationLevel GetImpersonationLevel(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
private: private:
int ClientSetup(void) const; int ClientSetup(void) const;

View File

@ -52,7 +52,7 @@ String ObjectListCommand::GetShortDescription(void) const
} }
void ObjectListCommand::InitParameters(boost::program_options::options_description& visibleDesc, void ObjectListCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("count,c", "display object counts by types") ("count,c", "display object counts by types")
@ -71,7 +71,7 @@ int ObjectListCommand::Run(const boost::program_options::variables_map& vm, cons
if (!Utility::PathExists(objectfile)) { if (!Utility::PathExists(objectfile)) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot open objects file '" << Application::GetObjectsPath() << "'."; << "Cannot open objects file '" << Application::GetObjectsPath() << "'.";
Log(LogCritical, "cli", "Run 'icinga2 daemon -C' to validate config and generate the cache file."); Log(LogCritical, "cli", "Run 'icinga2 daemon -C' to validate config and generate the cache file.");
return 1; return 1;
} }
@ -119,7 +119,7 @@ int ObjectListCommand::Run(const boost::program_options::variables_map& vm, cons
} }
Log(LogNotice, "cli") Log(LogNotice, "cli")
<< "Parsed " << objects_count << " objects."; << "Parsed " << objects_count << " objects.";
return 0; return 0;
} }

View File

@ -41,7 +41,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
private: private:

View File

@ -37,7 +37,7 @@ String PKINewCertCommand::GetShortDescription(void) const
} }
void PKINewCertCommand::InitParameters(boost::program_options::options_description& visibleDesc, void PKINewCertCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("cn", po::value<std::string>(), "Common Name") ("cn", po::value<std::string>(), "Common Name")

View File

@ -38,7 +38,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override; virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;

View File

@ -39,16 +39,16 @@ String PKIRequestCommand::GetShortDescription(void) const
} }
void PKIRequestCommand::InitParameters(boost::program_options::options_description& visibleDesc, void PKIRequestCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("key", po::value<std::string>(), "Key file path (input)") ("key", po::value<std::string>(), "Key file path (input)")
("cert", po::value<std::string>(), "Certificate file path (input + output)") ("cert", po::value<std::string>(), "Certificate file path (input + output)")
("ca", po::value<std::string>(), "CA file path (output)") ("ca", po::value<std::string>(), "CA file path (output)")
("trustedcert", po::value<std::string>(), "Trusted certificate file path (input)") ("trustedcert", po::value<std::string>(), "Trusted certificate file path (input)")
("host", po::value<std::string>(), "Icinga 2 host") ("host", po::value<std::string>(), "Icinga 2 host")
("port", po::value<std::string>(), "Icinga 2 port") ("port", po::value<std::string>(), "Icinga 2 port")
("ticket", po::value<std::string>(), "Icinga 2 PKI ticket"); ("ticket", po::value<std::string>(), "Icinga 2 PKI ticket");
} }
std::vector<String> PKIRequestCommand::GetArgumentSuggestions(const String& argument, const String& word) const std::vector<String> PKIRequestCommand::GetArgumentSuggestions(const String& argument, const String& word) const
@ -105,6 +105,6 @@ int PKIRequestCommand::Run(const boost::program_options::variables_map& vm, cons
ticket = vm["ticket"].as<std::string>(); ticket = vm["ticket"].as<std::string>();
return PkiUtility::RequestCertificate(vm["host"].as<std::string>(), port, vm["key"].as<std::string>(), return PkiUtility::RequestCertificate(vm["host"].as<std::string>(), port, vm["key"].as<std::string>(),
vm["cert"].as<std::string>(), vm["ca"].as<std::string>(), GetX509Certificate(vm["trustedcert"].as<std::string>()), vm["cert"].as<std::string>(), vm["ca"].as<std::string>(), GetX509Certificate(vm["trustedcert"].as<std::string>()),
ticket); ticket);
} }

View File

@ -38,7 +38,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override; virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;

View File

@ -40,14 +40,14 @@ String PKISaveCertCommand::GetShortDescription(void) const
} }
void PKISaveCertCommand::InitParameters(boost::program_options::options_description& visibleDesc, void PKISaveCertCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("key", po::value<std::string>(), "Key file path (input), obsolete") ("key", po::value<std::string>(), "Key file path (input), obsolete")
("cert", po::value<std::string>(), "Certificate file path (input), obsolete") ("cert", po::value<std::string>(), "Certificate file path (input), obsolete")
("trustedcert", po::value<std::string>(), "Trusted certificate file path (output)") ("trustedcert", po::value<std::string>(), "Trusted certificate file path (output)")
("host", po::value<std::string>(), "Icinga 2 host") ("host", po::value<std::string>(), "Icinga 2 host")
("port", po::value<std::string>()->default_value("5665"), "Icinga 2 port"); ("port", po::value<std::string>()->default_value("5665"), "Icinga 2 port");
} }
std::vector<String> PKISaveCertCommand::GetArgumentSuggestions(const String& argument, const String& word) const std::vector<String> PKISaveCertCommand::GetArgumentSuggestions(const String& argument, const String& word) const
@ -83,7 +83,7 @@ int PKISaveCertCommand::Run(const boost::program_options::variables_map& vm, con
String port = vm["port"].as<std::string>(); String port = vm["port"].as<std::string>();
Log(LogInformation, "cli") Log(LogInformation, "cli")
<< "Retrieving X.509 certificate for '" << host << ":" << port << "'."; << "Retrieving X.509 certificate for '" << host << ":" << port << "'.";
std::shared_ptr<X509> cert = PkiUtility::FetchCert(host, port); std::shared_ptr<X509> cert = PkiUtility::FetchCert(host, port);
@ -94,11 +94,11 @@ int PKISaveCertCommand::Run(const boost::program_options::variables_map& vm, con
std::cout << PkiUtility::GetCertificateInformation(cert) << "\n"; std::cout << PkiUtility::GetCertificateInformation(cert) << "\n";
std::cout << ConsoleColorTag(Console_ForegroundRed) std::cout << ConsoleColorTag(Console_ForegroundRed)
<< "***\n" << "***\n"
<< "*** You have to ensure that this certificate actually matches the parent\n" << "*** You have to ensure that this certificate actually matches the parent\n"
<< "*** instance's certificate in order to avoid man-in-the-middle attacks.\n" << "*** instance's certificate in order to avoid man-in-the-middle attacks.\n"
<< "***\n\n" << "***\n\n"
<< ConsoleColorTag(Console_Normal); << ConsoleColorTag(Console_Normal);
return PkiUtility::WriteCert(cert, vm["trustedcert"].as<std::string>()); return PkiUtility::WriteCert(cert, vm["trustedcert"].as<std::string>());
} }

View File

@ -38,7 +38,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override; virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;

View File

@ -37,11 +37,11 @@ String PKISignCSRCommand::GetShortDescription(void) const
} }
void PKISignCSRCommand::InitParameters(boost::program_options::options_description& visibleDesc, void PKISignCSRCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("csr", po::value<std::string>(), "CSR file path (input)") ("csr", po::value<std::string>(), "CSR file path (input)")
("cert", po::value<std::string>(), "Certificate file path (output)"); ("cert", po::value<std::string>(), "Certificate file path (output)");
} }
std::vector<String> PKISignCSRCommand::GetArgumentSuggestions(const String& argument, const String& word) const std::vector<String> PKISignCSRCommand::GetArgumentSuggestions(const String& argument, const String& word) const

View File

@ -38,7 +38,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override; virtual std::vector<String> GetArgumentSuggestions(const String& argument, const String& word) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;

View File

@ -39,11 +39,11 @@ String PKITicketCommand::GetShortDescription(void) const
} }
void PKITicketCommand::InitParameters(boost::program_options::options_description& visibleDesc, void PKITicketCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("cn", po::value<std::string>(), "Certificate common name") ("cn", po::value<std::string>(), "Certificate common name")
("salt", po::value<std::string>(), "Ticket salt"); ("salt", po::value<std::string>(), "Ticket salt");
} }
/** /**

View File

@ -38,7 +38,7 @@ public:
virtual String GetDescription(void) const override; virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
}; };

View File

@ -87,20 +87,20 @@ public:
if (sev == LogWarning) { if (sev == LogWarning) {
*m_Stream *m_Stream
<< '\n' << ConsoleColorTag(Console_ForegroundYellow, m_ConsoleType) << std::string(24, '#') << '\n' << '\n' << ConsoleColorTag(Console_ForegroundYellow, m_ConsoleType) << std::string(24, '#') << '\n'
<< ConsoleColorTag(Console_Normal, m_ConsoleType) << str << ConsoleColorTag(Console_Normal, m_ConsoleType) << str
<< ConsoleColorTag(Console_ForegroundYellow, m_ConsoleType) << std::string(24, '#') << "\n\n" << ConsoleColorTag(Console_ForegroundYellow, m_ConsoleType) << std::string(24, '#') << "\n\n"
<< ConsoleColorTag(Console_Normal, m_ConsoleType); << ConsoleColorTag(Console_Normal, m_ConsoleType);
} else if (sev == LogCritical) { } else if (sev == LogCritical) {
*m_Stream *m_Stream
<< '\n' << ConsoleColorTag(Console_ForegroundRed, m_ConsoleType) << std::string(24, '#') << '\n' << '\n' << ConsoleColorTag(Console_ForegroundRed, m_ConsoleType) << std::string(24, '#') << '\n'
<< ConsoleColorTag(Console_Normal, m_ConsoleType) << str << ConsoleColorTag(Console_Normal, m_ConsoleType) << str
<< ConsoleColorTag(Console_ForegroundRed, m_ConsoleType) << std::string(24, '#') << "\n\n" << ConsoleColorTag(Console_ForegroundRed, m_ConsoleType) << std::string(24, '#') << "\n\n"
<< ConsoleColorTag(Console_Normal, m_ConsoleType); << ConsoleColorTag(Console_Normal, m_ConsoleType);
} else } else
*m_Stream *m_Stream
<< ConsoleColorTag(color, m_ConsoleType) << str << ConsoleColorTag(color, m_ConsoleType) << str
<< ConsoleColorTag(Console_Normal, m_ConsoleType); << ConsoleColorTag(Console_Normal, m_ConsoleType);
} }
bool GetStreamHealth(void) const bool GetStreamHealth(void) const
@ -143,23 +143,23 @@ private:
bool TroubleshootCommand::GeneralInfo(InfoLog& log, const boost::program_options::variables_map& vm) bool TroubleshootCommand::GeneralInfo(InfoLog& log, const boost::program_options::variables_map& vm)
{ {
InfoLogLine(log, Console_ForegroundBlue) InfoLogLine(log, Console_ForegroundBlue)
<< std::string(14, '=') << " GENERAL INFORMATION " << std::string(14, '=') << "\n\n"; << std::string(14, '=') << " GENERAL INFORMATION " << std::string(14, '=') << "\n\n";
//Application::DisplayInfoMessage() but formatted //Application::DisplayInfoMessage() but formatted
InfoLogLine(log) InfoLogLine(log)
<< "\tApplication version: " << Application::GetAppVersion() << '\n' << "\tApplication version: " << Application::GetAppVersion() << '\n'
<< "\tInstallation root: " << Application::GetPrefixDir() << '\n' << "\tInstallation root: " << Application::GetPrefixDir() << '\n'
<< "\tSysconf directory: " << Application::GetSysconfDir() << '\n' << "\tSysconf directory: " << Application::GetSysconfDir() << '\n'
<< "\tRun directory: " << Application::GetRunDir() << '\n' << "\tRun directory: " << Application::GetRunDir() << '\n'
<< "\tLocal state directory: " << Application::GetLocalStateDir() << '\n' << "\tLocal state directory: " << Application::GetLocalStateDir() << '\n'
<< "\tPackage data directory: " << Application::GetPkgDataDir() << '\n' << "\tPackage data directory: " << Application::GetPkgDataDir() << '\n'
<< "\tState path: " << Application::GetStatePath() << '\n' << "\tState path: " << Application::GetStatePath() << '\n'
<< "\tObjects path: " << Application::GetObjectsPath() << '\n' << "\tObjects path: " << Application::GetObjectsPath() << '\n'
<< "\tVars path: " << Application::GetVarsPath() << '\n' << "\tVars path: " << Application::GetVarsPath() << '\n'
<< "\tPID path: " << Application::GetPidPath() << '\n'; << "\tPID path: " << Application::GetPidPath() << '\n';
InfoLogLine(log) InfoLogLine(log)
<< '\n'; << '\n';
return true; return true;
} }
@ -174,15 +174,15 @@ bool TroubleshootCommand::FeatureInfo(InfoLog& log, const boost::program_options
bool TroubleshootCommand::ObjectInfo(InfoLog& log, const boost::program_options::variables_map& vm, Dictionary::Ptr& logs, const String& path) bool TroubleshootCommand::ObjectInfo(InfoLog& log, const boost::program_options::variables_map& vm, Dictionary::Ptr& logs, const String& path)
{ {
InfoLogLine(log, Console_ForegroundBlue) InfoLogLine(log, Console_ForegroundBlue)
<< std::string(14, '=') << " OBJECT INFORMATION " << std::string(14, '=') << "\n\n"; << std::string(14, '=') << " OBJECT INFORMATION " << std::string(14, '=') << "\n\n";
String objectfile = Application::GetObjectsPath(); String objectfile = Application::GetObjectsPath();
std::set<String> configs; std::set<String> configs;
if (!Utility::PathExists(objectfile)) { if (!Utility::PathExists(objectfile)) {
InfoLogLine(log, 0, LogCritical) InfoLogLine(log, 0, LogCritical)
<< "Cannot open object file '" << objectfile << "'.\n" << "Cannot open object file '" << objectfile << "'.\n"
<< "FAILED: This probably means you have a fault configuration.\n"; << "FAILED: This probably means you have a fault configuration.\n";
return false; return false;
} else { } else {
InfoLog *OFile = nullptr; InfoLog *OFile = nullptr;
@ -194,12 +194,12 @@ bool TroubleshootCommand::ObjectInfo(InfoLog& log, const boost::program_options:
OFile = new InfoLog(path+"-objects", false); OFile = new InfoLog(path+"-objects", false);
if (!OFile->GetStreamHealth()) { if (!OFile->GetStreamHealth()) {
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "Failed to open Object-write-stream, not printing objects\n\n"; << "Failed to open Object-write-stream, not printing objects\n\n";
delete OFile; delete OFile;
OFile = nullptr; OFile = nullptr;
} else } else
InfoLogLine(log) InfoLogLine(log)
<< "Printing all objects to " << path+"-objects\n"; << "Printing all objects to " << path+"-objects\n";
} }
} }
CheckObjectFile(objectfile, log, OFile, OConsole, logs, configs); CheckObjectFile(objectfile, log, OFile, OConsole, logs, configs);
@ -209,24 +209,24 @@ bool TroubleshootCommand::ObjectInfo(InfoLog& log, const boost::program_options:
if (vm.count("include-vars")) { if (vm.count("include-vars")) {
if (vm.count("console")) { if (vm.count("console")) {
InfoLogLine(log, Console_ForegroundBlue) InfoLogLine(log, Console_ForegroundBlue)
<< "\n[begin: varsfile]\n"; << "\n[begin: varsfile]\n";
if (!PrintVarsFile(path, true)) if (!PrintVarsFile(path, true))
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "Failed to print vars file\n"; << "Failed to print vars file\n";
InfoLogLine(log, Console_ForegroundBlue) InfoLogLine(log, Console_ForegroundBlue)
<< "[end: varsfile]\n"; << "[end: varsfile]\n";
} else { } else {
if (PrintVarsFile(path, false)) if (PrintVarsFile(path, false))
InfoLogLine(log) InfoLogLine(log)
<< "Successfully printed all variables to " << path+"-vars\n"; << "Successfully printed all variables to " << path+"-vars\n";
else else
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "Failed to print vars to " << path+"-vars\n"; << "Failed to print vars to " << path+"-vars\n";
} }
} }
InfoLogLine(log) InfoLogLine(log)
<< '\n'; << '\n';
return true; return true;
} }
@ -234,12 +234,12 @@ bool TroubleshootCommand::ObjectInfo(InfoLog& log, const boost::program_options:
bool TroubleshootCommand::ReportInfo(InfoLog& log, const boost::program_options::variables_map& vm, Dictionary::Ptr& logs) bool TroubleshootCommand::ReportInfo(InfoLog& log, const boost::program_options::variables_map& vm, Dictionary::Ptr& logs)
{ {
InfoLogLine(log, Console_ForegroundBlue) InfoLogLine(log, Console_ForegroundBlue)
<< std::string(14, '=') << " LOGS AND CRASH REPORTS " << std::string(14, '=') << "\n\n"; << std::string(14, '=') << " LOGS AND CRASH REPORTS " << std::string(14, '=') << "\n\n";
PrintLoggers(log, logs); PrintLoggers(log, logs);
PrintCrashReports(log); PrintCrashReports(log);
InfoLogLine(log) InfoLogLine(log)
<< '\n'; << '\n';
return true; return true;
} }
@ -247,26 +247,26 @@ bool TroubleshootCommand::ReportInfo(InfoLog& log, const boost::program_options:
bool TroubleshootCommand::ConfigInfo(InfoLog& log, const boost::program_options::variables_map& vm) bool TroubleshootCommand::ConfigInfo(InfoLog& log, const boost::program_options::variables_map& vm)
{ {
InfoLogLine(log, Console_ForegroundBlue) InfoLogLine(log, Console_ForegroundBlue)
<< std::string(14, '=') << " CONFIGURATION FILES " << std::string(14, '=') << "\n\n"; << std::string(14, '=') << " CONFIGURATION FILES " << std::string(14, '=') << "\n\n";
InfoLogLine(log) InfoLogLine(log)
<< "A collection of important configuration files follows, please make sure to remove any sensitive data such as credentials, internal company names, etc\n"; << "A collection of important configuration files follows, please make sure to remove any sensitive data such as credentials, internal company names, etc\n";
if (!PrintFile(log, Application::GetSysconfDir() + "/icinga2/icinga2.conf")) { if (!PrintFile(log, Application::GetSysconfDir() + "/icinga2/icinga2.conf")) {
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "icinga2.conf not found, therefore skipping validation.\n" << "icinga2.conf not found, therefore skipping validation.\n"
<< "If you are using an icinga2.conf somewhere but the default path please validate it via 'icinga2 daemon -C -c \"path\to/icinga2.conf\"'\n" << "If you are using an icinga2.conf somewhere but the default path please validate it via 'icinga2 daemon -C -c \"path\to/icinga2.conf\"'\n"
<< "and provide it with your support request.\n"; << "and provide it with your support request.\n";
} }
if (!PrintFile(log, Application::GetSysconfDir() + "/icinga2/zones.conf")) { if (!PrintFile(log, Application::GetSysconfDir() + "/icinga2/zones.conf")) {
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "zones.conf not found.\n" << "zones.conf not found.\n"
<< "If you are using a zones.conf somewhere but the default path please provide it with your support request\n"; << "If you are using a zones.conf somewhere but the default path please provide it with your support request\n";
} }
InfoLogLine(log) InfoLogLine(log)
<< '\n'; << '\n';
return true; return true;
} }
@ -292,19 +292,19 @@ int TroubleshootCommand::Tail(const String& file, int numLines, InfoLog& log)
numLines = lines; numLines = lines;
InfoLogLine(log, Console_ForegroundCyan) InfoLogLine(log, Console_ForegroundCyan)
<< "[begin: '" << file << "' line: " << lines-numLines << "]\n"; << "[begin: '" << file << "' line: " << lines-numLines << "]\n";
for (int k = 0; k < numLines; k++) { for (int k = 0; k < numLines; k++) {
InfoLogLine(log, Console_ForegroundCyan) InfoLogLine(log, Console_ForegroundCyan)
<< "# "; << "# ";
InfoLogLine(log) InfoLogLine(log)
<< ringBuf[k] << '\n'; << ringBuf[k] << '\n';
} }
text.close(); text.close();
InfoLogLine(log, Console_ForegroundCyan) InfoLogLine(log, Console_ForegroundCyan)
<< "[end: '" << file << "' line: " << lines << "]\n\n"; << "[end: '" << file << "' line: " << lines << "]\n\n";
return numLines; return numLines;
} }
@ -316,11 +316,11 @@ bool TroubleshootCommand::CheckFeatures(InfoLog& log)
std::vector<String> enabled_features; std::vector<String> enabled_features;
if (!FeatureUtility::GetFeatures(disabled_features, true) || if (!FeatureUtility::GetFeatures(disabled_features, true) ||
!FeatureUtility::GetFeatures(enabled_features, false)) { !FeatureUtility::GetFeatures(enabled_features, false)) {
InfoLogLine(log, 0, LogCritical) InfoLogLine(log, 0, LogCritical)
<< "Failed to collect enabled and/or disabled features. Check\n" << "Failed to collect enabled and/or disabled features. Check\n"
<< FeatureUtility::GetFeaturesAvailablePath() << '\n' << FeatureUtility::GetFeaturesAvailablePath() << '\n'
<< FeatureUtility::GetFeaturesEnabledPath() << '\n'; << FeatureUtility::GetFeaturesEnabledPath() << '\n';
return false; return false;
} }
@ -330,23 +330,23 @@ bool TroubleshootCommand::CheckFeatures(InfoLog& log)
features->Set(feature, true); features->Set(feature, true);
InfoLogLine(log) InfoLogLine(log)
<< "Enabled features:\n"; << "Enabled features:\n";
InfoLogLine(log, Console_ForegroundGreen) InfoLogLine(log, Console_ForegroundGreen)
<< '\t' << boost::algorithm::join(enabled_features, " ") << '\n'; << '\t' << boost::algorithm::join(enabled_features, " ") << '\n';
InfoLogLine(log) InfoLogLine(log)
<< "Disabled features:\n"; << "Disabled features:\n";
InfoLogLine(log, Console_ForegroundRed) InfoLogLine(log, Console_ForegroundRed)
<< '\t' << boost::algorithm::join(disabled_features, " ") << '\n'; << '\t' << boost::algorithm::join(disabled_features, " ") << '\n';
if (!features->Get("checker").ToBool()) if (!features->Get("checker").ToBool())
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "checker is disabled, no checks can be run from this instance\n"; << "checker is disabled, no checks can be run from this instance\n";
if (!features->Get("mainlog").ToBool()) if (!features->Get("mainlog").ToBool())
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "mainlog is disabled, please activate it and rerun icinga2\n"; << "mainlog is disabled, please activate it and rerun icinga2\n";
if (!features->Get("debuglog").ToBool()) if (!features->Get("debuglog").ToBool())
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "debuglog is disabled, please activate it and rerun icinga2\n"; << "debuglog is disabled, please activate it and rerun icinga2\n";
return true; return true;
} }
@ -376,27 +376,27 @@ bool TroubleshootCommand::PrintCrashReports(InfoLog& log)
try { try {
Utility::Glob(spath, std::bind(&GetLatestReport, _1, std::ref(bestTimestamp), Utility::Glob(spath, std::bind(&GetLatestReport, _1, std::ref(bestTimestamp),
std::ref(bestFilename)), GlobFile); std::ref(bestFilename)), GlobFile);
} }
#ifdef _WIN32 #ifdef _WIN32
catch (win32_error &ex) { catch (win32_error &ex) {
if (int const * err = boost::get_error_info<errinfo_win32_error>(ex)) { if (int const * err = boost::get_error_info<errinfo_win32_error>(ex)) {
if (*err != 3) {//Error code for path does not exist if (*err != 3) {//Error code for path does not exist
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< Application::GetLocalStateDir() << "/log/icinga2/crash/ does not exist\n"; << Application::GetLocalStateDir() << "/log/icinga2/crash/ does not exist\n";
return false; return false;
} }
} }
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "Error printing crash reports\n"; << "Error printing crash reports\n";
return false; return false;
} }
#else #else
catch (...) { catch (...) {
InfoLogLine(log, 0, LogWarning) << "Error printing crash reports.\n" InfoLogLine(log, 0, LogWarning) << "Error printing crash reports.\n"
<< "Does " << Application::GetLocalStateDir() << "/log/icinga2/crash/ exist?\n"; << "Does " << Application::GetLocalStateDir() << "/log/icinga2/crash/ exist?\n";
return false; return false;
} }
@ -404,14 +404,14 @@ bool TroubleshootCommand::PrintCrashReports(InfoLog& log)
if (!bestTimestamp) if (!bestTimestamp)
InfoLogLine(log, Console_ForegroundYellow) InfoLogLine(log, Console_ForegroundYellow)
<< "No crash logs found in " << Application::GetLocalStateDir().CStr() << "/log/icinga2/crash/\n\n"; << "No crash logs found in " << Application::GetLocalStateDir().CStr() << "/log/icinga2/crash/\n\n";
else { else {
InfoLogLine(log) InfoLogLine(log)
<< "Latest crash report is from " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", Utility::GetTime()) << '\n' << "Latest crash report is from " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", Utility::GetTime()) << '\n'
<< "File: " << bestFilename << "\n\n"; << "File: " << bestFilename << "\n\n";
PrintFile(log, bestFilename); PrintFile(log, bestFilename);
InfoLogLine(log) InfoLogLine(log)
<< '\n'; << '\n';
} }
return true; return true;
@ -427,17 +427,17 @@ bool TroubleshootCommand::PrintFile(InfoLog& log, const String& path)
std::string line; std::string line;
InfoLogLine(log, Console_ForegroundCyan) InfoLogLine(log, Console_ForegroundCyan)
<< "[begin: '" << path << "']\n"; << "[begin: '" << path << "']\n";
while (std::getline(text, line)) { while (std::getline(text, line)) {
InfoLogLine(log, Console_ForegroundCyan) InfoLogLine(log, Console_ForegroundCyan)
<< "# "; << "# ";
InfoLogLine(log) InfoLogLine(log)
<< line << '\n'; << line << '\n';
} }
InfoLogLine(log, Console_ForegroundCyan) InfoLogLine(log, Console_ForegroundCyan)
<< "[end: '" << path << "']\n"; << "[end: '" << path << "']\n";
return true; return true;
} }
@ -449,17 +449,17 @@ bool TroubleshootCommand::CheckConfig(void)
//print is supposed allow the user to print the object file //print is supposed allow the user to print the object file
void TroubleshootCommand::CheckObjectFile(const String& objectfile, InfoLog& log, InfoLog *OFile, const bool objectConsole, void TroubleshootCommand::CheckObjectFile(const String& objectfile, InfoLog& log, InfoLog *OFile, const bool objectConsole,
Dictionary::Ptr& logs, std::set<String>& configs) Dictionary::Ptr& logs, std::set<String>& configs)
{ {
InfoLogLine(log) InfoLogLine(log)
<< "Checking object file from " << objectfile << '\n'; << "Checking object file from " << objectfile << '\n';
std::fstream fp; std::fstream fp;
fp.open(objectfile.CStr(), std::ios_base::in); fp.open(objectfile.CStr(), std::ios_base::in);
if (!fp.is_open()) { if (!fp.is_open()) {
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "Could not open object file.\n"; << "Could not open object file.\n";
return; return;
} }
@ -489,7 +489,7 @@ void TroubleshootCommand::CheckObjectFile(const String& objectfile, InfoLog& log
ObjectListUtility::PrintObject(sStream, first, message, type_count, "", ""); ObjectListUtility::PrintObject(sStream, first, message, type_count, "", "");
if (OFile) { if (OFile) {
InfoLogLine(*OFile) InfoLogLine(*OFile)
<< sStream.str(); << sStream.str();
sStream.flush(); sStream.flush();
} }
} }
@ -527,23 +527,23 @@ void TroubleshootCommand::CheckObjectFile(const String& objectfile, InfoLog& log
if (!countTotal) { if (!countTotal) {
InfoLogLine(log, 0, LogCritical) InfoLogLine(log, 0, LogCritical)
<< "No objects found in objectfile.\n"; << "No objects found in objectfile.\n";
return; return;
} }
//Print objects with count //Print objects with count
InfoLogLine(log) InfoLogLine(log)
<< "Found the " << countTotal << " objects:\n" << "Found the " << countTotal << " objects:\n"
<< " Type" << std::string(typeL-4, ' ') << " : Count\n"; << " Type" << std::string(typeL-4, ' ') << " : Count\n";
for (const Dictionary::Pair& kv : type_count) { for (const Dictionary::Pair& kv : type_count) {
InfoLogLine(log) InfoLogLine(log)
<< " " << kv.first << std::string(typeL - kv.first.GetLength(), ' ') << " " << kv.first << std::string(typeL - kv.first.GetLength(), ' ')
<< " : " << kv.second << '\n'; << " : " << kv.second << '\n';
} }
InfoLogLine(log) InfoLogLine(log)
<< '\n'; << '\n';
TroubleshootCommand::PrintObjectOrigin(log, configs); TroubleshootCommand::PrintObjectOrigin(log, configs);
} }
@ -567,19 +567,19 @@ void TroubleshootCommand::PrintLoggers(InfoLog& log, Dictionary::Ptr& logs)
{ {
if (!logs->GetLength()) { if (!logs->GetLength()) {
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< "No loggers found, check whether you enabled any logging features\n"; << "No loggers found, check whether you enabled any logging features\n";
} else { } else {
InfoLogLine(log) InfoLogLine(log)
<< "Getting the last 20 lines of " << logs->GetLength() << " FileLogger objects.\n"; << "Getting the last 20 lines of " << logs->GetLength() << " FileLogger objects.\n";
ObjectLock ulock(logs); ObjectLock ulock(logs);
for (const Dictionary::Pair& kv : logs) { for (const Dictionary::Pair& kv : logs) {
InfoLogLine(log) InfoLogLine(log)
<< "Logger " << kv.first << " at path: " << kv.second << '\n'; << "Logger " << kv.first << " at path: " << kv.second << '\n';
if (!Tail(kv.second, 20, log)) { if (!Tail(kv.second, 20, log)) {
InfoLogLine(log, 0, LogWarning) InfoLogLine(log, 0, LogWarning)
<< kv.second << " either does not exist or is empty\n"; << kv.second << " either does not exist or is empty\n";
} }
} }
} }
@ -588,16 +588,16 @@ void TroubleshootCommand::PrintLoggers(InfoLog& log, Dictionary::Ptr& logs)
void TroubleshootCommand::PrintObjectOrigin(InfoLog& log, const std::set<String>& configSet) void TroubleshootCommand::PrintObjectOrigin(InfoLog& log, const std::set<String>& configSet)
{ {
InfoLogLine(log) InfoLogLine(log)
<< "The objects origins are:\n"; << "The objects origins are:\n";
for (const String& config : configSet) { for (const String& config : configSet) {
InfoLogLine(log) InfoLogLine(log)
<< " " << config << '\n'; << " " << config << '\n';
} }
} }
void TroubleshootCommand::InitParameters(boost::program_options::options_description& visibleDesc, void TroubleshootCommand::InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const boost::program_options::options_description& hiddenDesc) const
{ {
visibleDesc.add_options() visibleDesc.add_options()
("console,c", "print to console instead of file") ("console,c", "print to console instead of file")
@ -611,10 +611,10 @@ int TroubleshootCommand::Run(const boost::program_options::variables_map& vm, co
{ {
#ifdef _WIN32 //Dislikes ':' in filenames #ifdef _WIN32 //Dislikes ':' in filenames
String path = Application::GetLocalStateDir() + "/log/icinga2/troubleshooting-" String path = Application::GetLocalStateDir() + "/log/icinga2/troubleshooting-"
+ Utility::FormatDateTime("%Y-%m-%d_%H-%M-%S", Utility::GetTime()) + ".log"; + Utility::FormatDateTime("%Y-%m-%d_%H-%M-%S", Utility::GetTime()) + ".log";
#else #else
String path = Application::GetLocalStateDir() + "/log/icinga2/troubleshooting-" String path = Application::GetLocalStateDir() + "/log/icinga2/troubleshooting-"
+ Utility::FormatDateTime("%Y-%m-%d_%H:%M:%S", Utility::GetTime()) + ".log"; + Utility::FormatDateTime("%Y-%m-%d_%H:%M:%S", Utility::GetTime()) + ".log";
#endif /*_WIN32*/ #endif /*_WIN32*/
InfoLog *log; InfoLog *log;
@ -638,12 +638,12 @@ int TroubleshootCommand::Run(const boost::program_options::variables_map& vm, co
double goTime = Utility::GetTime(); double goTime = Utility::GetTime();
InfoLogLine(*log) InfoLogLine(*log)
<< appName << " -- Troubleshooting help:\n" << appName << " -- Troubleshooting help:\n"
<< "Should you run into problems with Icinga please add this file to your help request\n" << "Should you run into problems with Icinga please add this file to your help request\n"
<< "Started collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", goTime) << "\n"; << "Started collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", goTime) << "\n";
InfoLogLine(*log, Console_ForegroundMagenta) InfoLogLine(*log, Console_ForegroundMagenta)
<< std::string(52, '=') << "\n\n"; << std::string(52, '=') << "\n\n";
if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-") if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
appName = appName.SubStr(3, appName.GetLength() - 3); appName = appName.SubStr(3, appName.GetLength() - 3);
@ -651,12 +651,12 @@ int TroubleshootCommand::Run(const boost::program_options::variables_map& vm, co
Dictionary::Ptr logs = new Dictionary; Dictionary::Ptr logs = new Dictionary;
if (!GeneralInfo(*log, vm) || if (!GeneralInfo(*log, vm) ||
!FeatureInfo(*log, vm) || !FeatureInfo(*log, vm) ||
!ObjectInfo(*log, vm, logs, path) || !ObjectInfo(*log, vm, logs, path) ||
!ReportInfo(*log, vm, logs) || !ReportInfo(*log, vm, logs) ||
!ConfigInfo(*log, vm)) { !ConfigInfo(*log, vm)) {
InfoLogLine(*log, 0, LogCritical) InfoLogLine(*log, 0, LogCritical)
<< "Could not recover from critical failure, exiting.\n"; << "Could not recover from critical failure, exiting.\n";
delete log; delete log;
return 3; return 3;
@ -665,15 +665,15 @@ int TroubleshootCommand::Run(const boost::program_options::variables_map& vm, co
double endTime = Utility::GetTime(); double endTime = Utility::GetTime();
InfoLogLine(*log, Console_ForegroundMagenta) InfoLogLine(*log, Console_ForegroundMagenta)
<< std::string(52, '=') << '\n'; << std::string(52, '=') << '\n';
InfoLogLine(*log, Console_ForegroundGreen) InfoLogLine(*log, Console_ForegroundGreen)
<< "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime) << "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime)
<< "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n"; << "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n";
if (!vm.count("console")) { if (!vm.count("console")) {
std::cout << "Started collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", goTime) << "\n" std::cout << "Started collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", goTime) << "\n"
<< "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime) << "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime)
<< "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n\n"; << "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n\n";
std::cout << "General log file: '" << path << "'\n"; std::cout << "General log file: '" << path << "'\n";
@ -683,7 +683,7 @@ int TroubleshootCommand::Run(const boost::program_options::variables_map& vm, co
std::cout << "Objects log file: '" << path << "-objects'\n"; std::cout << "Objects log file: '" << path << "-objects'\n";
std::cout << "\nPlease compress the files before uploading them,, for example:\n" std::cout << "\nPlease compress the files before uploading them,, for example:\n"
<< " # tar czf troubleshoot.tar.gz " << path << "*\n"; << " # tar czf troubleshoot.tar.gz " << path << "*\n";
} }
delete log; delete log;

View File

@ -41,7 +41,7 @@ public:
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
virtual void InitParameters(boost::program_options::options_description& visibleDesc, virtual void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
private: private:
class InfoLog; class InfoLog;
@ -49,9 +49,9 @@ private:
static bool GeneralInfo(InfoLog& log, const boost::program_options::variables_map& vm); static bool GeneralInfo(InfoLog& log, const boost::program_options::variables_map& vm);
static bool FeatureInfo(InfoLog& log, const boost::program_options::variables_map& vm); static bool FeatureInfo(InfoLog& log, const boost::program_options::variables_map& vm);
static bool ObjectInfo(InfoLog& log, const boost::program_options::variables_map& vm, static bool ObjectInfo(InfoLog& log, const boost::program_options::variables_map& vm,
Dictionary::Ptr& logs, const String& path); Dictionary::Ptr& logs, const String& path);
static bool ReportInfo(InfoLog& log, const boost::program_options::variables_map& vm, static bool ReportInfo(InfoLog& log, const boost::program_options::variables_map& vm,
Dictionary::Ptr& logs); Dictionary::Ptr& logs);
static bool ConfigInfo(InfoLog& log, const boost::program_options::variables_map& vm); static bool ConfigInfo(InfoLog& log, const boost::program_options::variables_map& vm);
static int Tail(const String& file, const int numLines, InfoLog& log); static int Tail(const String& file, const int numLines, InfoLog& log);
@ -61,7 +61,7 @@ private:
static bool PrintFile(InfoLog& log, const String& path); static bool PrintFile(InfoLog& log, const String& path);
static bool CheckConfig(void); static bool CheckConfig(void);
static void CheckObjectFile(const String& objectfile, InfoLog& log, InfoLog *OFile, const bool objectConsole, static void CheckObjectFile(const String& objectfile, InfoLog& log, InfoLog *OFile, const bool objectConsole,
Dictionary::Ptr& logs, std::set<String>& configs); Dictionary::Ptr& logs, std::set<String>& configs);
static bool PrintVarsFile(const String& path, const bool console); static bool PrintVarsFile(const String& path, const bool console);
static void PrintLoggers(InfoLog& log, Dictionary::Ptr& logs); static void PrintLoggers(InfoLog& log, Dictionary::Ptr& logs);
static void PrintObjectOrigin(InfoLog& log, const std::set<String>& configSet); static void PrintObjectOrigin(InfoLog& log, const std::set<String>& configSet);

View File

@ -42,7 +42,7 @@ public:
virtual String GetShortDescription(void) const override; virtual String GetShortDescription(void) const override;
virtual int GetMinArguments(void) const override; virtual int GetMinArguments(void) const override;
void InitParameters(boost::program_options::options_description& visibleDesc, void InitParameters(boost::program_options::options_description& visibleDesc,
boost::program_options::options_description& hiddenDesc) const override; boost::program_options::options_description& hiddenDesc) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override; virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
}; };

View File

@ -57,7 +57,7 @@ int VariableListCommand::Run(const boost::program_options::variables_map& vm, co
if (!Utility::PathExists(varsfile)) { if (!Utility::PathExists(varsfile)) {
Log(LogCritical, "cli") Log(LogCritical, "cli")
<< "Cannot open variables file '" << varsfile << "'."; << "Cannot open variables file '" << varsfile << "'.";
Log(LogCritical, "cli", "Run 'icinga2 daemon -C' to validate config and generate the cache file."); Log(LogCritical, "cli", "Run 'icinga2 daemon -C' to validate config and generate the cache file.");
return 1; return 1;
} }

View File

@ -89,5 +89,5 @@ void VariableUtility::PrintVariables(std::ostream& outfp)
fp.close(); fp.close();
Log(LogNotice, "cli") Log(LogNotice, "cli")
<< "Parsed " << variables_count << " variables."; << "Parsed " << variables_count << " variables.";
} }

View File

@ -59,7 +59,7 @@ void CheckResultReader::Start(bool runtimeCreated)
ObjectImpl<CheckResultReader>::Start(runtimeCreated); ObjectImpl<CheckResultReader>::Start(runtimeCreated);
Log(LogInformation, "CheckResultReader") Log(LogInformation, "CheckResultReader")
<< "'" << GetName() << "' started."; << "'" << GetName() << "' started.";
#ifndef _WIN32 #ifndef _WIN32
m_ReadTimer = new Timer(); m_ReadTimer = new Timer();
@ -75,7 +75,7 @@ void CheckResultReader::Start(bool runtimeCreated)
void CheckResultReader::Stop(bool runtimeRemoved) void CheckResultReader::Stop(bool runtimeRemoved)
{ {
Log(LogInformation, "CheckResultReader") Log(LogInformation, "CheckResultReader")
<< "'" << GetName() << "' stopped."; << "'" << GetName() << "' stopped.";
ObjectImpl<CheckResultReader>::Stop(runtimeRemoved); ObjectImpl<CheckResultReader>::Stop(runtimeRemoved);
} }
@ -123,15 +123,15 @@ void CheckResultReader::ProcessCheckResultFile(const String& path) const
/* Remove the checkresult files. */ /* Remove the checkresult files. */
if (unlink(path.CStr()) < 0) if (unlink(path.CStr()) < 0)
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("unlink") << boost::errinfo_api_function("unlink")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
if (unlink(crfile.CStr()) < 0) if (unlink(crfile.CStr()) < 0)
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("unlink") << boost::errinfo_api_function("unlink")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(crfile)); << boost::errinfo_file_name(crfile));
Checkable::Ptr checkable; Checkable::Ptr checkable;
@ -139,7 +139,7 @@ void CheckResultReader::ProcessCheckResultFile(const String& path) const
if (!host) { if (!host) {
Log(LogWarning, "CheckResultReader") Log(LogWarning, "CheckResultReader")
<< "Ignoring checkresult file for host '" << attrs["host_name"] << "': Host does not exist."; << "Ignoring checkresult file for host '" << attrs["host_name"] << "': Host does not exist.";
return; return;
} }
@ -149,8 +149,8 @@ void CheckResultReader::ProcessCheckResultFile(const String& path) const
if (!service) { if (!service) {
Log(LogWarning, "CheckResultReader") Log(LogWarning, "CheckResultReader")
<< "Ignoring checkresult file for host '" << attrs["host_name"] << "Ignoring checkresult file for host '" << attrs["host_name"]
<< "', service '" << attrs["service_description"] << "': Service does not exist."; << "', service '" << attrs["service_description"] << "': Service does not exist.";
return; return;
} }
@ -179,7 +179,7 @@ void CheckResultReader::ProcessCheckResultFile(const String& path) const
checkable->ProcessCheckResult(result); checkable->ProcessCheckResult(result);
Log(LogDebug, "CheckResultReader") Log(LogDebug, "CheckResultReader")
<< "Processed checkresult file for object '" << checkable->GetName() << "'"; << "Processed checkresult file for object '" << checkable->GetName() << "'";
/* Reschedule the next check. The side effect of this is that for as long /* Reschedule the next check. The side effect of this is that for as long
* as we receive check result files for a host/service we won't execute any * as we receive check result files for a host/service we won't execute any

View File

@ -61,7 +61,7 @@ void CompatLogger::Start(bool runtimeCreated)
ObjectImpl<CompatLogger>::Start(runtimeCreated); ObjectImpl<CompatLogger>::Start(runtimeCreated);
Log(LogInformation, "CompatLogger") Log(LogInformation, "CompatLogger")
<< "'" << GetName() << "' started."; << "'" << GetName() << "' started.";
Checkable::OnNewCheckResult.connect(std::bind(&CompatLogger::CheckResultHandler, this, _1, _2)); Checkable::OnNewCheckResult.connect(std::bind(&CompatLogger::CheckResultHandler, this, _1, _2));
Checkable::OnNotificationSentToUser.connect(std::bind(&CompatLogger::NotificationSentHandler, this, _1, _2, _3, _4, _5, _6, _7, _8)); Checkable::OnNotificationSentToUser.connect(std::bind(&CompatLogger::NotificationSentHandler, this, _1, _2, _3, _4, _5, _6, _7, _8));
@ -88,7 +88,7 @@ void CompatLogger::Start(bool runtimeCreated)
void CompatLogger::Stop(bool runtimeRemoved) void CompatLogger::Stop(bool runtimeRemoved)
{ {
Log(LogInformation, "CompatLogger") Log(LogInformation, "CompatLogger")
<< "'" << GetName() << "' stopped."; << "'" << GetName() << "' stopped.";
ObjectImpl<CompatLogger>::Stop(runtimeRemoved); ObjectImpl<CompatLogger>::Stop(runtimeRemoved);
} }
@ -118,7 +118,7 @@ void CompatLogger::CheckResultHandler(const Checkable::Ptr& checkable, const Che
bool reachable_before = vars_before->Get("reachable"); bool reachable_before = vars_before->Get("reachable");
if (state_before == state_after && stateType_before == stateType_after && if (state_before == state_after && stateType_before == stateType_after &&
attempt_before == attempt_after && reachable_before == reachable_after) attempt_before == attempt_after && reachable_before == reachable_after)
return; /* Nothing changed, ignore this checkresult. */ return; /* Nothing changed, ignore this checkresult. */
} }
@ -130,23 +130,23 @@ void CompatLogger::CheckResultHandler(const Checkable::Ptr& checkable, const Che
if (service) { if (service) {
msgbuf << "SERVICE ALERT: " msgbuf << "SERVICE ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< service->GetShortName() << ";" << service->GetShortName() << ";"
<< Service::StateToString(service->GetState()) << ";" << Service::StateToString(service->GetState()) << ";"
<< Service::StateTypeToString(service->GetStateType()) << ";" << Service::StateTypeToString(service->GetStateType()) << ";"
<< attempt_after << ";" << attempt_after << ";"
<< output << "" << output << ""
<< ""; << "";
} else { } else {
String state = Host::StateToString(Host::CalculateState(static_cast<ServiceState>(state_after))); String state = Host::StateToString(Host::CalculateState(static_cast<ServiceState>(state_after)));
msgbuf << "HOST ALERT: " msgbuf << "HOST ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< CompatUtility::GetHostStateString(host) << ";" << CompatUtility::GetHostStateString(host) << ";"
<< Host::StateTypeToString(host->GetStateType()) << ";" << Host::StateTypeToString(host->GetStateType()) << ";"
<< attempt_after << ";" << attempt_after << ";"
<< output << "" << output << ""
<< ""; << "";
} }
@ -244,8 +244,8 @@ void CompatLogger::RemoveDowntimeHandler(const Downtime::Ptr& downtime)
* @threadsafety Always. * @threadsafety Always.
*/ */
void CompatLogger::NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable, void CompatLogger::NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr, const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr,
const String& author, const String& comment_text, const String& command_name) const String& author, const String& comment_text, const String& command_name)
{ {
Host::Ptr host; Host::Ptr host;
Service::Ptr service; Service::Ptr service;
@ -471,7 +471,7 @@ void CompatLogger::ReopenFile(bool rotate)
String archiveFile = GetLogDir() + "/archives/icinga-" + Utility::FormatDateTime("%m-%d-%Y-%H", Utility::GetTime()) + ".log"; String archiveFile = GetLogDir() + "/archives/icinga-" + Utility::FormatDateTime("%m-%d-%Y-%H", Utility::GetTime()) + ".log";
Log(LogNotice, "CompatLogger") Log(LogNotice, "CompatLogger")
<< "Rotating compat log file '" << tempFile << "' -> '" << archiveFile << "'"; << "Rotating compat log file '" << tempFile << "' -> '" << archiveFile << "'";
(void) rename(tempFile.CStr(), archiveFile.CStr()); (void) rename(tempFile.CStr(), archiveFile.CStr());
} }
@ -481,7 +481,7 @@ void CompatLogger::ReopenFile(bool rotate)
if (!m_OutputFile) { if (!m_OutputFile) {
Log(LogWarning, "CompatLogger") Log(LogWarning, "CompatLogger")
<< "Could not open compat log file '" << tempFile << "' for writing. Log output will be lost."; << "Could not open compat log file '" << tempFile << "' for writing. Log output will be lost.";
return; return;
} }
@ -498,11 +498,11 @@ void CompatLogger::ReopenFile(bool rotate)
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "CURRENT HOST STATE: " msgbuf << "CURRENT HOST STATE: "
<< host->GetName() << ";" << host->GetName() << ";"
<< CompatUtility::GetHostStateString(host) << ";" << CompatUtility::GetHostStateString(host) << ";"
<< Host::StateTypeToString(host->GetStateType()) << ";" << Host::StateTypeToString(host->GetStateType()) << ";"
<< host->GetCheckAttempt() << ";" << host->GetCheckAttempt() << ";"
<< output << ""; << output << "";
WriteLine(msgbuf.str()); WriteLine(msgbuf.str());
} }
@ -518,12 +518,12 @@ void CompatLogger::ReopenFile(bool rotate)
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "CURRENT SERVICE STATE: " msgbuf << "CURRENT SERVICE STATE: "
<< host->GetName() << ";" << host->GetName() << ";"
<< service->GetShortName() << ";" << service->GetShortName() << ";"
<< Service::StateToString(service->GetState()) << ";" << Service::StateToString(service->GetState()) << ";"
<< Service::StateTypeToString(service->GetStateType()) << ";" << Service::StateTypeToString(service->GetStateType()) << ";"
<< service->GetCheckAttempt() << ";" << service->GetCheckAttempt() << ";"
<< output << ""; << output << "";
WriteLine(msgbuf.str()); WriteLine(msgbuf.str());
} }
@ -543,16 +543,16 @@ void CompatLogger::ScheduleNextRotation(void)
if (!temp) { if (!temp) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("localtime") << boost::errinfo_api_function("localtime")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
tmthen = *temp; tmthen = *temp;
#else /* _MSC_VER */ #else /* _MSC_VER */
if (!localtime_r(&now, &tmthen)) { if (!localtime_r(&now, &tmthen)) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("localtime_r") << boost::errinfo_api_function("localtime_r")
<< boost::errinfo_errno(errno)); << boost::errinfo_errno(errno));
} }
#endif /* _MSC_VER */ #endif /* _MSC_VER */
@ -576,8 +576,8 @@ void CompatLogger::ScheduleNextRotation(void)
time_t ts = mktime(&tmthen); time_t ts = mktime(&tmthen);
Log(LogNotice, "CompatLogger") Log(LogNotice, "CompatLogger")
<< "Rescheduling rotation timer for compat log '" << "Rescheduling rotation timer for compat log '"
<< GetName() << "' to '" << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S %z", ts) << "'"; << GetName() << "' to '" << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S %z", ts) << "'";
m_RotationTimer->Reschedule(ts); m_RotationTimer->Reschedule(ts);
} }
@ -603,7 +603,7 @@ void CompatLogger::ValidateRotationMethod(const String& value, const ValidationU
ObjectImpl<CompatLogger>::ValidateRotationMethod(value, utils); ObjectImpl<CompatLogger>::ValidateRotationMethod(value, utils);
if (value != "HOURLY" && value != "DAILY" && if (value != "HOURLY" && value != "DAILY" &&
value != "WEEKLY" && value != "MONTHLY" && value != "NONE") { value != "WEEKLY" && value != "MONTHLY" && value != "NONE") {
BOOST_THROW_EXCEPTION(ValidationError(this, { "rotation_method" }, "Rotation method '" + value + "' is invalid.")); BOOST_THROW_EXCEPTION(ValidationError(this, { "rotation_method" }, "Rotation method '" + value + "' is invalid."));
} }
} }

View File

@ -53,8 +53,8 @@ private:
void CheckResultHandler(const Checkable::Ptr& service, const CheckResult::Ptr& cr); void CheckResultHandler(const Checkable::Ptr& service, const CheckResult::Ptr& cr);
void NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& service, void NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& service,
const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr, const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr,
const String& author, const String& comment_text, const String& command_name); const String& author, const String& comment_text, const String& command_name);
void FlappingChangedHandler(const Checkable::Ptr& checkable); void FlappingChangedHandler(const Checkable::Ptr& checkable);
void EnableFlappingChangedHandler(const Checkable::Ptr& checkable); void EnableFlappingChangedHandler(const Checkable::Ptr& checkable);
void TriggerDowntimeHandler(const Downtime::Ptr& downtime); void TriggerDowntimeHandler(const Downtime::Ptr& downtime);

View File

@ -51,7 +51,7 @@ void ExternalCommandListener::Start(bool runtimeCreated)
ObjectImpl<ExternalCommandListener>::Start(runtimeCreated); ObjectImpl<ExternalCommandListener>::Start(runtimeCreated);
Log(LogInformation, "ExternalCommandListener") Log(LogInformation, "ExternalCommandListener")
<< "'" << GetName() << "' started."; << "'" << GetName() << "' started.";
#ifndef _WIN32 #ifndef _WIN32
m_CommandThread = std::thread(std::bind(&ExternalCommandListener::CommandPipeThread, this, GetCommandPath())); m_CommandThread = std::thread(std::bind(&ExternalCommandListener::CommandPipeThread, this, GetCommandPath()));
@ -65,7 +65,7 @@ void ExternalCommandListener::Start(bool runtimeCreated)
void ExternalCommandListener::Stop(bool runtimeRemoved) void ExternalCommandListener::Stop(bool runtimeRemoved)
{ {
Log(LogInformation, "ExternalCommandListener") Log(LogInformation, "ExternalCommandListener")
<< "'" << GetName() << "' stopped."; << "'" << GetName() << "' stopped.";
ObjectImpl<ExternalCommandListener>::Stop(runtimeRemoved); ObjectImpl<ExternalCommandListener>::Stop(runtimeRemoved);
} }
@ -84,9 +84,9 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath)
} else { } else {
if (unlink(commandPath.CStr()) < 0) { if (unlink(commandPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("unlink") << boost::errinfo_api_function("unlink")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(commandPath)); << boost::errinfo_file_name(commandPath));
} }
} }
} }
@ -95,7 +95,7 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath)
if (!fifo_ok && mkfifo(commandPath.CStr(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0) { if (!fifo_ok && mkfifo(commandPath.CStr(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0) {
Log(LogCritical, "ExternalCommandListener") Log(LogCritical, "ExternalCommandListener")
<< "mkfifo() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "mkfifo() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return; return;
} }
@ -103,7 +103,7 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath)
* fifo to get the right mask. */ * fifo to get the right mask. */
if (chmod(commandPath.CStr(), mode) < 0) { if (chmod(commandPath.CStr(), mode) < 0) {
Log(LogCritical, "ExternalCommandListener") Log(LogCritical, "ExternalCommandListener")
<< "chmod() on fifo '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "chmod() on fifo '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return; return;
} }
@ -112,7 +112,7 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath)
if (fd < 0) { if (fd < 0) {
Log(LogCritical, "ExternalCommandListener") Log(LogCritical, "ExternalCommandListener")
<< "open() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; << "open() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return; return;
} }
@ -134,7 +134,7 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath)
continue; continue;
Log(LogWarning, "ExternalCommandListener") Log(LogWarning, "ExternalCommandListener")
<< "Cannot read from command pipe." << DiagnosticInformation(ex); << "Cannot read from command pipe." << DiagnosticInformation(ex);
break; break;
} }
@ -153,14 +153,14 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath)
try { try {
Log(LogInformation, "ExternalCommandListener") Log(LogInformation, "ExternalCommandListener")
<< "Executing external command: " << command; << "Executing external command: " << command;
ExternalCommandProcessor::Execute(command); ExternalCommandProcessor::Execute(command);
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogWarning, "ExternalCommandListener") Log(LogWarning, "ExternalCommandListener")
<< "External command failed: " << DiagnosticInformation(ex, false); << "External command failed: " << DiagnosticInformation(ex, false);
Log(LogNotice, "ExternalCommandListener") Log(LogNotice, "ExternalCommandListener")
<< "External command failed: " << DiagnosticInformation(ex, true); << "External command failed: " << DiagnosticInformation(ex, true);
} }
} }
} }

View File

@ -74,7 +74,7 @@ void StatusDataWriter::Start(bool runtimeCreated)
ObjectImpl<StatusDataWriter>::Start(runtimeCreated); ObjectImpl<StatusDataWriter>::Start(runtimeCreated);
Log(LogInformation, "StatusDataWriter") Log(LogInformation, "StatusDataWriter")
<< "'" << GetName() << "' started."; << "'" << GetName() << "' started.";
m_ObjectsCacheOutdated = true; m_ObjectsCacheOutdated = true;
@ -94,7 +94,7 @@ void StatusDataWriter::Start(bool runtimeCreated)
void StatusDataWriter::Stop(bool runtimeRemoved) void StatusDataWriter::Stop(bool runtimeRemoved)
{ {
Log(LogInformation, "StatusDataWriter") Log(LogInformation, "StatusDataWriter")
<< "'" << GetName() << "' stopped."; << "'" << GetName() << "' stopped.";
ObjectImpl<StatusDataWriter>::Stop(runtimeRemoved); ObjectImpl<StatusDataWriter>::Stop(runtimeRemoved);
} }
@ -111,29 +111,29 @@ void StatusDataWriter::DumpComments(std::ostream& fp, const Checkable::Ptr& chec
if (service) if (service)
fp << "servicecomment {" << "\n" fp << "servicecomment {" << "\n"
<< "\t" << "service_description=" << service->GetShortName() << "\n"; << "\t" << "service_description=" << service->GetShortName() << "\n";
else else
fp << "hostcomment {" << "\n"; fp << "hostcomment {" << "\n";
fp << "\t" "host_name=" << host->GetName() << "\n" fp << "\t" "host_name=" << host->GetName() << "\n"
"\t" "comment_id=" << comment->GetLegacyId() << "\n" "\t" "comment_id=" << comment->GetLegacyId() << "\n"
"\t" "entry_time=" << comment->GetEntryTime() << "\n" "\t" "entry_time=" << comment->GetEntryTime() << "\n"
"\t" "entry_type=" << comment->GetEntryType() << "\n" "\t" "entry_type=" << comment->GetEntryType() << "\n"
"\t" "persistent=" "1" "\n" "\t" "persistent=" "1" "\n"
"\t" "author=" << comment->GetAuthor() << "\n" "\t" "author=" << comment->GetAuthor() << "\n"
"\t" "comment_data=" << comment->GetText() << "\n" "\t" "comment_data=" << comment->GetText() << "\n"
"\t" "expires=" << (comment->GetExpireTime() != 0 ? 1 : 0) << "\n" "\t" "expires=" << (comment->GetExpireTime() != 0 ? 1 : 0) << "\n"
"\t" "expire_time=" << comment->GetExpireTime() << "\n" "\t" "expire_time=" << comment->GetExpireTime() << "\n"
"\t" "}" "\n" "\t" "}" "\n"
"\n"; "\n";
} }
} }
void StatusDataWriter::DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& tp) void StatusDataWriter::DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& tp)
{ {
fp << "define timeperiod {" "\n" fp << "define timeperiod {" "\n"
"\t" "timeperiod_name" "\t" << tp->GetName() << "\n" "\t" "timeperiod_name" "\t" << tp->GetName() << "\n"
"\t" "alias" "\t" << tp->GetName() << "\n"; "\t" "alias" "\t" << tp->GetName() << "\n";
Dictionary::Ptr ranges = tp->GetRanges(); Dictionary::Ptr ranges = tp->GetRanges();
@ -144,14 +144,13 @@ void StatusDataWriter::DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& t
} }
} }
fp << "\t" "}" "\n" fp << "\t" "}" "\n" "\n";
"\n";
} }
void StatusDataWriter::DumpCommand(std::ostream& fp, const Command::Ptr& command) void StatusDataWriter::DumpCommand(std::ostream& fp, const Command::Ptr& command)
{ {
fp << "define command {" "\n" fp << "define command {" "\n"
"\t" "command_name\t"; "\t" "command_name\t";
fp << CompatUtility::GetCommandName(command) << "\n"; fp << CompatUtility::GetCommandName(command) << "\n";
@ -161,8 +160,7 @@ void StatusDataWriter::DumpCommand(std::ostream& fp, const Command::Ptr& command
DumpCustomAttributes(fp, command); DumpCustomAttributes(fp, command);
fp << "\n" "\t" "}" "\n" fp << "\n" "\t" "}" "\n" "\n";
"\n";
} }
void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Checkable::Ptr& checkable) void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Checkable::Ptr& checkable)
@ -177,7 +175,7 @@ void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Checkable::Ptr& che
if (service) if (service)
fp << "servicedowntime {" << "\n" fp << "servicedowntime {" << "\n"
"\t" "service_description=" << service->GetShortName() << "\n"; "\t" "service_description=" << service->GetShortName() << "\n";
else else
fp << "hostdowntime {" "\n"; fp << "hostdowntime {" "\n";
@ -187,26 +185,25 @@ void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Checkable::Ptr& che
triggeredByLegacy = triggeredByObj->GetLegacyId(); triggeredByLegacy = triggeredByObj->GetLegacyId();
fp << "\t" << "host_name=" << host->GetName() << "\n" fp << "\t" << "host_name=" << host->GetName() << "\n"
"\t" "downtime_id=" << downtime->GetLegacyId() << "\n" "\t" "downtime_id=" << downtime->GetLegacyId() << "\n"
"\t" "entry_time=" << downtime->GetEntryTime() << "\n" "\t" "entry_time=" << downtime->GetEntryTime() << "\n"
"\t" "start_time=" << downtime->GetStartTime() << "\n" "\t" "start_time=" << downtime->GetStartTime() << "\n"
"\t" "end_time=" << downtime->GetEndTime() << "\n" "\t" "end_time=" << downtime->GetEndTime() << "\n"
"\t" "triggered_by=" << triggeredByLegacy << "\n" "\t" "triggered_by=" << triggeredByLegacy << "\n"
"\t" "fixed=" << static_cast<long>(downtime->GetFixed()) << "\n" "\t" "fixed=" << static_cast<long>(downtime->GetFixed()) << "\n"
"\t" "duration=" << static_cast<long>(downtime->GetDuration()) << "\n" "\t" "duration=" << static_cast<long>(downtime->GetDuration()) << "\n"
"\t" "is_in_effect=" << (downtime->IsInEffect() ? 1 : 0) << "\n" "\t" "is_in_effect=" << (downtime->IsInEffect() ? 1 : 0) << "\n"
"\t" "author=" << downtime->GetAuthor() << "\n" "\t" "author=" << downtime->GetAuthor() << "\n"
"\t" "comment=" << downtime->GetComment() << "\n" "\t" "comment=" << downtime->GetComment() << "\n"
"\t" "trigger_time=" << downtime->GetTriggerTime() << "\n" "\t" "trigger_time=" << downtime->GetTriggerTime() << "\n"
"\t" "}" "\n" "\t" "}" "\n"
"\n"; "\n";
} }
} }
void StatusDataWriter::DumpHostStatus(std::ostream& fp, const Host::Ptr& host) void StatusDataWriter::DumpHostStatus(std::ostream& fp, const Host::Ptr& host)
{ {
fp << "hoststatus {" << "\n" fp << "hoststatus {" "\n" "\t" "host_name=" << host->GetName() << "\n";
<< "\t" << "host_name=" << host->GetName() << "\n";
{ {
ObjectLock olock(host); ObjectLock olock(host);
@ -215,11 +212,10 @@ void StatusDataWriter::DumpHostStatus(std::ostream& fp, const Host::Ptr& host)
/* ugly but cgis parse only that */ /* ugly but cgis parse only that */
fp << "\t" "last_time_up=" << host->GetLastStateUp() << "\n" fp << "\t" "last_time_up=" << host->GetLastStateUp() << "\n"
"\t" "last_time_down=" << host->GetLastStateDown() << "\n" "\t" "last_time_down=" << host->GetLastStateDown() << "\n"
"\t" "last_time_unreachable=" << host->GetLastStateUnreachable() << "\n"; "\t" "last_time_unreachable=" << host->GetLastStateUnreachable() << "\n";
fp << "\t" "}" "\n" fp << "\t" "}" "\n" "\n";
"\n";
DumpDowntimes(fp, host); DumpDowntimes(fp, host);
DumpComments(fp, host); DumpComments(fp, host);
@ -237,25 +233,25 @@ void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
String address6 = host->GetAddress6(); String address6 = host->GetAddress6();
fp << "define host {" "\n" fp << "define host {" "\n"
"\t" "host_name" "\t" << host->GetName() << "\n"; "\t" "host_name" "\t" << host->GetName() << "\n";
if (!display_name.IsEmpty()) { if (!display_name.IsEmpty()) {
fp << "\t" "display_name" "\t" << host->GetDisplayName() << "\n" fp << "\t" "display_name" "\t" << host->GetDisplayName() << "\n"
"\t" "alias" "\t" << host->GetDisplayName() << "\n"; "\t" "alias" "\t" << host->GetDisplayName() << "\n";
} }
if (!address.IsEmpty()) if (!address.IsEmpty())
fp << "\t" "address" "\t" << address << "\n"; fp << "\t" "address" "\t" << address << "\n";
if (!address6.IsEmpty()) if (!address6.IsEmpty())
fp << "\t" "address6" "\t" << address6 << "\n"; fp << "\t" "address6" "\t" << address6 << "\n";
if (!notes.IsEmpty()) if (!notes.IsEmpty())
fp << "\t" "notes" "\t" << notes << "\n"; fp << "\t" "notes" "\t" << notes << "\n";
if (!notes_url.IsEmpty()) if (!notes_url.IsEmpty())
fp << "\t" "notes_url" "\t" << notes_url << "\n"; fp << "\t" "notes_url" "\t" << notes_url << "\n";
if (!action_url.IsEmpty()) if (!action_url.IsEmpty())
fp << "\t" "action_url" "\t" << action_url << "\n"; fp << "\t" "action_url" "\t" << action_url << "\n";
if (!icon_image.IsEmpty()) if (!icon_image.IsEmpty())
fp << "\t" "icon_image" "\t" << icon_image << "\n"; fp << "\t" "icon_image" "\t" << icon_image << "\n";
if (!icon_image_alt.IsEmpty()) if (!icon_image_alt.IsEmpty())
fp << "\t" "icon_image_alt" "\t" << icon_image_alt << "\n"; fp << "\t" "icon_image_alt" "\t" << icon_image_alt << "\n";
std::set<Checkable::Ptr> parents = host->GetParents(); std::set<Checkable::Ptr> parents = host->GetParents();
@ -268,14 +264,14 @@ void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
ObjectLock olock(host); ObjectLock olock(host);
fp << "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(host) << "\n" fp << "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(host) << "\n"
"\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(host) << "\n" "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(host) << "\n"
"\t" "max_check_attempts" "\t" << host->GetMaxCheckAttempts() << "\n" "\t" "max_check_attempts" "\t" << host->GetMaxCheckAttempts() << "\n"
"\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(host) << "\n" "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(host) << "\n"
"\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(host) << "\n" "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(host) << "\n"
"\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(host) << "\n" "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(host) << "\n"
"\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(host) << "\n" "\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(host) << "\n"
"\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(host) << "\n" "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(host) << "\n"
"\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(host) << "\n"; "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(host) << "\n";
CheckCommand::Ptr checkcommand = host->GetCheckCommand(); CheckCommand::Ptr checkcommand = host->GetCheckCommand();
if (checkcommand) if (checkcommand)
@ -296,10 +292,10 @@ void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
fp << "\n"; fp << "\n";
fp << "\t" << "initial_state" "\t" "o" "\n" fp << "\t" << "initial_state" "\t" "o" "\n"
"\t" "low_flap_threshold" "\t" << host->GetFlappingThresholdLow() << "\n" "\t" "low_flap_threshold" "\t" << host->GetFlappingThresholdLow() << "\n"
"\t" "high_flap_threshold" "\t" << host->GetFlappingThresholdHigh() << "\n" "\t" "high_flap_threshold" "\t" << host->GetFlappingThresholdHigh() << "\n"
"\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(host) << "\n" "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(host) << "\n"
"\t" "check_freshness" "\t" "1" "\n"; "\t" "check_freshness" "\t" "1" "\n";
fp << "\t" "host_groups" "\t"; fp << "\t" "host_groups" "\t";
bool first = true; bool first = true;
@ -327,8 +323,7 @@ void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
DumpCustomAttributes(fp, host); DumpCustomAttributes(fp, host);
fp << "\t" "}" "\n" fp << "\t" "}" "\n" "\n";
"\n";
} }
void StatusDataWriter::DumpCheckableStatusAttrs(std::ostream& fp, const Checkable::Ptr& checkable) void StatusDataWriter::DumpCheckableStatusAttrs(std::ostream& fp, const Checkable::Ptr& checkable)
@ -339,17 +334,17 @@ void StatusDataWriter::DumpCheckableStatusAttrs(std::ostream& fp, const Checkabl
CheckCommand::Ptr checkcommand = checkable->GetCheckCommand(); CheckCommand::Ptr checkcommand = checkable->GetCheckCommand();
fp << "\t" << "check_command=" << CompatUtility::GetCommandName(checkcommand) << "!" << CompatUtility::GetCheckableCommandArgs(checkable) << "\n" fp << "\t" << "check_command=" << CompatUtility::GetCommandName(checkcommand) << "!" << CompatUtility::GetCheckableCommandArgs(checkable) << "\n"
"\t" "event_handler=" << CompatUtility::GetCommandName(eventcommand) << "\n" "\t" "event_handler=" << CompatUtility::GetCommandName(eventcommand) << "\n"
"\t" "check_period=" << CompatUtility::GetCheckableCheckPeriod(checkable) << "\n" "\t" "check_period=" << CompatUtility::GetCheckableCheckPeriod(checkable) << "\n"
"\t" "check_interval=" << CompatUtility::GetCheckableCheckInterval(checkable) << "\n" "\t" "check_interval=" << CompatUtility::GetCheckableCheckInterval(checkable) << "\n"
"\t" "retry_interval=" << CompatUtility::GetCheckableRetryInterval(checkable) << "\n" "\t" "retry_interval=" << CompatUtility::GetCheckableRetryInterval(checkable) << "\n"
"\t" "has_been_checked=" << CompatUtility::GetCheckableHasBeenChecked(checkable) << "\n" "\t" "has_been_checked=" << CompatUtility::GetCheckableHasBeenChecked(checkable) << "\n"
"\t" "should_be_scheduled=" << checkable->GetEnableActiveChecks() << "\n" "\t" "should_be_scheduled=" << checkable->GetEnableActiveChecks() << "\n"
"\t" "event_handler_enabled=" << CompatUtility::GetCheckableEventHandlerEnabled(checkable) << "\n"; "\t" "event_handler_enabled=" << CompatUtility::GetCheckableEventHandlerEnabled(checkable) << "\n";
if (cr) { if (cr) {
fp << "\t" << "check_execution_time=" << Convert::ToString(cr->CalculateExecutionTime()) << "\n" fp << "\t" << "check_execution_time=" << Convert::ToString(cr->CalculateExecutionTime()) << "\n"
"\t" "check_latency=" << Convert::ToString(cr->CalculateLatency()) << "\n"; "\t" "check_latency=" << Convert::ToString(cr->CalculateLatency()) << "\n";
} }
Host::Ptr host; Host::Ptr host;
@ -358,48 +353,48 @@ void StatusDataWriter::DumpCheckableStatusAttrs(std::ostream& fp, const Checkabl
if (service) { if (service) {
fp << "\t" "current_state=" << service->GetState() << "\n" fp << "\t" "current_state=" << service->GetState() << "\n"
"\t" "last_hard_state=" << service->GetLastHardState() << "\n" "\t" "last_hard_state=" << service->GetLastHardState() << "\n"
"\t" "last_time_ok=" << static_cast<int>(service->GetLastStateOK()) << "\n" "\t" "last_time_ok=" << static_cast<int>(service->GetLastStateOK()) << "\n"
"\t" "last_time_warn=" << static_cast<int>(service->GetLastStateWarning()) << "\n" "\t" "last_time_warn=" << static_cast<int>(service->GetLastStateWarning()) << "\n"
"\t" "last_time_critical=" << static_cast<int>(service->GetLastStateCritical()) << "\n" "\t" "last_time_critical=" << static_cast<int>(service->GetLastStateCritical()) << "\n"
"\t" "last_time_unknown=" << static_cast<int>(service->GetLastStateUnknown()) << "\n"; "\t" "last_time_unknown=" << static_cast<int>(service->GetLastStateUnknown()) << "\n";
} else { } else {
fp << "\t" "current_state=" << CompatUtility::GetHostCurrentState(host) << "\n" fp << "\t" "current_state=" << CompatUtility::GetHostCurrentState(host) << "\n"
"\t" "last_hard_state=" << host->GetLastHardState() << "\n" "\t" "last_hard_state=" << host->GetLastHardState() << "\n"
"\t" "last_time_up=" << static_cast<int>(host->GetLastStateUp()) << "\n" "\t" "last_time_up=" << static_cast<int>(host->GetLastStateUp()) << "\n"
"\t" "last_time_down=" << static_cast<int>(host->GetLastStateDown()) << "\n"; "\t" "last_time_down=" << static_cast<int>(host->GetLastStateDown()) << "\n";
} }
fp << "\t" "state_type=" << checkable->GetStateType() << "\n" fp << "\t" "state_type=" << checkable->GetStateType() << "\n"
"\t" "plugin_output=" << CompatUtility::GetCheckResultOutput(cr) << "\n" "\t" "plugin_output=" << CompatUtility::GetCheckResultOutput(cr) << "\n"
"\t" "long_plugin_output=" << CompatUtility::GetCheckResultLongOutput(cr) << "\n" "\t" "long_plugin_output=" << CompatUtility::GetCheckResultLongOutput(cr) << "\n"
"\t" "performance_data=" << CompatUtility::GetCheckResultPerfdata(cr) << "\n"; "\t" "performance_data=" << CompatUtility::GetCheckResultPerfdata(cr) << "\n";
if (cr) { if (cr) {
fp << "\t" << "check_source=" << cr->GetCheckSource() << "\n" fp << "\t" << "check_source=" << cr->GetCheckSource() << "\n"
"\t" "last_check=" << static_cast<long>(cr->GetScheduleEnd()) << "\n"; "\t" "last_check=" << static_cast<long>(cr->GetScheduleEnd()) << "\n";
} }
fp << "\t" << "next_check=" << static_cast<long>(checkable->GetNextCheck()) << "\n" fp << "\t" << "next_check=" << static_cast<long>(checkable->GetNextCheck()) << "\n"
"\t" "current_attempt=" << checkable->GetCheckAttempt() << "\n" "\t" "current_attempt=" << checkable->GetCheckAttempt() << "\n"
"\t" "max_attempts=" << checkable->GetMaxCheckAttempts() << "\n" "\t" "max_attempts=" << checkable->GetMaxCheckAttempts() << "\n"
"\t" "last_state_change=" << static_cast<long>(checkable->GetLastStateChange()) << "\n" "\t" "last_state_change=" << static_cast<long>(checkable->GetLastStateChange()) << "\n"
"\t" "last_hard_state_change=" << static_cast<long>(checkable->GetLastHardStateChange()) << "\n" "\t" "last_hard_state_change=" << static_cast<long>(checkable->GetLastHardStateChange()) << "\n"
"\t" "last_update=" << static_cast<long>(time(nullptr)) << "\n" "\t" "last_update=" << static_cast<long>(time(nullptr)) << "\n"
"\t" "notifications_enabled=" << CompatUtility::GetCheckableNotificationsEnabled(checkable) << "\n" "\t" "notifications_enabled=" << CompatUtility::GetCheckableNotificationsEnabled(checkable) << "\n"
"\t" "active_checks_enabled=" << CompatUtility::GetCheckableActiveChecksEnabled(checkable) << "\n" "\t" "active_checks_enabled=" << CompatUtility::GetCheckableActiveChecksEnabled(checkable) << "\n"
"\t" "passive_checks_enabled=" << CompatUtility::GetCheckablePassiveChecksEnabled(checkable) << "\n" "\t" "passive_checks_enabled=" << CompatUtility::GetCheckablePassiveChecksEnabled(checkable) << "\n"
"\t" "flap_detection_enabled=" << CompatUtility::GetCheckableFlapDetectionEnabled(checkable) << "\n" "\t" "flap_detection_enabled=" << CompatUtility::GetCheckableFlapDetectionEnabled(checkable) << "\n"
"\t" "is_flapping=" << CompatUtility::GetCheckableIsFlapping(checkable) << "\n" "\t" "is_flapping=" << CompatUtility::GetCheckableIsFlapping(checkable) << "\n"
"\t" "percent_state_change=" << CompatUtility::GetCheckablePercentStateChange(checkable) << "\n" "\t" "percent_state_change=" << CompatUtility::GetCheckablePercentStateChange(checkable) << "\n"
"\t" "problem_has_been_acknowledged=" << CompatUtility::GetCheckableProblemHasBeenAcknowledged(checkable) << "\n" "\t" "problem_has_been_acknowledged=" << CompatUtility::GetCheckableProblemHasBeenAcknowledged(checkable) << "\n"
"\t" "acknowledgement_type=" << CompatUtility::GetCheckableAcknowledgementType(checkable) << "\n" "\t" "acknowledgement_type=" << CompatUtility::GetCheckableAcknowledgementType(checkable) << "\n"
"\t" "acknowledgement_end_time=" << checkable->GetAcknowledgementExpiry() << "\n" "\t" "acknowledgement_end_time=" << checkable->GetAcknowledgementExpiry() << "\n"
"\t" "scheduled_downtime_depth=" << checkable->GetDowntimeDepth() << "\n" "\t" "scheduled_downtime_depth=" << checkable->GetDowntimeDepth() << "\n"
"\t" "last_notification=" << CompatUtility::GetCheckableNotificationLastNotification(checkable) << "\n" "\t" "last_notification=" << CompatUtility::GetCheckableNotificationLastNotification(checkable) << "\n"
"\t" "next_notification=" << CompatUtility::GetCheckableNotificationNextNotification(checkable) << "\n" "\t" "next_notification=" << CompatUtility::GetCheckableNotificationNextNotification(checkable) << "\n"
"\t" "current_notification_number=" << CompatUtility::GetCheckableNotificationNotificationNumber(checkable) << "\n" "\t" "current_notification_number=" << CompatUtility::GetCheckableNotificationNotificationNumber(checkable) << "\n"
"\t" "is_reachable=" << CompatUtility::GetCheckableIsReachable(checkable) << "\n"; "\t" "is_reachable=" << CompatUtility::GetCheckableIsReachable(checkable) << "\n";
} }
void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& service) void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& service)
@ -407,16 +402,15 @@ void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& s
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
fp << "servicestatus {" "\n" fp << "servicestatus {" "\n"
"\t" "host_name=" << host->GetName() << "\n" "\t" "host_name=" << host->GetName() << "\n"
"\t" "service_description=" << service->GetShortName() << "\n"; "\t" "service_description=" << service->GetShortName() << "\n";
{ {
ObjectLock olock(service); ObjectLock olock(service);
DumpCheckableStatusAttrs(fp, service); DumpCheckableStatusAttrs(fp, service);
} }
fp << "\t" "}" "\n" fp << "\t" "}" "\n" "\n";
"\n";
DumpDowntimes(fp, service); DumpDowntimes(fp, service);
DumpComments(fp, service); DumpComments(fp, service);
@ -430,22 +424,22 @@ void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& s
ObjectLock olock(service); ObjectLock olock(service);
fp << "define service {" "\n" fp << "define service {" "\n"
"\t" "host_name" "\t" << host->GetName() << "\n" "\t" "host_name" "\t" << host->GetName() << "\n"
"\t" "service_description" "\t" << service->GetShortName() << "\n" "\t" "service_description" "\t" << service->GetShortName() << "\n"
"\t" "display_name" "\t" << service->GetDisplayName() << "\n" "\t" "display_name" "\t" << service->GetDisplayName() << "\n"
"\t" "check_period" "\t" << CompatUtility::GetCheckableCheckPeriod(service) << "\n" "\t" "check_period" "\t" << CompatUtility::GetCheckableCheckPeriod(service) << "\n"
"\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(service) << "\n" "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(service) << "\n"
"\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(service) << "\n" "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(service) << "\n"
"\t" "max_check_attempts" "\t" << service->GetMaxCheckAttempts() << "\n" "\t" "max_check_attempts" "\t" << service->GetMaxCheckAttempts() << "\n"
"\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(service) << "\n" "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(service) << "\n"
"\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(service) << "\n" "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(service) << "\n"
"\t" "flap_detection_enabled" "\t" << CompatUtility::GetCheckableFlapDetectionEnabled(service) << "\n" "\t" "flap_detection_enabled" "\t" << CompatUtility::GetCheckableFlapDetectionEnabled(service) << "\n"
"\t" "is_volatile" "\t" << CompatUtility::GetCheckableIsVolatile(service) << "\n" "\t" "is_volatile" "\t" << CompatUtility::GetCheckableIsVolatile(service) << "\n"
"\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(service) << "\n" "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(service) << "\n"
"\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(service) << "\n" "\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(service) << "\n"
"\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(service) << "\n" "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(service) << "\n"
"\t" "notification_period" "\t" << "" << "\n" "\t" "notification_period" "\t" << "" << "\n"
"\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(service) << "\n"; "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(service) << "\n";
CheckCommand::Ptr checkcommand = service->GetCheckCommand(); CheckCommand::Ptr checkcommand = service->GetCheckCommand();
if (checkcommand) if (checkcommand)
@ -470,20 +464,20 @@ void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& s
String icon_image_alt = service->GetIconImageAlt(); String icon_image_alt = service->GetIconImageAlt();
fp << "\t" "initial_state" "\t" "o" "\n" fp << "\t" "initial_state" "\t" "o" "\n"
"\t" "low_flap_threshold" "\t" << service->GetFlappingThresholdLow() << "\n" "\t" "low_flap_threshold" "\t" << service->GetFlappingThresholdLow() << "\n"
"\t" "high_flap_threshold" "\t" << service->GetFlappingThresholdHigh() << "\n" "\t" "high_flap_threshold" "\t" << service->GetFlappingThresholdHigh() << "\n"
"\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(service) << "\n" "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(service) << "\n"
"\t" "check_freshness" << "\t" "1" "\n"; "\t" "check_freshness" << "\t" "1" "\n";
if (!notes.IsEmpty()) if (!notes.IsEmpty())
fp << "\t" "notes" "\t" << notes << "\n"; fp << "\t" "notes" "\t" << notes << "\n";
if (!notes_url.IsEmpty()) if (!notes_url.IsEmpty())
fp << "\t" "notes_url" "\t" << notes_url << "\n"; fp << "\t" "notes_url" "\t" << notes_url << "\n";
if (!action_url.IsEmpty()) if (!action_url.IsEmpty())
fp << "\t" "action_url" "\t" << action_url << "\n"; fp << "\t" "action_url" "\t" << action_url << "\n";
if (!icon_image.IsEmpty()) if (!icon_image.IsEmpty())
fp << "\t" "icon_image" "\t" << icon_image << "\n"; fp << "\t" "icon_image" "\t" << icon_image << "\n";
if (!icon_image_alt.IsEmpty()) if (!icon_image_alt.IsEmpty())
fp << "\t" "icon_image_alt" "\t" << icon_image_alt << "\n"; fp << "\t" "icon_image_alt" "\t" << icon_image_alt << "\n";
} }
fp << "\t" "service_groups" "\t"; fp << "\t" "service_groups" "\t";
@ -512,8 +506,7 @@ void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& s
DumpCustomAttributes(fp, service); DumpCustomAttributes(fp, service);
fp << "\t" "}" "\n" fp << "\t" "}" "\n" "\n";
"\n";
} }
void StatusDataWriter::DumpCustomAttributes(std::ostream& fp, const CustomVarObject::Ptr& object) void StatusDataWriter::DumpCustomAttributes(std::ostream& fp, const CustomVarObject::Ptr& object)
@ -557,8 +550,8 @@ void StatusDataWriter::UpdateObjectsCache(void)
objectfp << std::fixed; objectfp << std::fixed;
objectfp << "# Icinga objects cache file" "\n" objectfp << "# Icinga objects cache file" "\n"
"# This file is auto-generated. Do not modify this file." "\n" "# This file is auto-generated. Do not modify this file." "\n"
"\n"; "\n";
for (const Host::Ptr& host : ConfigType::GetObjectsByType<Host>()) { for (const Host::Ptr& host : ConfigType::GetObjectsByType<Host>()) {
std::ostringstream tempobjectfp; std::ostringstream tempobjectfp;
@ -591,16 +584,15 @@ void StatusDataWriter::UpdateObjectsCache(void)
if (!notes.IsEmpty()) if (!notes.IsEmpty())
tempobjectfp << "\t" "notes" "\t" << notes << "\n"; tempobjectfp << "\t" "notes" "\t" << notes << "\n";
if (!notes_url.IsEmpty()) if (!notes_url.IsEmpty())
tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n"; tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n";
if (!action_url.IsEmpty()) if (!action_url.IsEmpty())
tempobjectfp << "\t" "action_url" "\t" << action_url << "\n"; tempobjectfp << "\t" "action_url" "\t" << action_url << "\n";
DumpCustomAttributes(tempobjectfp, hg); DumpCustomAttributes(tempobjectfp, hg);
tempobjectfp << "\t" "members" "\t"; tempobjectfp << "\t" "members" "\t";
DumpNameList(tempobjectfp, hg->GetMembers()); DumpNameList(tempobjectfp, hg->GetMembers());
tempobjectfp << "\n" tempobjectfp << "\n" "\t" "}" "\n";
"\t" "}" "\n";
objectfp << tempobjectfp.str(); objectfp << tempobjectfp.str();
} }
@ -615,16 +607,16 @@ void StatusDataWriter::UpdateObjectsCache(void)
String action_url = sg->GetActionUrl(); String action_url = sg->GetActionUrl();
tempobjectfp << "define servicegroup {" "\n" tempobjectfp << "define servicegroup {" "\n"
"\t" "servicegroup_name" "\t" << sg->GetName() << "\n"; "\t" "servicegroup_name" "\t" << sg->GetName() << "\n";
if (!display_name.IsEmpty()) if (!display_name.IsEmpty())
tempobjectfp << "\t" "alias" "\t" << display_name << "\n"; tempobjectfp << "\t" "alias" "\t" << display_name << "\n";
if (!notes.IsEmpty()) if (!notes.IsEmpty())
tempobjectfp << "\t" "notes" "\t" << notes << "\n"; tempobjectfp << "\t" "notes" "\t" << notes << "\n";
if (!notes_url.IsEmpty()) if (!notes_url.IsEmpty())
tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n"; tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n";
if (!action_url.IsEmpty()) if (!action_url.IsEmpty())
tempobjectfp << "\t" "action_url" "\t" << action_url << "\n"; tempobjectfp << "\t" "action_url" "\t" << action_url << "\n";
DumpCustomAttributes(tempobjectfp, sg); DumpCustomAttributes(tempobjectfp, sg);
@ -640,8 +632,7 @@ void StatusDataWriter::UpdateObjectsCache(void)
DumpStringList(tempobjectfp, sglist); DumpStringList(tempobjectfp, sglist);
tempobjectfp << "\n" tempobjectfp << "\n" "}" "\n";
"}" "\n";
objectfp << tempobjectfp.str(); objectfp << tempobjectfp.str();
} }
@ -665,11 +656,11 @@ void StatusDataWriter::UpdateObjectsCache(void)
tempobjectfp << "\t" "pager" "\t" << pager << "\n"; tempobjectfp << "\t" "pager" "\t" << pager << "\n";
tempobjectfp << "\t" "service_notification_options" "\t" "w,u,c,r,f,s" "\n" tempobjectfp << "\t" "service_notification_options" "\t" "w,u,c,r,f,s" "\n"
"\t" "host_notification_options""\t" "d,u,r,f,s" "\n" "\t" "host_notification_options""\t" "d,u,r,f,s" "\n"
"\t" "host_notifications_enabled" "\t" "1" "\n" "\t" "host_notifications_enabled" "\t" "1" "\n"
"\t" "service_notifications_enabled" "\t" "1" "\n" "\t" "service_notifications_enabled" "\t" "1" "\n"
"\t" "}" "\n" "\t" "}" "\n"
"\n"; "\n";
objectfp << tempobjectfp.str(); objectfp << tempobjectfp.str();
} }
@ -711,7 +702,7 @@ void StatusDataWriter::UpdateObjectsCache(void)
if (!parent) { if (!parent) {
Log(LogDebug, "StatusDataWriter") Log(LogDebug, "StatusDataWriter")
<< "Missing parent for dependency '" << dep->GetName() << "'."; << "Missing parent for dependency '" << dep->GetName() << "'.";
continue; continue;
} }
@ -723,7 +714,7 @@ void StatusDataWriter::UpdateObjectsCache(void)
if (!child) { if (!child) {
Log(LogDebug, "StatusDataWriter") Log(LogDebug, "StatusDataWriter")
<< "Missing child for dependency '" << dep->GetName() << "'."; << "Missing child for dependency '" << dep->GetName() << "'.";
continue; continue;
} }
@ -749,23 +740,23 @@ void StatusDataWriter::UpdateObjectsCache(void)
/* Icinga 1.x only allows host->host, service->service dependencies */ /* Icinga 1.x only allows host->host, service->service dependencies */
if (!child_service && !parent_service) { if (!child_service && !parent_service) {
objectfp << "define hostdependency {" "\n" objectfp << "define hostdependency {" "\n"
"\t" "dependent_host_name" "\t" << child_host->GetName() << "\n" "\t" "dependent_host_name" "\t" << child_host->GetName() << "\n"
"\t" "host_name" "\t" << parent_host->GetName() << "\n" "\t" "host_name" "\t" << parent_host->GetName() << "\n"
"\t" "execution_failure_criteria" "\t" << criteria << "\n" "\t" "execution_failure_criteria" "\t" << criteria << "\n"
"\t" "notification_failure_criteria" "\t" << criteria << "\n" "\t" "notification_failure_criteria" "\t" << criteria << "\n"
"\t" "}" "\n" "\t" "}" "\n"
"\n"; "\n";
} else if (child_service && parent_service){ } else if (child_service && parent_service){
objectfp << "define servicedependency {" "\n" objectfp << "define servicedependency {" "\n"
"\t" "dependent_host_name" "\t" << child_service->GetHost()->GetName() << "\n" "\t" "dependent_host_name" "\t" << child_service->GetHost()->GetName() << "\n"
"\t" "dependent_service_description" "\t" << child_service->GetShortName() << "\n" "\t" "dependent_service_description" "\t" << child_service->GetShortName() << "\n"
"\t" "host_name" "\t" << parent_service->GetHost()->GetName() << "\n" "\t" "host_name" "\t" << parent_service->GetHost()->GetName() << "\n"
"\t" "service_description" "\t" << parent_service->GetShortName() << "\n" "\t" "service_description" "\t" << parent_service->GetShortName() << "\n"
"\t" "execution_failure_criteria" "\t" << criteria << "\n" "\t" "execution_failure_criteria" "\t" << criteria << "\n"
"\t" "notification_failure_criteria" "\t" << criteria << "\n" "\t" "notification_failure_criteria" "\t" << criteria << "\n"
"\t" "}" "\n" "\t" "}" "\n"
"\n"; "\n";
} }
} }
@ -777,9 +768,9 @@ void StatusDataWriter::UpdateObjectsCache(void)
if (rename(tempObjectsPath.CStr(), objectsPath.CStr()) < 0) { if (rename(tempObjectsPath.CStr(), objectsPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempObjectsPath)); << boost::errinfo_file_name(tempObjectsPath));
} }
} }
@ -803,39 +794,39 @@ void StatusDataWriter::StatusTimerHandler(void)
statusfp << std::fixed; statusfp << std::fixed;
statusfp << "# Icinga status file" "\n" statusfp << "# Icinga status file" "\n"
"# This file is auto-generated. Do not modify this file." "\n" "# This file is auto-generated. Do not modify this file." "\n"
"\n"; "\n";
statusfp << "info {" "\n" statusfp << "info {" "\n"
"\t" "created=" << Utility::GetTime() << "\n" "\t" "created=" << Utility::GetTime() << "\n"
"\t" "version=" << Application::GetAppVersion() << "\n" "\t" "version=" << Application::GetAppVersion() << "\n"
"\t" "}" "\n" "\t" "}" "\n"
"\n"; "\n";
statusfp << "programstatus {" "\n" statusfp << "programstatus {" "\n"
"\t" "icinga_pid=" << Utility::GetPid() << "\n" "\t" "icinga_pid=" << Utility::GetPid() << "\n"
"\t" "daemon_mode=1" "\n" "\t" "daemon_mode=1" "\n"
"\t" "program_start=" << static_cast<long>(Application::GetStartTime()) << "\n" "\t" "program_start=" << static_cast<long>(Application::GetStartTime()) << "\n"
"\t" "active_host_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableHostChecks() ? 1 : 0) << "\n" "\t" "active_host_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableHostChecks() ? 1 : 0) << "\n"
"\t" "passive_host_checks_enabled=1" "\n" "\t" "passive_host_checks_enabled=1" "\n"
"\t" "active_service_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableServiceChecks() ? 1 : 0) << "\n" "\t" "active_service_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableServiceChecks() ? 1 : 0) << "\n"
"\t" "passive_service_checks_enabled=1" "\n" "\t" "passive_service_checks_enabled=1" "\n"
"\t" "check_service_freshness=1" "\n" "\t" "check_service_freshness=1" "\n"
"\t" "check_host_freshness=1" "\n" "\t" "check_host_freshness=1" "\n"
"\t" "enable_notifications=" << (IcingaApplication::GetInstance()->GetEnableNotifications() ? 1 : 0) << "\n" "\t" "enable_notifications=" << (IcingaApplication::GetInstance()->GetEnableNotifications() ? 1 : 0) << "\n"
"\t" "enable_event_handlers=" << (IcingaApplication::GetInstance()->GetEnableEventHandlers() ? 1 : 0) << "\n" "\t" "enable_event_handlers=" << (IcingaApplication::GetInstance()->GetEnableEventHandlers() ? 1 : 0) << "\n"
"\t" "enable_flap_detection=" << (IcingaApplication::GetInstance()->GetEnableFlapping() ? 1 : 0) << "\n" "\t" "enable_flap_detection=" << (IcingaApplication::GetInstance()->GetEnableFlapping() ? 1 : 0) << "\n"
"\t" "enable_failure_prediction=0" "\n" "\t" "enable_failure_prediction=0" "\n"
"\t" "process_performance_data=" << (IcingaApplication::GetInstance()->GetEnablePerfdata() ? 1 : 0) << "\n" "\t" "process_performance_data=" << (IcingaApplication::GetInstance()->GetEnablePerfdata() ? 1 : 0) << "\n"
"\t" "active_scheduled_host_check_stats=" << CIB::GetActiveHostChecksStatistics(60) << "," << CIB::GetActiveHostChecksStatistics(5 * 60) << "," << CIB::GetActiveHostChecksStatistics(15 * 60) << "\n" "\t" "active_scheduled_host_check_stats=" << CIB::GetActiveHostChecksStatistics(60) << "," << CIB::GetActiveHostChecksStatistics(5 * 60) << "," << CIB::GetActiveHostChecksStatistics(15 * 60) << "\n"
"\t" "passive_host_check_stats=" << CIB::GetPassiveHostChecksStatistics(60) << "," << CIB::GetPassiveHostChecksStatistics(5 * 60) << "," << CIB::GetPassiveHostChecksStatistics(15 * 60) << "\n" "\t" "passive_host_check_stats=" << CIB::GetPassiveHostChecksStatistics(60) << "," << CIB::GetPassiveHostChecksStatistics(5 * 60) << "," << CIB::GetPassiveHostChecksStatistics(15 * 60) << "\n"
"\t" "active_scheduled_service_check_stats=" << CIB::GetActiveServiceChecksStatistics(60) << "," << CIB::GetActiveServiceChecksStatistics(5 * 60) << "," << CIB::GetActiveServiceChecksStatistics(15 * 60) << "\n" "\t" "active_scheduled_service_check_stats=" << CIB::GetActiveServiceChecksStatistics(60) << "," << CIB::GetActiveServiceChecksStatistics(5 * 60) << "," << CIB::GetActiveServiceChecksStatistics(15 * 60) << "\n"
"\t" "passive_service_check_stats=" << CIB::GetPassiveServiceChecksStatistics(60) << "," << CIB::GetPassiveServiceChecksStatistics(5 * 60) << "," << CIB::GetPassiveServiceChecksStatistics(15 * 60) << "\n" "\t" "passive_service_check_stats=" << CIB::GetPassiveServiceChecksStatistics(60) << "," << CIB::GetPassiveServiceChecksStatistics(5 * 60) << "," << CIB::GetPassiveServiceChecksStatistics(15 * 60) << "\n"
"\t" "next_downtime_id=" << Downtime::GetNextDowntimeID() << "\n" "\t" "next_downtime_id=" << Downtime::GetNextDowntimeID() << "\n"
"\t" "next_comment_id=" << Comment::GetNextCommentID() << "\n"; "\t" "next_comment_id=" << Comment::GetNextCommentID() << "\n";
statusfp << "\t" "}" "\n" statusfp << "\t" "}" "\n"
"\n"; "\n";
for (const Host::Ptr& host : ConfigType::GetObjectsByType<Host>()) { for (const Host::Ptr& host : ConfigType::GetObjectsByType<Host>()) {
std::ostringstream tempstatusfp; std::ostringstream tempstatusfp;
@ -859,13 +850,13 @@ void StatusDataWriter::StatusTimerHandler(void)
if (rename(tempStatusPath.CStr(), statusPath.CStr()) < 0) { if (rename(tempStatusPath.CStr(), statusPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempStatusPath)); << boost::errinfo_file_name(tempStatusPath));
} }
Log(LogNotice, "StatusDataWriter") Log(LogNotice, "StatusDataWriter")
<< "Writing status.dat file took " << Utility::FormatDuration(Utility::GetTime() - start); << "Writing status.dat file took " << Utility::FormatDuration(Utility::GetTime() - start);
} }
void StatusDataWriter::ObjectHandler(void) void StatusDataWriter::ObjectHandler(void)

View File

@ -58,7 +58,7 @@ ActivationContext::Ptr ActivationContext::GetCurrentContext(void)
} }
ActivationScope::ActivationScope(const ActivationContext::Ptr& context) ActivationScope::ActivationScope(const ActivationContext::Ptr& context)
: m_Context(context) : m_Context(context)
{ {
if (!m_Context) if (!m_Context)
m_Context = new ActivationContext(); m_Context = new ActivationContext();

View File

@ -27,10 +27,10 @@ ApplyRule::RuleMap ApplyRule::m_Rules;
ApplyRule::TypeMap ApplyRule::m_Types; ApplyRule::TypeMap ApplyRule::m_Types;
ApplyRule::ApplyRule(const String& targetType, const String& name, const std::shared_ptr<Expression>& expression, ApplyRule::ApplyRule(const String& targetType, const String& name, const std::shared_ptr<Expression>& expression,
const std::shared_ptr<Expression>& filter, const String& package, const String& fkvar, const String& fvvar, const std::shared_ptr<Expression>& fterm, const std::shared_ptr<Expression>& filter, const String& package, const String& fkvar, const String& fvvar, const std::shared_ptr<Expression>& fterm,
bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope) bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope)
: m_TargetType(targetType), m_Name(name), m_Expression(expression), m_Filter(filter), m_Package(package), m_FKVar(fkvar), : m_TargetType(targetType), m_Name(name), m_Expression(expression), m_Filter(filter), m_Package(package), m_FKVar(fkvar),
m_FVVar(fvvar), m_FTerm(fterm), m_IgnoreOnError(ignoreOnError), m_DebugInfo(di), m_Scope(scope), m_HasMatches(false) m_FVVar(fvvar), m_FTerm(fterm), m_IgnoreOnError(ignoreOnError), m_DebugInfo(di), m_Scope(scope), m_HasMatches(false)
{ } { }
String ApplyRule::GetTargetType(void) const String ApplyRule::GetTargetType(void) const
@ -89,8 +89,8 @@ Dictionary::Ptr ApplyRule::GetScope(void) const
} }
void ApplyRule::AddRule(const String& sourceType, const String& targetType, const String& name, void ApplyRule::AddRule(const String& sourceType, const String& targetType, const String& name,
const std::shared_ptr<Expression>& expression, const std::shared_ptr<Expression>& filter, const String& package, const String& fkvar, const std::shared_ptr<Expression>& expression, const std::shared_ptr<Expression>& filter, const String& package, const String& fkvar,
const String& fvvar, const std::shared_ptr<Expression>& fterm, bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope) const String& fvvar, const std::shared_ptr<Expression>& fterm, bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope)
{ {
m_Rules[sourceType].push_back(ApplyRule(targetType, name, expression, filter, package, fkvar, fvvar, fterm, ignoreOnError, di, scope)); m_Rules[sourceType].push_back(ApplyRule(targetType, name, expression, filter, package, fkvar, fvvar, fterm, ignoreOnError, di, scope));
} }
@ -164,7 +164,7 @@ void ApplyRule::CheckMatches(void)
for (const ApplyRule& rule : kv.second) { for (const ApplyRule& rule : kv.second) {
if (!rule.HasMatches()) if (!rule.HasMatches())
Log(LogWarning, "ApplyRule") Log(LogWarning, "ApplyRule")
<< "Apply rule '" << rule.GetName() << "' (" << rule.GetDebugInfo() << ") for type '" << kv.first << "' does not match anywhere!"; << "Apply rule '" << rule.GetName() << "' (" << rule.GetDebugInfo() << ") for type '" << kv.first << "' does not match anywhere!";
} }
} }
} }

View File

@ -53,8 +53,8 @@ public:
bool EvaluateFilter(ScriptFrame& frame) const; bool EvaluateFilter(ScriptFrame& frame) const;
static void AddRule(const String& sourceType, const String& targetType, const String& name, const std::shared_ptr<Expression>& expression, static void AddRule(const String& sourceType, const String& targetType, const String& name, const std::shared_ptr<Expression>& expression,
const std::shared_ptr<Expression>& filter, const String& package, const String& fkvar, const String& fvvar, const std::shared_ptr<Expression>& fterm, const std::shared_ptr<Expression>& filter, const String& package, const String& fkvar, const String& fvvar, const std::shared_ptr<Expression>& fterm,
bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope); bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope);
static std::vector<ApplyRule>& GetRules(const String& type); static std::vector<ApplyRule>& GetRules(const String& type);
static void RegisterType(const String& sourceType, const std::vector<String>& targetTypes); static void RegisterType(const String& sourceType, const std::vector<String>& targetTypes);
@ -82,8 +82,8 @@ private:
static RuleMap m_Rules; static RuleMap m_Rules;
ApplyRule(const String& targetType, const String& name, const std::shared_ptr<Expression>& expression, ApplyRule(const String& targetType, const String& name, const std::shared_ptr<Expression>& expression,
const std::shared_ptr<Expression>& filter, const String& package, const String& fkvar, const String& fvvar, const std::shared_ptr<Expression>& fterm, const std::shared_ptr<Expression>& filter, const String& package, const String& fkvar, const String& fvvar, const std::shared_ptr<Expression>& fterm,
bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope); bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope);
}; };
} }

View File

@ -117,7 +117,7 @@ do { \
while (*yptr) while (*yptr)
yyextra->m_LexBuffer << *yptr++; yyextra->m_LexBuffer << *yptr++;
} }
<STRING><<EOF>> { <STRING><<EOF>> {
BOOST_THROW_EXCEPTION(ScriptError("End-of-file while in string literal", DebugInfoRange(yyextra->m_LocationBegin, *yylloc))); BOOST_THROW_EXCEPTION(ScriptError("End-of-file while in string literal", DebugInfoRange(yyextra->m_LocationBegin, *yylloc)));

View File

@ -416,7 +416,8 @@ object:
} }
$$ = new ObjectExpression(abstract, std::unique_ptr<Expression>($3), std::unique_ptr<Expression>($4), $$ = new ObjectExpression(abstract, std::unique_ptr<Expression>($3), std::unique_ptr<Expression>($4),
std::move(filter), context->GetZone(), context->GetPackage(), std::move(*$5), $6, $7, std::unique_ptr<Expression>($9), DebugInfoRange(@2, @7)); std::move(filter), context->GetZone(), context->GetPackage(), std::move(*$5), $6, $7,
std::unique_ptr<Expression>($9), DebugInfoRange(@2, @7));
delete $5; delete $5;
} }
; ;

View File

@ -36,14 +36,14 @@ std::map<String, std::vector<ZoneFragment> > ConfigCompiler::m_ZoneDirs;
* Constructor for the ConfigCompiler class. * Constructor for the ConfigCompiler class.
* *
* @param path The path of the configuration file (or another name that * @param path The path of the configuration file (or another name that
* identifies the source of the configuration text). * identifies the source of the configuration text).
* @param input Input stream for the configuration file. * @param input Input stream for the configuration file.
* @param zone The zone. * @param zone The zone.
*/ */
ConfigCompiler::ConfigCompiler(const String& path, std::istream *input, ConfigCompiler::ConfigCompiler(const String& path, std::istream *input,
const String& zone, const String& package) const String& zone, const String& package)
: m_Path(path), m_Input(input), m_Zone(zone), m_Package(package), : m_Path(path), m_Input(input), m_Zone(zone), m_Package(package),
m_Eof(false), m_OpenBraces(0) m_Eof(false), m_OpenBraces(0)
{ {
InitializeScanner(); InitializeScanner();
} }
@ -110,14 +110,14 @@ String ConfigCompiler::GetPackage(void) const
} }
void ConfigCompiler::CollectIncludes(std::vector<std::unique_ptr<Expression> >& expressions, void ConfigCompiler::CollectIncludes(std::vector<std::unique_ptr<Expression> >& expressions,
const String& file, const String& zone, const String& package) const String& file, const String& zone, const String& package)
{ {
try { try {
expressions.emplace_back(CompileFile(file, zone, package)); expressions.emplace_back(CompileFile(file, zone, package));
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Log(LogWarning, "ConfigCompiler") Log(LogWarning, "ConfigCompiler")
<< "Cannot compile file '" << "Cannot compile file '"
<< file << "': " << DiagnosticInformation(ex); << file << "': " << DiagnosticInformation(ex);
} }
} }
@ -130,7 +130,7 @@ void ConfigCompiler::CollectIncludes(std::vector<std::unique_ptr<Expression> >&
* @param debuginfo Debug information. * @param debuginfo Debug information.
*/ */
std::unique_ptr<Expression> ConfigCompiler::HandleInclude(const String& relativeBase, const String& path, std::unique_ptr<Expression> ConfigCompiler::HandleInclude(const String& relativeBase, const String& path,
bool search, const String& zone, const String& package, const DebugInfo& debuginfo) bool search, const String& zone, const String& package, const DebugInfo& debuginfo)
{ {
String upath; String upath;
@ -174,7 +174,7 @@ std::unique_ptr<Expression> ConfigCompiler::HandleInclude(const String& relative
* @param debuginfo Debug information. * @param debuginfo Debug information.
*/ */
std::unique_ptr<Expression> ConfigCompiler::HandleIncludeRecursive(const String& relativeBase, const String& path, std::unique_ptr<Expression> ConfigCompiler::HandleIncludeRecursive(const String& relativeBase, const String& path,
const String& pattern, const String& zone, const String& package, const DebugInfo&) const String& pattern, const String& zone, const String& package, const DebugInfo&)
{ {
String ppath; String ppath;
@ -217,7 +217,7 @@ void ConfigCompiler::HandleIncludeZone(const String& relativeBase, const String&
* @param debuginfo Debug information. * @param debuginfo Debug information.
*/ */
std::unique_ptr<Expression> ConfigCompiler::HandleIncludeZones(const String& relativeBase, const String& tag, std::unique_ptr<Expression> ConfigCompiler::HandleIncludeZones(const String& relativeBase, const String& tag,
const String& path, const String& pattern, const String& package, const DebugInfo&) const String& path, const String& pattern, const String& package, const DebugInfo&)
{ {
String ppath; String ppath;
String newRelativeBase = relativeBase; String newRelativeBase = relativeBase;
@ -242,7 +242,7 @@ std::unique_ptr<Expression> ConfigCompiler::HandleIncludeZones(const String& rel
* @returns Configuration items. * @returns Configuration items.
*/ */
std::unique_ptr<Expression> ConfigCompiler::CompileStream(const String& path, std::unique_ptr<Expression> ConfigCompiler::CompileStream(const String& path,
std::istream *stream, const String& zone, const String& package) std::istream *stream, const String& zone, const String& package)
{ {
CONTEXT("Compiling configuration stream with name '" + path + "'"); CONTEXT("Compiling configuration stream with name '" + path + "'");
@ -266,7 +266,7 @@ std::unique_ptr<Expression> ConfigCompiler::CompileStream(const String& path,
* @returns Configuration items. * @returns Configuration items.
*/ */
std::unique_ptr<Expression> ConfigCompiler::CompileFile(const String& path, const String& zone, std::unique_ptr<Expression> ConfigCompiler::CompileFile(const String& path, const String& zone,
const String& package) const String& package)
{ {
CONTEXT("Compiling configuration file '" + path + "'"); CONTEXT("Compiling configuration file '" + path + "'");
@ -279,7 +279,7 @@ std::unique_ptr<Expression> ConfigCompiler::CompileFile(const String& path, cons
<< boost::errinfo_file_name(path)); << boost::errinfo_file_name(path));
Log(LogNotice, "ConfigCompiler") Log(LogNotice, "ConfigCompiler")
<< "Compiling config file: " << path; << "Compiling config file: " << path;
return CompileStream(path, &stream, zone, package); return CompileStream(path, &stream, zone, package);
} }
@ -292,7 +292,7 @@ std::unique_ptr<Expression> ConfigCompiler::CompileFile(const String& path, cons
* @returns Configuration items. * @returns Configuration items.
*/ */
std::unique_ptr<Expression> ConfigCompiler::CompileText(const String& path, const String& text, std::unique_ptr<Expression> ConfigCompiler::CompileText(const String& path, const String& text,
const String& zone, const String& package) const String& zone, const String& package)
{ {
std::stringstream stream(text); std::stringstream stream(text);
return CompileStream(path, &stream, zone, package); return CompileStream(path, &stream, zone, package);
@ -306,7 +306,7 @@ std::unique_ptr<Expression> ConfigCompiler::CompileText(const String& path, cons
void ConfigCompiler::AddIncludeSearchDir(const String& dir) void ConfigCompiler::AddIncludeSearchDir(const String& dir)
{ {
Log(LogInformation, "ConfigCompiler") Log(LogInformation, "ConfigCompiler")
<< "Adding include search dir: " << dir; << "Adding include search dir: " << dir;
m_IncludeSearchDirs.push_back(dir); m_IncludeSearchDirs.push_back(dir);
} }
@ -344,7 +344,7 @@ bool ConfigCompiler::HasZoneConfigAuthority(const String& zoneName)
} }
Log(LogNotice, "ConfigCompiler") Log(LogNotice, "ConfigCompiler")
<< "Registered authoritative config directories for zone '" << zoneName << "': " << Utility::NaturalJoin(paths); << "Registered authoritative config directories for zone '" << zoneName << "': " << Utility::NaturalJoin(paths);
} }
return !empty; return !empty;

View File

@ -87,17 +87,17 @@ class I2_CONFIG_API ConfigCompiler
{ {
public: public:
explicit ConfigCompiler(const String& path, std::istream *input, explicit ConfigCompiler(const String& path, std::istream *input,
const String& zone = String(), const String& package = String()); const String& zone = String(), const String& package = String());
virtual ~ConfigCompiler(void); virtual ~ConfigCompiler(void);
std::unique_ptr<Expression> Compile(void); std::unique_ptr<Expression> Compile(void);
static std::unique_ptr<Expression>CompileStream(const String& path, std::istream *stream, static std::unique_ptr<Expression>CompileStream(const String& path, std::istream *stream,
const String& zone = String(), const String& package = String()); const String& zone = String(), const String& package = String());
static std::unique_ptr<Expression>CompileFile(const String& path, const String& zone = String(), static std::unique_ptr<Expression>CompileFile(const String& path, const String& zone = String(),
const String& package = String()); const String& package = String());
static std::unique_ptr<Expression>CompileText(const String& path, const String& text, static std::unique_ptr<Expression>CompileText(const String& path, const String& text,
const String& zone = String(), const String& package = String()); const String& zone = String(), const String& package = String());
static void AddIncludeSearchDir(const String& dir); static void AddIncludeSearchDir(const String& dir);
@ -110,14 +110,14 @@ public:
String GetPackage(void) const; String GetPackage(void) const;
static void CollectIncludes(std::vector<std::unique_ptr<Expression> >& expressions, static void CollectIncludes(std::vector<std::unique_ptr<Expression> >& expressions,
const String& file, const String& zone, const String& package); const String& file, const String& zone, const String& package);
static std::unique_ptr<Expression> HandleInclude(const String& relativeBase, const String& path, bool search, static std::unique_ptr<Expression> HandleInclude(const String& relativeBase, const String& path, bool search,
const String& zone, const String& package, const DebugInfo& debuginfo = DebugInfo()); const String& zone, const String& package, const DebugInfo& debuginfo = DebugInfo());
static std::unique_ptr<Expression> HandleIncludeRecursive(const String& relativeBase, const String& path, static std::unique_ptr<Expression> HandleIncludeRecursive(const String& relativeBase, const String& path,
const String& pattern, const String& zone, const String& package, const DebugInfo& debuginfo = DebugInfo()); const String& pattern, const String& zone, const String& package, const DebugInfo& debuginfo = DebugInfo());
static std::unique_ptr<Expression> HandleIncludeZones(const String& relativeBase, const String& tag, static std::unique_ptr<Expression> HandleIncludeZones(const String& relativeBase, const String& tag,
const String& path, const String& pattern, const String& package, const DebugInfo& debuginfo = DebugInfo()); const String& path, const String& pattern, const String& package, const DebugInfo& debuginfo = DebugInfo());
size_t ReadInput(char *buffer, size_t max_bytes); size_t ReadInput(char *buffer, size_t max_bytes);
void *GetScanner(void) const; void *GetScanner(void) const;

View File

@ -32,7 +32,7 @@ ConfigCompilerContext *ConfigCompilerContext::GetInstance(void)
} }
ConfigCompilerContext::ConfigCompilerContext(void) ConfigCompilerContext::ConfigCompilerContext(void)
: m_ObjectsFP(nullptr) : m_ObjectsFP(nullptr)
{ } { }
void ConfigCompilerContext::OpenObjectsFile(const String& filename) void ConfigCompilerContext::OpenObjectsFile(const String& filename)
@ -89,9 +89,9 @@ void ConfigCompilerContext::FinishObjectsFile(void)
if (rename(m_ObjectsTempFile.CStr(), m_ObjectsPath.CStr()) < 0) { if (rename(m_ObjectsTempFile.CStr(), m_ObjectsPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error() BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename") << boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno) << boost::errinfo_errno(errno)
<< boost::errinfo_file_name(m_ObjectsTempFile)); << boost::errinfo_file_name(m_ObjectsTempFile));
} }
} }

View File

@ -60,15 +60,15 @@ REGISTER_SCRIPTFUNCTION_NS(Internal, run_with_activation_context, &ConfigItem::R
* @param debuginfo Debug information. * @param debuginfo Debug information.
*/ */
ConfigItem::ConfigItem(const Type::Ptr& type, const String& name, ConfigItem::ConfigItem(const Type::Ptr& type, const String& name,
bool abstract, const std::shared_ptr<Expression>& exprl, bool abstract, const std::shared_ptr<Expression>& exprl,
const std::shared_ptr<Expression>& filter, bool defaultTmpl, bool ignoreOnError, const std::shared_ptr<Expression>& filter, bool defaultTmpl, bool ignoreOnError,
const DebugInfo& debuginfo, const Dictionary::Ptr& scope, const DebugInfo& debuginfo, const Dictionary::Ptr& scope,
const String& zone, const String& package) const String& zone, const String& package)
: m_Type(type), m_Name(name), m_Abstract(abstract), : m_Type(type), m_Name(name), m_Abstract(abstract),
m_Expression(exprl), m_Filter(filter), m_Expression(exprl), m_Filter(filter),
m_DefaultTmpl(defaultTmpl), m_IgnoreOnError(ignoreOnError), m_DefaultTmpl(defaultTmpl), m_IgnoreOnError(ignoreOnError),
m_DebugInfo(debuginfo), m_Scope(scope), m_Zone(zone), m_DebugInfo(debuginfo), m_Scope(scope), m_Zone(zone),
m_Package(package) m_Package(package)
{ {
} }
@ -176,7 +176,7 @@ ConfigObject::Ptr ConfigItem::Commit(bool discard)
{ {
#ifdef I2_DEBUG #ifdef I2_DEBUG
Log(LogDebug, "ConfigItem") Log(LogDebug, "ConfigItem")
<< "Commit called for ConfigItem Type=" << GetType() << ", Name=" << GetName(); << "Commit called for ConfigItem Type=" << GetType() << ", Name=" << GetName();
#endif /* I2_DEBUG */ #endif /* I2_DEBUG */
/* Make sure the type is valid. */ /* Make sure the type is valid. */
@ -204,7 +204,7 @@ ConfigObject::Ptr ConfigItem::Commit(bool discard)
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
if (m_IgnoreOnError) { if (m_IgnoreOnError) {
Log(LogNotice, "ConfigObject") Log(LogNotice, "ConfigObject")
<< "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex); << "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex);
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
@ -256,7 +256,7 @@ ConfigObject::Ptr ConfigItem::Commit(bool discard)
} catch (ValidationError& ex) { } catch (ValidationError& ex) {
if (m_IgnoreOnError) { if (m_IgnoreOnError) {
Log(LogNotice, "ConfigObject") Log(LogNotice, "ConfigObject")
<< "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex); << "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex);
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
@ -275,7 +275,7 @@ ConfigObject::Ptr ConfigItem::Commit(bool discard)
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
if (m_IgnoreOnError) { if (m_IgnoreOnError) {
Log(LogNotice, "ConfigObject") Log(LogNotice, "ConfigObject")
<< "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex); << "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex);
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
@ -336,8 +336,8 @@ void ConfigItem::Register(void)
if (it != items.end()) { if (it != items.end()) {
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "A configuration item of type '" << m_Type->GetName() msgbuf << "A configuration item of type '" << m_Type->GetName()
<< "' and name '" << GetName() << "' already exists (" << "' and name '" << GetName() << "' already exists ("
<< it->second->GetDebugInfo() << "), new declaration: " << GetDebugInfo(); << it->second->GetDebugInfo() << "), new declaration: " << GetDebugInfo();
BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str())); BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str()));
} }
@ -481,7 +481,7 @@ bool ConfigItem::CommitNewItems(const ActivationContext::Ptr& context, WorkQueue
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
if (item->m_IgnoreOnError) { if (item->m_IgnoreOnError) {
Log(LogNotice, "ConfigObject") Log(LogNotice, "ConfigObject")
<< "Ignoring config object '" << item->m_Name << "' of type '" << item->m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex); << "Ignoring config object '" << item->m_Name << "' of type '" << item->m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex);
item->Unregister(); item->Unregister();
@ -565,7 +565,7 @@ bool ConfigItem::CommitItems(const ActivationContext::Ptr& context, WorkQueue& u
for (const ItemCountMap::value_type& kv : itemCounts) { for (const ItemCountMap::value_type& kv : itemCounts) {
Log(LogInformation, "ConfigItem") Log(LogInformation, "ConfigItem")
<< "Instantiated " << kv.second << " " << (kv.second != 1 ? kv.first->GetPluralName() : kv.first->GetName()) << "."; << "Instantiated " << kv.second << " " << (kv.second != 1 ? kv.first->GetPluralName() : kv.first->GetName()) << ".";
} }
} }
@ -604,7 +604,7 @@ bool ConfigItem::ActivateItems(WorkQueue& upq, const std::vector<ConfigItem::Ptr
#ifdef I2_DEBUG #ifdef I2_DEBUG
Log(LogDebug, "ConfigItem") Log(LogDebug, "ConfigItem")
<< "Setting 'active' to true for object '" << object->GetName() << "' of type '" << object->GetReflectionType()->GetName() << "'"; << "Setting 'active' to true for object '" << object->GetName() << "' of type '" << object->GetReflectionType()->GetName() << "'";
#endif /* I2_DEBUG */ #endif /* I2_DEBUG */
upq.Enqueue(std::bind(&ConfigObject::PreActivate, object)); upq.Enqueue(std::bind(&ConfigObject::PreActivate, object));
} }
@ -627,7 +627,7 @@ bool ConfigItem::ActivateItems(WorkQueue& upq, const std::vector<ConfigItem::Ptr
#ifdef I2_DEBUG #ifdef I2_DEBUG
Log(LogDebug, "ConfigItem") Log(LogDebug, "ConfigItem")
<< "Activating object '" << object->GetName() << "' of type '" << object->GetReflectionType()->GetName() << "'"; << "Activating object '" << object->GetName() << "' of type '" << object->GetReflectionType()->GetName() << "'";
#endif /* I2_DEBUG */ #endif /* I2_DEBUG */
upq.Enqueue(std::bind(&ConfigObject::Activate, object, runtimeCreated)); upq.Enqueue(std::bind(&ConfigObject::Activate, object, runtimeCreated));
} }
@ -728,7 +728,7 @@ void ConfigItem::RemoveIgnoredItems(const String& allowedConfigPath)
continue; continue;
Log(LogNotice, "ConfigItem") Log(LogNotice, "ConfigItem")
<< "Removing ignored item path '" << path << "'."; << "Removing ignored item path '" << path << "'.";
(void) unlink(path.CStr()); (void) unlink(path.CStr());
} }

View File

@ -41,11 +41,11 @@ public:
DECLARE_PTR_TYPEDEFS(ConfigItem); DECLARE_PTR_TYPEDEFS(ConfigItem);
ConfigItem(const Type::Ptr& type, const String& name, bool abstract, ConfigItem(const Type::Ptr& type, const String& name, bool abstract,
const std::shared_ptr<Expression>& exprl, const std::shared_ptr<Expression>& exprl,
const std::shared_ptr<Expression>& filter, const std::shared_ptr<Expression>& filter,
bool defaultTmpl, bool ignoreOnError, const DebugInfo& debuginfo, bool defaultTmpl, bool ignoreOnError, const DebugInfo& debuginfo,
const Dictionary::Ptr& scope, const String& zone, const Dictionary::Ptr& scope, const String& zone,
const String& package); const String& package);
Type::Ptr GetType(void) const; Type::Ptr GetType(void) const;
String GetName(void) const; String GetName(void) const;
@ -67,7 +67,7 @@ public:
ConfigObject::Ptr GetObject(void) const; ConfigObject::Ptr GetObject(void) const;
static ConfigItem::Ptr GetByTypeAndName(const Type::Ptr& type, static ConfigItem::Ptr GetByTypeAndName(const Type::Ptr& type,
const String& name); const String& name);
static bool CommitItems(const ActivationContext::Ptr& context, WorkQueue& upq, std::vector<ConfigItem::Ptr>& newItems, bool silent = false); static bool CommitItems(const ActivationContext::Ptr& context, WorkQueue& upq, std::vector<ConfigItem::Ptr>& newItems, bool silent = false);
static bool ActivateItems(WorkQueue& upq, const std::vector<ConfigItem::Ptr>& newItems, bool runtimeCreated = false, bool silent = false, bool withModAttrs = false); static bool ActivateItems(WorkQueue& upq, const std::vector<ConfigItem::Ptr>& newItems, bool runtimeCreated = false, bool silent = false, bool withModAttrs = false);
@ -110,7 +110,7 @@ private:
static IgnoredItemList m_IgnoredItems; static IgnoredItemList m_IgnoredItems;
static ConfigItem::Ptr GetObjectUnlocked(const String& type, static ConfigItem::Ptr GetObjectUnlocked(const String& type,
const String& name); const String& name);
ConfigObject::Ptr Commit(bool discard = true); ConfigObject::Ptr Commit(bool discard = true);

View File

@ -116,7 +116,7 @@ ConfigItem::Ptr ConfigItemBuilder::Compile(void)
templateArray->Add(m_Name); templateArray->Add(m_Name);
exprs.emplace_back(new SetExpression(MakeIndexer(ScopeThis, "templates"), OpSetAdd, exprs.emplace_back(new SetExpression(MakeIndexer(ScopeThis, "templates"), OpSetAdd,
std::unique_ptr<LiteralExpression>(new LiteralExpression(templateArray)), m_DebugInfo)); std::unique_ptr<LiteralExpression>(new LiteralExpression(templateArray)), m_DebugInfo));
#ifdef I2_DEBUG #ifdef I2_DEBUG
if (!m_Abstract) { if (!m_Abstract) {
@ -141,6 +141,6 @@ ConfigItem::Ptr ConfigItemBuilder::Compile(void)
exprl->MakeInline(); exprl->MakeInline();
return new ConfigItem(m_Type, m_Name, m_Abstract, exprl, m_Filter, return new ConfigItem(m_Type, m_Name, m_Abstract, exprl, m_Filter,
m_DefaultTmpl, m_IgnoreOnError, m_DebugInfo, m_Scope, m_Zone, m_Package); m_DefaultTmpl, m_IgnoreOnError, m_DebugInfo, m_Scope, m_Zone, m_Package);
} }

View File

@ -73,7 +73,7 @@ ExpressionResult Expression::Evaluate(ScriptFrame& frame, DebugHint *dhint) cons
frame.DecreaseStackDepth(); frame.DecreaseStackDepth();
BOOST_THROW_EXCEPTION(ScriptError("Error while evaluating expression: " + String(ex.what()), GetDebugInfo()) BOOST_THROW_EXCEPTION(ScriptError("Error while evaluating expression: " + String(ex.what()), GetDebugInfo())
<< boost::errinfo_nested_exception(boost::current_exception())); << boost::errinfo_nested_exception(boost::current_exception()));
} }
frame.DecreaseStackDepth(); frame.DecreaseStackDepth();
@ -796,7 +796,7 @@ ExpressionResult ApplyExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhin
CHECK_RESULT(nameres); CHECK_RESULT(nameres);
return VMOps::NewApply(frame, m_Type, m_Target, nameres.GetValue(), m_Filter, return VMOps::NewApply(frame, m_Type, m_Target, nameres.GetValue(), m_Filter,
m_Package, m_FKVar, m_FVVar, m_FTerm, m_ClosedVars, m_IgnoreOnError, m_Expression, m_DebugInfo); m_Package, m_FKVar, m_FVVar, m_FTerm, m_ClosedVars, m_IgnoreOnError, m_Expression, m_DebugInfo);
} }
ExpressionResult ObjectExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const ExpressionResult ObjectExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
@ -818,7 +818,7 @@ ExpressionResult ObjectExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhi
} }
return VMOps::NewObject(frame, m_Abstract, type, name, m_Filter, m_Zone, return VMOps::NewObject(frame, m_Abstract, type, name, m_Filter, m_Zone,
m_Package, m_DefaultTmpl, m_IgnoreOnError, m_ClosedVars, m_Expression, m_DebugInfo); m_Package, m_DefaultTmpl, m_IgnoreOnError, m_ClosedVars, m_Expression, m_DebugInfo);
} }
ExpressionResult ForExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const ExpressionResult ForExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const

View File

@ -41,7 +41,7 @@ public:
{ } { }
DebugHint(Dictionary::Ptr&& hints) DebugHint(Dictionary::Ptr&& hints)
: m_Hints(std::move(hints)) : m_Hints(std::move(hints))
{ } { }
void AddMessage(const String& message, const DebugInfo& di) void AddMessage(const String& message, const DebugInfo& di)
@ -155,7 +155,7 @@ struct ExpressionResult
public: public:
template<typename T> template<typename T>
ExpressionResult(const T& value, ExpressionResultCode code = ResultOK) ExpressionResult(const T& value, ExpressionResultCode code = ResultOK)
: m_Value(value), m_Code(code) : m_Value(value), m_Code(code)
{ } { }
operator const Value&(void) const operator const Value&(void) const
@ -769,7 +769,7 @@ class I2_CONFIG_API FunctionExpression : public DebuggableExpression
{ {
public: public:
FunctionExpression(const String& name, const std::vector<String>& args, FunctionExpression(const String& name, const std::vector<String>& args,
std::map<String, std::unique_ptr<Expression> >&& closedVars, std::unique_ptr<Expression> expression, const DebugInfo& debugInfo = DebugInfo()) std::map<String, std::unique_ptr<Expression> >&& closedVars, std::unique_ptr<Expression> expression, const DebugInfo& debugInfo = DebugInfo())
: DebuggableExpression(debugInfo), m_Name(name), m_Args(args), m_ClosedVars(std::move(closedVars)), m_Expression(std::move(expression)) : DebuggableExpression(debugInfo), m_Name(name), m_Args(args), m_ClosedVars(std::move(closedVars)), m_Expression(std::move(expression))
{ } { }
@ -787,13 +787,13 @@ class I2_CONFIG_API ApplyExpression : public DebuggableExpression
{ {
public: public:
ApplyExpression(const String& type, const String& target, std::unique_ptr<Expression> name, ApplyExpression(const String& type, const String& target, std::unique_ptr<Expression> name,
std::unique_ptr<Expression> filter, const String& package, const String& fkvar, const String& fvvar, std::unique_ptr<Expression> filter, const String& package, const String& fkvar, const String& fvvar,
std::unique_ptr<Expression> fterm, std::map<String, std::unique_ptr<Expression> >&& closedVars, bool ignoreOnError, std::unique_ptr<Expression> fterm, std::map<String, std::unique_ptr<Expression> >&& closedVars, bool ignoreOnError,
std::unique_ptr<Expression> expression, const DebugInfo& debugInfo = DebugInfo()) std::unique_ptr<Expression> expression, const DebugInfo& debugInfo = DebugInfo())
: DebuggableExpression(debugInfo), m_Type(type), m_Target(target), : DebuggableExpression(debugInfo), m_Type(type), m_Target(target),
m_Name(std::move(name)), m_Filter(std::move(filter)), m_Package(package), m_FKVar(fkvar), m_FVVar(fvvar), m_Name(std::move(name)), m_Filter(std::move(filter)), m_Package(package), m_FKVar(fkvar), m_FVVar(fvvar),
m_FTerm(std::move(fterm)), m_IgnoreOnError(ignoreOnError), m_ClosedVars(std::move(closedVars)), m_FTerm(std::move(fterm)), m_IgnoreOnError(ignoreOnError), m_ClosedVars(std::move(closedVars)),
m_Expression(std::move(expression)) m_Expression(std::move(expression))
{ } { }
protected: protected:
@ -817,11 +817,11 @@ class I2_CONFIG_API ObjectExpression : public DebuggableExpression
{ {
public: public:
ObjectExpression(bool abstract, std::unique_ptr<Expression> type, std::unique_ptr<Expression> name, std::unique_ptr<Expression> filter, ObjectExpression(bool abstract, std::unique_ptr<Expression> type, std::unique_ptr<Expression> name, std::unique_ptr<Expression> filter,
const String& zone, const String& package, std::map<String, std::unique_ptr<Expression> >&& closedVars, const String& zone, const String& package, std::map<String, std::unique_ptr<Expression> >&& closedVars,
bool defaultTmpl, bool ignoreOnError, std::unique_ptr<Expression> expression, const DebugInfo& debugInfo = DebugInfo()) bool defaultTmpl, bool ignoreOnError, std::unique_ptr<Expression> expression, const DebugInfo& debugInfo = DebugInfo())
: DebuggableExpression(debugInfo), m_Abstract(abstract), m_Type(std::move(type)), : DebuggableExpression(debugInfo), m_Abstract(abstract), m_Type(std::move(type)),
m_Name(std::move(name)), m_Filter(std::move(filter)), m_Zone(zone), m_Package(package), m_DefaultTmpl(defaultTmpl), m_Name(std::move(name)), m_Filter(std::move(filter)), m_Zone(zone), m_Package(package), m_DefaultTmpl(defaultTmpl),
m_IgnoreOnError(ignoreOnError), m_ClosedVars(std::move(closedVars)), m_Expression(std::move(expression)) m_IgnoreOnError(ignoreOnError), m_ClosedVars(std::move(closedVars)), m_Expression(std::move(expression))
{ } { }
protected: protected:
@ -879,9 +879,9 @@ class I2_CONFIG_API IncludeExpression : public DebuggableExpression
{ {
public: public:
IncludeExpression(const String& relativeBase, std::unique_ptr<Expression> path, std::unique_ptr<Expression> pattern, std::unique_ptr<Expression> name, IncludeExpression(const String& relativeBase, std::unique_ptr<Expression> path, std::unique_ptr<Expression> pattern, std::unique_ptr<Expression> name,
IncludeType type, bool searchIncludes, const String& zone, const String& package, const DebugInfo& debugInfo = DebugInfo()) IncludeType type, bool searchIncludes, const String& zone, const String& package, const DebugInfo& debugInfo = DebugInfo())
: DebuggableExpression(debugInfo), m_RelativeBase(relativeBase), m_Path(std::move(path)), m_Pattern(std::move(pattern)), : DebuggableExpression(debugInfo), m_RelativeBase(relativeBase), m_Path(std::move(path)), m_Pattern(std::move(pattern)),
m_Name(std::move(name)), m_Type(type), m_SearchIncludes(searchIncludes), m_Zone(zone), m_Package(package) m_Name(std::move(name)), m_Type(type), m_SearchIncludes(searchIncludes), m_Zone(zone), m_Package(package)
{ } { }
protected: protected:
@ -902,7 +902,7 @@ class I2_CONFIG_API BreakpointExpression : public DebuggableExpression
{ {
public: public:
BreakpointExpression(const DebugInfo& debugInfo = DebugInfo()) BreakpointExpression(const DebugInfo& debugInfo = DebugInfo())
: DebuggableExpression(debugInfo) : DebuggableExpression(debugInfo)
{ } { }
protected: protected:

View File

@ -109,7 +109,7 @@ public:
} }
static inline Value NewFunction(ScriptFrame& frame, const String& name, const std::vector<String>& argNames, static inline Value NewFunction(ScriptFrame& frame, const String& name, const std::vector<String>& argNames,
const std::map<String, std::unique_ptr<Expression> >& closedVars, const std::shared_ptr<Expression>& expression) const std::map<String, std::unique_ptr<Expression> >& closedVars, const std::shared_ptr<Expression>& expression)
{ {
auto evaluatedClosedVars = EvaluateClosedVars(frame, closedVars); auto evaluatedClosedVars = EvaluateClosedVars(frame, closedVars);
@ -138,7 +138,7 @@ public:
bool ignoreOnError, const std::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo()) bool ignoreOnError, const std::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
{ {
ApplyRule::AddRule(type, target, name, expression, filter, package, fkvar, ApplyRule::AddRule(type, target, name, expression, filter, package, fkvar,
fvvar, fterm, ignoreOnError, debugInfo, EvaluateClosedVars(frame, closedVars)); fvvar, fterm, ignoreOnError, debugInfo, EvaluateClosedVars(frame, closedVars));
return Empty; return Empty;
} }

View File

@ -51,7 +51,7 @@ void DbConnection::OnConfigLoaded(void)
if (!GetEnableHa()) { if (!GetEnableHa()) {
Log(LogDebug, "DbConnection") Log(LogDebug, "DbConnection")
<< "HA functionality disabled. Won't pause IDO connection: " << GetName(); << "HA functionality disabled. Won't pause IDO connection: " << GetName();
SetHAMode(HARunEverywhere); SetHAMode(HARunEverywhere);
} }
@ -64,7 +64,7 @@ void DbConnection::Start(bool runtimeCreated)
ObjectImpl<DbConnection>::Start(runtimeCreated); ObjectImpl<DbConnection>::Start(runtimeCreated);
Log(LogInformation, "DbConnection") Log(LogInformation, "DbConnection")
<< "'" << GetName() << "' started."; << "'" << GetName() << "' started.";
DbObject::OnQuery.connect(std::bind(&DbConnection::ExecuteQuery, this, _1)); DbObject::OnQuery.connect(std::bind(&DbConnection::ExecuteQuery, this, _1));
DbObject::OnMultipleQueries.connect(std::bind(&DbConnection::ExecuteMultipleQueries, this, _1)); DbObject::OnMultipleQueries.connect(std::bind(&DbConnection::ExecuteMultipleQueries, this, _1));
@ -73,7 +73,7 @@ void DbConnection::Start(bool runtimeCreated)
void DbConnection::Stop(bool runtimeRemoved) void DbConnection::Stop(bool runtimeRemoved)
{ {
Log(LogInformation, "DbConnection") Log(LogInformation, "DbConnection")
<< "'" << GetName() << "' stopped."; << "'" << GetName() << "' stopped.";
ObjectImpl<DbConnection>::Stop(runtimeRemoved); ObjectImpl<DbConnection>::Stop(runtimeRemoved);
} }
@ -91,7 +91,7 @@ void DbConnection::Resume(void)
ConfigObject::Resume(); ConfigObject::Resume();
Log(LogInformation, "DbConnection") Log(LogInformation, "DbConnection")
<< "Resuming IDO connection: " << GetName(); << "Resuming IDO connection: " << GetName();
m_CleanUpTimer = new Timer(); m_CleanUpTimer = new Timer();
m_CleanUpTimer->SetInterval(60); m_CleanUpTimer->SetInterval(60);
@ -104,7 +104,7 @@ void DbConnection::Pause(void)
ConfigObject::Pause(); ConfigObject::Pause();
Log(LogInformation, "DbConnection") Log(LogInformation, "DbConnection")
<< "Pausing IDO connection: " << GetName(); << "Pausing IDO connection: " << GetName();
m_CleanUpTimer.reset(); m_CleanUpTimer.reset();
@ -151,7 +151,7 @@ void DbConnection::InsertRuntimeVariable(const String& key, const Value& value)
void DbConnection::UpdateProgramStatus(void) void DbConnection::UpdateProgramStatus(void)
{ {
Log(LogNotice, "DbConnection") Log(LogNotice, "DbConnection")
<< "Updating programstatus table."; << "Updating programstatus table.";
std::vector<DbQuery> queries; std::vector<DbQuery> queries;
@ -237,9 +237,9 @@ void DbConnection::CleanUpHandler(void)
CleanUpExecuteQuery(tables[i].name, tables[i].time_column, now - max_age); CleanUpExecuteQuery(tables[i].name, tables[i].time_column, now - max_age);
Log(LogNotice, "DbConnection") Log(LogNotice, "DbConnection")
<< "Cleanup (" << tables[i].name << "): " << max_age << "Cleanup (" << tables[i].name << "): " << max_age
<< " now: " << now << " now: " << now
<< " old: " << now - max_age; << " old: " << now - max_age;
} }
} }
@ -459,9 +459,9 @@ void DbConnection::ValidateCategories(const Array::Ptr& value, const ValidationU
int filter = FilterArrayToInt(value, DbQuery::GetCategoryFilterMap(), 0); int filter = FilterArrayToInt(value, DbQuery::GetCategoryFilterMap(), 0);
if (filter != DbCatEverything && (filter & ~(DbCatInvalid | DbCatEverything | DbCatConfig | DbCatState | if (filter != DbCatEverything && (filter & ~(DbCatInvalid | DbCatEverything | DbCatConfig | DbCatState |
DbCatAcknowledgement | DbCatComment | DbCatDowntime | DbCatEventHandler | DbCatExternalCommand | DbCatAcknowledgement | DbCatComment | DbCatDowntime | DbCatEventHandler | DbCatExternalCommand |
DbCatFlapping | DbCatLog | DbCatNotification | DbCatProgramStatus | DbCatRetention | DbCatFlapping | DbCatLog | DbCatNotification | DbCatProgramStatus | DbCatRetention |
DbCatStateHistory)) != 0) DbCatStateHistory)) != 0)
BOOST_THROW_EXCEPTION(ValidationError(this, { "categories" }, "categories filter is invalid.")); BOOST_THROW_EXCEPTION(ValidationError(this, { "categories" }, "categories filter is invalid."));
} }

View File

@ -200,11 +200,11 @@ void DbEvents::ReachabilityChangedHandler(const Checkable::Ptr& checkable, const
is_reachable = 1; is_reachable = 1;
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "Updating reachability for checkable '" << checkable->GetName() << "': " << (is_reachable ? "" : "not" ) << " reachable for " << children.size() << " children."; << "Updating reachability for checkable '" << checkable->GetName() << "': " << (is_reachable ? "" : "not" ) << " reachable for " << children.size() << " children.";
for (const Checkable::Ptr& child : children) { for (const Checkable::Ptr& child : children) {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "Updating reachability for checkable '" << child->GetName() << "': " << (is_reachable ? "" : "not" ) << " reachable."; << "Updating reachability for checkable '" << child->GetName() << "': " << (is_reachable ? "" : "not" ) << " reachable.";
Host::Ptr host; Host::Ptr host;
Service::Ptr service; Service::Ptr service;
@ -730,10 +730,10 @@ void DbEvents::TriggerDowntime(const Downtime::Ptr& downtime)
/* acknowledgements */ /* acknowledgements */
void DbEvents::AddAcknowledgementHistory(const Checkable::Ptr& checkable, const String& author, const String& comment, void DbEvents::AddAcknowledgementHistory(const Checkable::Ptr& checkable, const String& author, const String& comment,
AcknowledgementType type, bool notify, double expiry) AcknowledgementType type, bool notify, double expiry)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add acknowledgement history for '" << checkable->GetName() << "'"; << "add acknowledgement history for '" << checkable->GetName() << "'";
double now = Utility::GetTime(); double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now); std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
@ -781,7 +781,7 @@ void DbEvents::AddAcknowledgementHistory(const Checkable::Ptr& checkable, const
void DbEvents::AddAcknowledgement(const Checkable::Ptr& checkable, AcknowledgementType type) void DbEvents::AddAcknowledgement(const Checkable::Ptr& checkable, AcknowledgementType type)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add acknowledgement for '" << checkable->GetName() << "'"; << "add acknowledgement for '" << checkable->GetName() << "'";
AddAcknowledgementInternal(checkable, type, true); AddAcknowledgementInternal(checkable, type, true);
} }
@ -789,7 +789,7 @@ void DbEvents::AddAcknowledgement(const Checkable::Ptr& checkable, Acknowledgeme
void DbEvents::RemoveAcknowledgement(const Checkable::Ptr& checkable) void DbEvents::RemoveAcknowledgement(const Checkable::Ptr& checkable)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "remove acknowledgement for '" << checkable->GetName() << "'"; << "remove acknowledgement for '" << checkable->GetName() << "'";
AddAcknowledgementInternal(checkable, AcknowledgementNone, false); AddAcknowledgementInternal(checkable, AcknowledgementNone, false);
} }
@ -829,10 +829,10 @@ void DbEvents::AddAcknowledgementInternal(const Checkable::Ptr& checkable, Ackno
/* notifications */ /* notifications */
void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const std::set<User::Ptr>& users, NotificationType type, void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const std::set<User::Ptr>& users, NotificationType type,
const CheckResult::Ptr& cr, const String& author, const String& text) const CheckResult::Ptr& cr, const String& author, const String& text)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add notification history for '" << checkable->GetName() << "'"; << "add notification history for '" << checkable->GetName() << "'";
/* start and end happen at the same time */ /* start and end happen at the same time */
double now = Utility::GetTime(); double now = Utility::GetTime();
@ -885,7 +885,7 @@ void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, con
for (const User::Ptr& user : users) { for (const User::Ptr& user : users) {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add contact notification history for service '" << checkable->GetName() << "' and user '" << user->GetName() << "'."; << "add contact notification history for service '" << checkable->GetName() << "' and user '" << user->GetName() << "'.";
DbQuery query2; DbQuery query2;
query2.Table = "contactnotifications"; query2.Table = "contactnotifications";
@ -913,7 +913,7 @@ void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, con
void DbEvents::AddStateChangeHistory(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, StateType type) void DbEvents::AddStateChangeHistory(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, StateType type)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add state change history for '" << checkable->GetName() << "'"; << "add state change history for '" << checkable->GetName() << "'";
double ts = cr->GetExecutionEnd(); double ts = cr->GetExecutionEnd();
std::pair<unsigned long, unsigned long> state_time_bag = CompatUtility::ConvertTimestamp(ts); std::pair<unsigned long, unsigned long> state_time_bag = CompatUtility::ConvertTimestamp(ts);
@ -983,7 +983,7 @@ void DbEvents::AddCheckResultLogHistory(const Checkable::Ptr& checkable, const C
bool reachable_before = vars_before->Get("reachable"); bool reachable_before = vars_before->Get("reachable");
if (state_before == state_after && stateType_before == stateType_after && if (state_before == state_after && stateType_before == stateType_after &&
attempt_before == attempt_after && reachable_before == reachable_after) attempt_before == attempt_after && reachable_before == reachable_after)
return; /* Nothing changed, ignore this checkresult. */ return; /* Nothing changed, ignore this checkresult. */
} }
@ -1001,13 +1001,13 @@ void DbEvents::AddCheckResultLogHistory(const Checkable::Ptr& checkable, const C
if (service) { if (service) {
msgbuf << "SERVICE ALERT: " msgbuf << "SERVICE ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< service->GetShortName() << ";" << service->GetShortName() << ";"
<< Service::StateToString(service->GetState()) << ";" << Service::StateToString(service->GetState()) << ";"
<< Service::StateTypeToString(service->GetStateType()) << ";" << Service::StateTypeToString(service->GetStateType()) << ";"
<< attempt_after << ";" << attempt_after << ";"
<< output << "" << output << ""
<< ""; << "";
switch (service->GetState()) { switch (service->GetState()) {
case ServiceOK: case ServiceOK:
@ -1024,17 +1024,17 @@ void DbEvents::AddCheckResultLogHistory(const Checkable::Ptr& checkable, const C
break; break;
default: default:
Log(LogCritical, "DbEvents") Log(LogCritical, "DbEvents")
<< "Unknown service state: " << state_after; << "Unknown service state: " << state_after;
return; return;
} }
} else { } else {
msgbuf << "HOST ALERT: " msgbuf << "HOST ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< CompatUtility::GetHostStateString(host) << ";" << CompatUtility::GetHostStateString(host) << ";"
<< Host::StateTypeToString(host->GetStateType()) << ";" << Host::StateTypeToString(host->GetStateType()) << ";"
<< attempt_after << ";" << attempt_after << ";"
<< output << "" << output << ""
<< ""; << "";
switch (host->GetState()) { switch (host->GetState()) {
case HostUp: case HostUp:
@ -1045,7 +1045,7 @@ void DbEvents::AddCheckResultLogHistory(const Checkable::Ptr& checkable, const C
break; break;
default: default:
Log(LogCritical, "DbEvents") Log(LogCritical, "DbEvents")
<< "Unknown host state: " << state_after; << "Unknown host state: " << state_after;
return; return;
} }
@ -1124,8 +1124,8 @@ void DbEvents::AddRemoveDowntimeLogHistory(const Downtime::Ptr& downtime)
} }
void DbEvents::AddNotificationSentLogHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const User::Ptr& user, void DbEvents::AddNotificationSentLogHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const User::Ptr& user,
NotificationType notification_type, const CheckResult::Ptr& cr, NotificationType notification_type, const CheckResult::Ptr& cr,
const String& author, const String& comment_text) const String& author, const String& comment_text)
{ {
CheckCommand::Ptr commandObj = checkable->GetCheckCommand(); CheckCommand::Ptr commandObj = checkable->GetCheckCommand();
@ -1156,23 +1156,23 @@ void DbEvents::AddNotificationSentLogHistory(const Notification::Ptr& notificati
if (service) { if (service) {
msgbuf << "SERVICE NOTIFICATION: " msgbuf << "SERVICE NOTIFICATION: "
<< user->GetName() << ";" << user->GetName() << ";"
<< host->GetName() << ";" << host->GetName() << ";"
<< service->GetShortName() << ";" << service->GetShortName() << ";"
<< notification_type_str << " " << notification_type_str << " "
<< "(" << Service::StateToString(service->GetState()) << ");" << "(" << Service::StateToString(service->GetState()) << ");"
<< check_command << ";" << check_command << ";"
<< output << author_comment << output << author_comment
<< ""; << "";
} else { } else {
msgbuf << "HOST NOTIFICATION: " msgbuf << "HOST NOTIFICATION: "
<< user->GetName() << ";" << user->GetName() << ";"
<< host->GetName() << ";" << host->GetName() << ";"
<< notification_type_str << " " << notification_type_str << " "
<< "(" << Host::StateToString(host->GetState()) << ");" << "(" << Host::StateToString(host->GetState()) << ");"
<< check_command << ";" << check_command << ";"
<< output << author_comment << output << author_comment
<< ""; << "";
} }
AddLogHistory(checkable, msgbuf.str(), LogEntryTypeHostNotification); AddLogHistory(checkable, msgbuf.str(), LogEntryTypeHostNotification);
@ -1199,17 +1199,17 @@ void DbEvents::AddFlappingChangedLogHistory(const Checkable::Ptr& checkable)
if (service) { if (service) {
msgbuf << "SERVICE FLAPPING ALERT: " msgbuf << "SERVICE FLAPPING ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< service->GetShortName() << ";" << service->GetShortName() << ";"
<< flapping_state_str << "; " << flapping_state_str << "; "
<< flapping_output << flapping_output
<< ""; << "";
} else { } else {
msgbuf << "HOST FLAPPING ALERT: " msgbuf << "HOST FLAPPING ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< flapping_state_str << "; " << flapping_state_str << "; "
<< flapping_output << flapping_output
<< ""; << "";
} }
AddLogHistory(checkable, msgbuf.str(), LogEntryTypeInfoMessage); AddLogHistory(checkable, msgbuf.str(), LogEntryTypeInfoMessage);
@ -1231,17 +1231,17 @@ void DbEvents::AddEnableFlappingChangedLogHistory(const Checkable::Ptr& checkabl
if (service) { if (service) {
msgbuf << "SERVICE FLAPPING ALERT: " msgbuf << "SERVICE FLAPPING ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< service->GetShortName() << ";" << service->GetShortName() << ";"
<< flapping_state_str << "; " << flapping_state_str << "; "
<< flapping_output << flapping_output
<< ""; << "";
} else { } else {
msgbuf << "HOST FLAPPING ALERT: " msgbuf << "HOST FLAPPING ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< flapping_state_str << "; " << flapping_state_str << "; "
<< flapping_output << flapping_output
<< ""; << "";
} }
AddLogHistory(checkable, msgbuf.str(), LogEntryTypeInfoMessage); AddLogHistory(checkable, msgbuf.str(), LogEntryTypeInfoMessage);
@ -1250,7 +1250,7 @@ void DbEvents::AddEnableFlappingChangedLogHistory(const Checkable::Ptr& checkabl
void DbEvents::AddLogHistory(const Checkable::Ptr& checkable, String buffer, LogEntryType type) void DbEvents::AddLogHistory(const Checkable::Ptr& checkable, String buffer, LogEntryType type)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add log entry history for '" << checkable->GetName() << "'"; << "add log entry history for '" << checkable->GetName() << "'";
double now = Utility::GetTime(); double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now); std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
@ -1284,7 +1284,7 @@ void DbEvents::AddLogHistory(const Checkable::Ptr& checkable, String buffer, Log
void DbEvents::AddFlappingChangedHistory(const Checkable::Ptr& checkable) void DbEvents::AddFlappingChangedHistory(const Checkable::Ptr& checkable)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add flapping history for '" << checkable->GetName() << "'"; << "add flapping history for '" << checkable->GetName() << "'";
double now = Utility::GetTime(); double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now); std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
@ -1331,7 +1331,7 @@ void DbEvents::AddFlappingChangedHistory(const Checkable::Ptr& checkable)
void DbEvents::AddEnableFlappingChangedHistory(const Checkable::Ptr& checkable) void DbEvents::AddEnableFlappingChangedHistory(const Checkable::Ptr& checkable)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add flapping history for '" << checkable->GetName() << "'"; << "add flapping history for '" << checkable->GetName() << "'";
double now = Utility::GetTime(); double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now); std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
@ -1381,7 +1381,7 @@ void DbEvents::AddCheckableCheckHistory(const Checkable::Ptr& checkable, const C
return; return;
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add checkable check history for '" << checkable->GetName() << "'"; << "add checkable check history for '" << checkable->GetName() << "'";
Host::Ptr host; Host::Ptr host;
Service::Ptr service; Service::Ptr service;
@ -1446,7 +1446,7 @@ void DbEvents::AddCheckableCheckHistory(const Checkable::Ptr& checkable, const C
void DbEvents::AddEventHandlerHistory(const Checkable::Ptr& checkable) void DbEvents::AddEventHandlerHistory(const Checkable::Ptr& checkable)
{ {
Log(LogDebug, "DbEvents") Log(LogDebug, "DbEvents")
<< "add eventhandler history for '" << checkable->GetName() << "'"; << "add eventhandler history for '" << checkable->GetName() << "'";
double now = Utility::GetTime(); double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now); std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);

Some files were not shown because too many files have changed in this diff Show More