string master_host, master_port;
GetMasterHostPort(out master_host, out master_port);
- args += " --master_host " + master_host
- + "," + master_port;
+ args += " --master_host " + master_host + "," + master_port;
foreach (ListViewItem lvi in lvwEndpoints.Items) {
args += " --endpoint " + lvi.SubItems[0].Text.Trim();
- if (lvi.SubItems.Count > 1) {
- args += "," + lvi.SubItems[1].Text.Trim()
- + "," + lvi.SubItems[2].Text.Trim();
- }
+ if (lvi.SubItems.Count > 1)
+ args += "," + lvi.SubItems[1].Text.Trim() + "," + lvi.SubItems[2].Text.Trim();
}
});
#include "i2tcl.hpp"
%}
-%typemap(in,numinputs=0) Tcl_Interp *interp {
+%typemap(in,numinputs=0) Tcl_Interp *interp {
$1 = interp;
}
autoindex = Convert::ToLong(argv[2]);
} catch (const std::invalid_argument&) {
Log(LogCritical, "icinga-app")
- << "Invalid index for --autocomplete: " << argv[2];
+ << "Invalid index for --autocomplete: " << argv[2];
return EXIT_FAILURE;
}
("library,l", po::value<std::vector<std::string> >(), "load a library")
("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"
- "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");
po::options_description hiddenDesc("Hidden options");
try {
CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
- vm, cmdname, command, autocomplete);
+ vm, cmdname, command, autocomplete);
} catch (const std::exception& ex) {
Log(LogCritical, "icinga-app")
- << "Error while parsing command-line options: " << ex.what();
+ << "Error while parsing command-line options: " << ex.what();
return EXIT_FAILURE;
}
(void) Loader::LoadExtensionLibrary(libraryName);
} catch (const std::exception& ex) {
Log(LogCritical, "icinga-app")
- << "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex);
+ << "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex);
return EXIT_FAILURE;
}
}
- }
+ }
if (!command || vm.count("help") || vm.count("version")) {
String appName;
appName = appName.SubStr(3, appName.GetLength() - 3);
std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
- << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
- << Application::GetAppVersion()
+ << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
+ << Application::GetAppVersion()
#ifdef I2_DEBUG
- << "; debug"
+ << "; debug"
#endif /* I2_DEBUG */
- << ConsoleColorTag(Console_Normal)
- << ")" << std::endl << std::endl;
+ << ConsoleColorTag(Console_Normal)
+ << ")" << std::endl << std::endl;
if ((!command || vm.count("help")) && !vm.count("version")) {
std::cout << "Usage:" << std::endl
- << " " << Utility::BaseName(argv[0]) << " ";
+ << " " << Utility::BaseName(argv[0]) << " ";
if (cmdname.IsEmpty())
std::cout << "<command>";
if (command) {
std::cout << std::endl
- << command->GetDescription() << std::endl;
+ << command->GetDescription() << std::endl;
}
}
if (autocomplete) {
CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
- &GlobalArgumentCompletion, true, autoindex);
+ &GlobalArgumentCompletion, true, autoindex);
rc = 0;
} else if (command) {
Logger::DisableTimestamp(true);
if (!gr) {
if (errno == 0) {
Log(LogCritical, "cli")
- << "Invalid group specified: " << group;
+ << "Invalid group specified: " << group;
return EXIT_FAILURE;
} else {
Log(LogCritical, "cli")
- << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return EXIT_FAILURE;
}
}
if (getgid() != gr->gr_gid) {
if (!vm.count("reload-internal") && setgroups(0, nullptr) < 0) {
Log(LogCritical, "cli")
- << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
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;
}
if (setgid(gr->gr_gid) < 0) {
Log(LogCritical, "cli")
- << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return EXIT_FAILURE;
}
}
if (!pw) {
if (errno == 0) {
Log(LogCritical, "cli")
- << "Invalid user specified: " << user;
+ << "Invalid user specified: " << user;
return EXIT_FAILURE;
} else {
Log(LogCritical, "cli")
- << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return EXIT_FAILURE;
}
}
if (getuid() != pw->pw_uid) {
if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
Log(LogCritical, "cli")
- << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
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;
}
if (setuid(pw->pw_uid) < 0) {
Log(LogCritical, "cli")
- << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
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;
}
}
if (static_cast<int>(args.size()) < command->GetMinArguments()) {
Log(LogCritical, "cli")
- << "Too few arguments. Command needs at least " << command->GetMinArguments()
- << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
+ << "Too few arguments. Command needs at least " << command->GetMinArguments()
+ << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
return EXIT_FAILURE;
}
if (command->GetMaxArguments() >= 0 && static_cast<int>(args.size()) > command->GetMaxArguments()) {
Log(LogCritical, "cli")
- << "Too many arguments. At most " << command->GetMaxArguments()
- << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
+ << "Too many arguments. At most " << command->GetMaxArguments()
+ << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
return EXIT_FAILURE;
}
l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
if ((dwCurrentState == SERVICE_RUNNING) ||
- (dwCurrentState == SERVICE_STOPPED))
+ (dwCurrentState == SERVICE_STOPPED))
l_SvcStatus.dwCheckPoint = 0;
else
l_SvcStatus.dwCheckPoint = dwCheckPoint++;
Url::Ptr ConnectForm::GetUrl(void) const
{
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());
}
attrs.push_back("__name");
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)
names.push_back(objectName);
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)
if (fileLimit != 0) {
if (fileLimit < GetDefaultRLimitFiles()) {
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();
}
if (processLimit != 0) {
if (processLimit < GetDefaultRLimitProcesses()) {
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();
}
if (stackLimit != 0) {
if (stackLimit < GetDefaultRLimitStack()) {
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();
}
if (std::fabs(timeDiff) > 15) {
/* We made a significant jump in time. */
Log(LogInformation, "Application")
- << "We jumped "
- << (timeDiff < 0 ? "forward" : "backward")
- << " in time: " << std::fabs(timeDiff) << " seconds";
+ << "We jumped "
+ << (timeDiff < 0 ? "forward" : "backward")
+ << " in time: " << std::fabs(timeDiff) << " seconds";
Timer::AdjustTimers(-timeDiff);
}
char buffer[MAXPATHLEN];
if (!getcwd(buffer, sizeof(buffer))) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("getcwd")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("getcwd")
+ << boost::errinfo_errno(errno));
}
String workingDirectory = buffer;
if (!realpath(executablePath.CStr(), buffer)) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("realpath")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(executablePath));
+ << boost::errinfo_api_function("realpath")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(executablePath));
}
return buffer;
if (!GetModuleFileName(nullptr, FullExePath, sizeof(FullExePath)))
BOOST_THROW_EXCEPTION(win32_error()
- << boost::errinfo_api_function("GetModuleFileName")
- << errinfo_win32_error(GetLastError()));
+ << boost::errinfo_api_function("GetModuleFileName")
+ << errinfo_win32_error(GetLastError()));
return FullExePath;
#endif /* _WIN32 */
os << " Application version: " << GetAppVersion() << "\n";
os << " Installation root: " << GetPrefixDir() << "\n"
- << " Sysconf directory: " << GetSysconfDir() << "\n"
- << " Run directory: " << GetRunDir() << "\n"
- << " Local state directory: " << GetLocalStateDir() << "\n"
- << " Package data directory: " << GetPkgDataDir() << "\n"
- << " State path: " << GetStatePath() << "\n"
- << " Modified attributes path: " << GetModAttrPath() << "\n"
- << " Objects path: " << GetObjectsPath() << "\n"
- << " Vars path: " << GetVarsPath() << "\n"
- << " PID path: " << GetPidPath() << "\n";
+ << " Sysconf directory: " << GetSysconfDir() << "\n"
+ << " Run directory: " << GetRunDir() << "\n"
+ << " Local state directory: " << GetLocalStateDir() << "\n"
+ << " Package data directory: " << GetPkgDataDir() << "\n"
+ << " State path: " << GetStatePath() << "\n"
+ << " Modified attributes path: " << GetModAttrPath() << "\n"
+ << " Objects path: " << GetObjectsPath() << "\n"
+ << " Vars path: " << GetVarsPath() << "\n"
+ << " PID path: " << GetPidPath() << "\n";
os << "\n"
- << "System information:" << "\n"
- << " Platform: " << Utility::GetPlatformName() << "\n"
- << " Platform version: " << Utility::GetPlatformVersion() << "\n"
- << " Kernel: " << Utility::GetPlatformKernel() << "\n"
- << " Kernel version: " << Utility::GetPlatformKernelVersion() << "\n"
- << " Architecture: " << Utility::GetPlatformArchitecture() << "\n";
+ << "System information:" << "\n"
+ << " Platform: " << Utility::GetPlatformName() << "\n"
+ << " Platform version: " << Utility::GetPlatformVersion() << "\n"
+ << " Kernel: " << Utility::GetPlatformKernel() << "\n"
+ << " Kernel version: " << Utility::GetPlatformKernelVersion() << "\n"
+ << " Architecture: " << Utility::GetPlatformArchitecture() << "\n";
os << "\n"
- << "Build information:" << "\n"
- << " Compiler: " << ScriptGlobal::Get("BuildCompilerName") << " " << ScriptGlobal::Get("BuildCompilerVersion") << "\n"
- << " Build host: " << ScriptGlobal::Get("BuildHostName") << "\n";
+ << "Build information:" << "\n"
+ << " Compiler: " << ScriptGlobal::Get("BuildCompilerName") << " " << ScriptGlobal::Get("BuildCompilerVersion") << "\n"
+ << " Build host: " << ScriptGlobal::Get("BuildHostName") << "\n";
}
/**
void Application::DisplayBugMessage(std::ostream& os)
{
os << "***" << "\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"
- << "* information that might be useful in order to reproduce this problem." << "\n"
- << "***" << "\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"
+ << "* information that might be useful in order to reproduce this problem." << "\n"
+ << "***" << "\n";
}
String Application::GetCrashReportFilename(void)
if (pid < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("fork")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("fork")
+ << boost::errinfo_errno(errno));
}
if (pid == 0) {
if (fd < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("open")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(filename));
+ << boost::errinfo_api_function("open")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(filename));
}
if (fd != 1) {
int status;
if (waitpid(pid, &status, 0) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("waitpid")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("waitpid")
+ << boost::errinfo_errno(errno));
}
#ifdef __linux__
#endif /* _WIN32 */
std::cerr << "Caught SIGABRT." << std::endl
- << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << std::endl
- << std::endl;
+ << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << std::endl
+ << std::endl;
String fname = GetCrashReportFilename();
String dirName = Utility::DirName(fname);
ofs.open(fname.CStr());
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);
ofs.open(fname.CStr());
ofs << "Caught unhandled exception." << "\n"
- << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n"
- << "\n";
+ << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n"
+ << "\n";
DisplayInfoMessage(ofs);
RethrowUncaughtException();
} catch (const std::exception& ex) {
Log(LogCritical, "Application")
- << DiagnosticInformation(ex, false) << "\n"
- << "\n"
- << "Additional information is available in '" << fname << "'" << "\n";
+ << DiagnosticInformation(ex, false) << "\n"
+ << "\n"
+ << "Additional information is available in '" << fname << "'" << "\n";
ofs << "\n"
- << DiagnosticInformation(ex)
- << "\n";
+ << DiagnosticInformation(ex)
+ << "\n";
}
DisplayBugMessage(ofs);
ofs.open(fname.CStr());
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);
ofs << "Caught unhandled SEH exception." << "\n"
- << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n"
- << "\n";
+ << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n"
+ << "\n";
StackTrace trace(exi);
ofs << "Stacktrace:" << "\n";
UpdatePidFile(GetPidPath());
} catch (const std::exception&) {
Log(LogCritical, "Application")
- << "Cannot update PID file '" << GetPidPath() << "'. Aborting.";
+ << "Cannot update PID file '" << GetPidPath() << "'. Aborting.";
return EXIT_FAILURE;
}
if (!m_PidFile) {
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 + "'"));
}
if (ftruncate(fd, 0) < 0) {
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::errinfo_api_function("ftruncate")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("ftruncate")
+ << boost::errinfo_errno(errno));
}
#endif /* _WIN32 */
int error = errno;
fclose(pidfile);
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("fcntl")
- << boost::errinfo_errno(error));
+ << boost::errinfo_api_function("fcntl")
+ << boost::errinfo_errno(error));
}
if (lock.l_type == F_UNLCK) {
private:
static Application::Ptr m_Instance; /**< The application instance. */
- static bool m_ShuttingDown; /**< Whether the application is in the process of
- shutting down. */
+ static bool m_ShuttingDown; /**< Whether the application is in the process of shutting down. */
static bool m_RequestRestart; /**< A restart was requested through SIGHUP */
- static pid_t m_ReloadProcess; /**< The PID of a subprocess doing a reload,
- only valid when l_Restarting==true */
+ static pid_t m_ReloadProcess; /**< The PID of a subprocess doing a reload, only valid when l_Restarting==true */
static bool m_RequestReopenLogs; /**< Whether we should re-open log files. */
static int m_ArgC; /**< The number of command-line arguments. */
/**
* Makes a deep clone of an array
* and its elements.
- *
+ *
* @returns a copy of the array.
*/
Object::Ptr Array::Clone(void) const
{ }
Array(std::initializer_list<Value> init)
- : m_Data(init)
+ : m_Data(init)
{ }
~Array(void)
String Base64::Decode(const String& input)
{
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_push(bio64, biomem);
BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);
void ConfigObject::DumpObjects(const String& filename, int attributeTypes)
{
Log(LogInformation, "ConfigObject")
- << "Dumping program state to file '" << filename << "'";
+ << "Dumping program state to file '" << filename << "'";
std::fstream fp;
String tempFilename = Utility::CreateTempFile(filename + ".XXXXXX", 0600, fp);
if (rename(tempFilename.CStr(), filename.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempFilename));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempFilename));
}
}
#ifdef I2_DEBUG
Log(LogDebug, "ConfigObject")
- << "Restoring object '" << name << "' of type '" << type << "'.";
+ << "Restoring object '" << name << "' of type '" << type << "'.";
#endif /* I2_DEBUG */
Dictionary::Ptr update = persistentObject->Get("update");
Deserialize(object, update, false, attributeTypes);
return;
Log(LogInformation, "ConfigObject")
- << "Restoring program state from file '" << filename << "'";
+ << "Restoring program state from file '" << filename << "'";
std::fstream fp;
fp.open(filename.CStr(), std::ios_base::in);
}
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)
Type *type = dynamic_cast<Type *>(this);
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()),
- object->GetDebugInfo()));
+ Convert::ToString(it->second->GetDebugInfo()) + "), new declaration: " + Convert::ToString(object->GetDebugInfo()),
+ object->GetDebugInfo()));
}
m_ObjectMap[name] = object;
}
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 << "{";
}
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)
fp << "template ";
}
ConfigIdentifier::ConfigIdentifier(const String& identifier)
- : m_Name(identifier)
+ : m_Name(identifier)
{ }
String ConfigIdentifier::GetName(void) const
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 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 EmitRaw(std::ostream& fp, const String& val);
static void EmitIndent(std::ostream& fp, int indentLevel);
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,
- 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 EmitFunctionCall(std::ostream& fp, const String& name, const Array::Ptr& arguments);
std::ostream& icinga::operator<<(std::ostream& out, const DebugInfo& val)
{
out << "in " << val.Path << ": "
- << val.FirstLine << ":" << val.FirstColumn
- << "-"
- << val.LastLine << ":" << val.LastColumn;
+ << val.FirstLine << ":" << val.FirstColumn
+ << "-"
+ << val.LastLine << ":" << val.LastColumn;
return out;
}
REGISTER_TYPE_WITH_PROTOTYPE(Function, Function::GetPrototype());
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)
{
SetName(name, true);
template<typename F>
Function(const String& name, F function, const std::vector<String>& args = std::vector<String>(),
- bool side_effect_free = false, bool deprecated = false)
- : Function(name, WrapFunction(function), args, side_effect_free, deprecated)
+ bool side_effect_free = false, bool deprecated = false)
+ : Function(name, WrapFunction(function), args, side_effect_free, deprecated)
{ }
Value Invoke(const std::vector<Value>& arguments = std::vector<Value>());
Callback m_Callback;
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) \
public:
template <typename FuncType, int Arity>
- auto operator() (FuncType f, const std::vector<Value>& args)
- -> decltype(Invoke(f, args, BuildIndices<Arity>{}))
+ auto operator() (FuncType f, const std::vector<Value>& args) -> decltype(Invoke(f, args, BuildIndices<Arity>{}))
{
return Invoke(f, args, BuildIndices<Arity>{});
}
template<typename FuncType>
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::function<Value (const std::vector<Value>&)>>::type
+ 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
WrapFunction(FuncType function)
{
return [function](const std::vector<Value>& arguments) {
#endif /* _WIN32 */
Log(LogNotice, "Loader")
- << "Loading library '" << path << "'";
+ << "Loading library '" << path << "'";
#ifdef _WIN32
HMODULE hModule = LoadLibrary(path.CStr());
if (!hModule) {
BOOST_THROW_EXCEPTION(win32_error()
- << boost::errinfo_api_function("LoadLibrary")
- << errinfo_win32_error(GetLastError())
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("LoadLibrary")
+ << errinfo_win32_error(GetLastError())
+ << boost::errinfo_file_name(path));
}
#else /* _WIN32 */
void *hModule = dlopen(path.CStr(), RTLD_NOW | RTLD_GLOBAL);
{
public:
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
* @param message The message.
*/
void icinga::IcingaLog(LogSeverity severity, const String& facility,
- const String& message)
+ const String& message)
{
LogEntry entry;
entry.Timestamp = Utility::GetTime();
continue;
Log(LogInformation, "TypeInfo")
- << kv.second << " " << kv.first << " objects";
+ << kv.second << " " << kv.first << " objects";
kv.second = 0;
}
{ }
PerfdataValue::PerfdataValue(String label, double value, bool counter,
- const String& unit, const Value& warn, const Value& crit, const Value& min,
- const Value& max)
+ const String& unit, const Value& warn, const Value& crit, const Value& min,
+ const Value& max)
{
SetLabel(label, true);
SetValue(value, true);
else {
if (tokens.size() > index && tokens[index] != "")
Log(LogDebug, "PerfdataValue")
- << "Ignoring unsupported perfdata " << description << " range, value: '" << tokens[index] << "'.";
+ << "Ignoring unsupported perfdata " << description << " range, value: '" << tokens[index] << "'.";
return Empty;
}
}
PerfdataValue(void);
PerfdataValue(String label, double value, bool counter = false, const String& unit = "",
- const Value& warn = Empty, const Value& crit = Empty,
- const Value& min = Empty, const Value& max = Empty);
+ const Value& warn = Empty, const Value& crit = Empty,
+ const Value& min = Empty, const Value& max = Empty);
static PerfdataValue::Ptr Parse(const String& perfdata);
String Format(void) const;
private:
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);
};
}
if (send(l_ProcessControlFD, jresponse.CStr(), jresponse.GetLength(), 0) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("send")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("send")
+ << boost::errinfo_errno(errno));
}
}
int controlFDs[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, controlFDs) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("socketpair")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("socketpair")
+ << boost::errinfo_errno(errno));
}
pid_t pid = fork();
if (pid < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("fork")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("fork")
+ << boost::errinfo_errno(errno));
}
if (pid == 0) {
# endif /* HAVE_PIPE2 */
if (pipe(l_EventFDs[tid]) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("pipe")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("pipe")
+ << boost::errinfo_errno(errno));
}
Utility::SetCloExec(l_EventFDs[tid][0]);
#ifdef _WIN32
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;
sprintf(pipeName, "\\\\.\\Pipe\\OverlappedPipe.%d.%d", (int)GetCurrentProcessId(), (int)currentIndex);
*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)
return FALSE;
HANDLE outWritePipeDup;
if (!DuplicateHandle(GetCurrentProcess(), outWritePipe, GetCurrentProcess(),
- &outWritePipeDup, 0, TRUE, DUPLICATE_SAME_ACCESS))
+ &outWritePipeDup, 0, TRUE, DUPLICATE_SAME_ACCESS))
BOOST_THROW_EXCEPTION(win32_error()
<< boost::errinfo_api_function("DuplicateHandle")
<< errinfo_win32_error(GetLastError()));
rgHandles[2] = GetStdHandle(STD_INPUT_HANDLE);
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::errinfo_api_function("UpdateProcThreadAttribute")
<< errinfo_win32_error(GetLastError()));
envp[offset] = '\0';
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();
CloseHandle(outWritePipe);
CloseHandle(outWritePipeDup);
m_PID = pi.dwProcessId;
Log(LogNotice, "Process")
- << "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID;
+ << "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID;
#else /* _WIN32 */
int outfds[2];
#endif /* HAVE_PIPE2 */
if (pipe(outfds) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("pipe")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("pipe")
+ << boost::errinfo_errno(errno));
}
Utility::SetCloExec(outfds[0]);
}
Log(LogNotice, "Process")
- << "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID;
+ << "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID;
(void)close(outfds[1]);
if (timeout < Utility::GetTime()) {
Log(LogWarning, "Process")
- << "Killing process group " << m_PID << " (" << PrettyPrintArguments(m_Arguments)
- << ") after timeout of " << m_Timeout << " seconds";
+ << "Killing process group " << m_PID << " (" << PrettyPrintArguments(m_Arguments)
+ << ") after timeout of " << m_Timeout << " seconds";
m_OutputStream << "<Timeout exceeded.>";
#ifdef _WIN32
int error = ProcessKill(-m_Process, SIGKILL);
if (error) {
Log(LogWarning, "Process")
- << "Couldn't kill the process group " << m_PID << " (" << PrettyPrintArguments(m_Arguments)
- << "): [errno " << error << "] " << strerror(error);
+ << "Couldn't kill the process group " << m_PID << " (" << PrettyPrintArguments(m_Arguments)
+ << "): [errno " << error << "] " << strerror(error);
could_not_kill = true;
}
#endif /* _WIN32 */
GetExitCodeProcess(m_Process, &exitcode);
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 */
int status, exitcode;
if (could_not_kill || m_PID == -1) {
exitcode = 128;
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)) {
exitcode = WEXITSTATUS(status);
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)) {
int signum = WTERMSIG(status);
const char *zsigname = strsignal(signum);
}
Log(LogWarning, "Process")
- << "PID " << m_PID << " was terminated by signal " << signame;
+ << "PID " << m_PID << " was terminated by signal " << signame;
std::ostringstream outputbuf;
outputbuf << "<Terminated by signal " << signame << ".>";
Array::Ptr result = new Array();
if ((start < end && increment <= 0) ||
- (start > end && increment >= 0))
+ (start > end && increment >= 0))
return result;
for (double i = start; (increment > 0 ? i < end : i > end); i += increment)
char service[NI_MAXSERV];
if (getnameinfo(address, len, host, sizeof(host), service,
- sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
+ sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
#ifndef _WIN32
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::errinfo_api_function("getnameinfo")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("getnameinfo")
+ << boost::errinfo_errno(errno));
#else /* _WIN32 */
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::errinfo_api_function("getnameinfo")
- << errinfo_win32_error(WSAGetLastError()));
+ << boost::errinfo_api_function("getnameinfo")
+ << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */
}
if (getsockname(GetFD(), (sockaddr *)&sin, &len) < 0) {
#ifndef _WIN32
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::errinfo_api_function("getsockname")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("getsockname")
+ << boost::errinfo_errno(errno));
#else /* _WIN32 */
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::errinfo_api_function("getsockname")
- << errinfo_win32_error(WSAGetLastError()));
+ << boost::errinfo_api_function("getsockname")
+ << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */
}
if (getpeername(GetFD(), (sockaddr *)&sin, &len) < 0) {
#ifndef _WIN32
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::errinfo_api_function("getpeername")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("getpeername")
+ << boost::errinfo_errno(errno));
#else /* _WIN32 */
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::errinfo_api_function("getpeername")
- << errinfo_win32_error(WSAGetLastError()));
+ << boost::errinfo_api_function("getpeername")
+ << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */
}
if (listen(GetFD(), SOMAXCONN) < 0) {
#ifndef _WIN32
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::errinfo_api_function("listen")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("listen")
+ << boost::errinfo_errno(errno));
#else /* _WIN32 */
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::errinfo_api_function("listen")
- << errinfo_win32_error(WSAGetLastError()));
+ << boost::errinfo_api_function("listen")
+ << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */
}
}
if (rc < 0) {
#ifndef _WIN32
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::errinfo_api_function("send")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("send")
+ << boost::errinfo_errno(errno));
#else /* _WIN32 */
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::errinfo_api_function("send")
- << errinfo_win32_error(WSAGetLastError()));
+ << boost::errinfo_api_function("send")
+ << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */
}
if (rc < 0) {
#ifndef _WIN32
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::errinfo_api_function("recv")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("recv")
+ << boost::errinfo_errno(errno));
#else /* _WIN32 */
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::errinfo_api_function("recv")
- << errinfo_win32_error(WSAGetLastError()));
+ << boost::errinfo_api_function("recv")
+ << errinfo_win32_error(WSAGetLastError()));
#endif /* _WIN32 */
}
if (rc < 0) {
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::errinfo_api_function("select")
- << errinfo_win32_error(WSAGetLastError()));
+ << boost::errinfo_api_function("select")
+ << errinfo_win32_error(WSAGetLastError()));
}
#else /* _WIN32 */
pollfd pfd;
if (rc < 0) {
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::errinfo_api_function("poll")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("poll")
+ << boost::errinfo_errno(errno));
}
#endif /* _WIN32 */
{
if (dumb_socketpair(s, 0) < 0)
BOOST_THROW_EXCEPTION(socket_error()
- << boost::errinfo_api_function("socketpair")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("socketpair")
+ << boost::errinfo_errno(errno));
}
event.Descriptor.EventInterface->OnEvent(event.REvents);
} catch (const std::exception& ex) {
Log(LogCritical, "SocketEvents")
- << "Exception thrown in socket I/O handler:\n"
- << DiagnosticInformation(ex);
+ << "Exception thrown in socket I/O handler:\n"
+ << DiagnosticInformation(ex);
} catch (...) {
Log(LogCritical, "SocketEvents", "Exception of unknown type thrown in socket I/O handler.");
}
event.Descriptor.EventInterface->OnEvent(event.REvents);
} catch (const std::exception& ex) {
Log(LogCritical, "SocketEvents")
- << "Exception thrown in socket I/O handler:\n"
- << DiagnosticInformation(ex);
+ << "Exception thrown in socket I/O handler:\n"
+ << DiagnosticInformation(ex);
} catch (...) {
Log(LogCritical, "SocketEvents", "Exception of unknown type thrown in socket I/O handler.");
}
#endif /* __linux__ */
else {
Log(LogWarning, "SocketEvents")
- << "Invalid event engine selected: " << eventEngine << " - Falling back to 'poll'";
+ << "Invalid event engine selected: " << eventEngine << " - Falling back to 'poll'";
eventEngine = "poll";
m_Count = 0;
while (StackWalk64(architecture, GetCurrentProcess(), GetCurrentThread(),
- &frame, exi->ContextRecord, nullptr, &SymFunctionTableAccess64,
- &SymGetModuleBase64, nullptr) && m_Count < sizeof(m_Frames) / sizeof(m_Frames[0])) {
+ &frame, exi->ContextRecord, nullptr, &SymFunctionTableAccess64,
+ &SymGetModuleBase64, nullptr) && m_Count < sizeof(m_Frames) / sizeof(m_Frames[0])) {
m_Frames[m_Count] = reinterpret_cast<void *>(frame.AddrPC.Offset);
m_Count++;
}
*
* @param fp The stream.
* @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.
*/
void StackTrace::Print(std::ostream& fp, int ignoreFrames) const
# endif /* HAVE_BACKTRACE_SYMBOLS */
#else /* _WIN32 */
for (int i = ignoreFrames + 1; i < m_Count; i++) {
- fp << "\t(" << i - ignoreFrames - 1 << "): "
- << Utility::GetSymbolName(m_Frames[i])
- << std::endl;
+ fp << "\t(" << i - ignoreFrames - 1 << "): " << Utility::GetSymbolName(m_Frames[i]) << std::endl;
}
#endif /* _WIN32 */
}
hints.ai_flags = AI_PASSIVE;
int rc = getaddrinfo(node.IsEmpty() ? nullptr : node.CStr(),
- service.CStr(), &hints, &result);
+ service.CStr(), &hints, &result);
if (rc != 0) {
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::errinfo_api_function("getaddrinfo")
- << errinfo_getaddrinfo_error(rc));
+ << boost::errinfo_api_function("getaddrinfo")
+ << errinfo_getaddrinfo_error(rc));
}
int fd = INVALID_SOCKET;
fd = socket(info->ai_family, info->ai_socktype, info->ai_protocol);
if (fd == INVALID_SOCKET) {
-#ifdef _WIN32
+#ifdef _WIN32
error = WSAGetLastError();
#else /* _WIN32 */
error = errno;
if (GetFD() == INVALID_SOCKET) {
Log(LogCritical, "TcpSocket")
- << "Invalid socket: " << Utility::FormatErrorNumber(error);
+ << "Invalid socket: " << Utility::FormatErrorNumber(error);
#ifndef _WIN32
BOOST_THROW_EXCEPTION(socket_error()
- << boost::errinfo_api_function(func)
- << boost::errinfo_errno(error));
+ << boost::errinfo_api_function(func)
+ << boost::errinfo_errno(error));
#else /* _WIN32 */
BOOST_THROW_EXCEPTION(socket_error()
- << boost::errinfo_api_function(func)
- << errinfo_win32_error(error));
+ << boost::errinfo_api_function(func)
+ << errinfo_win32_error(error));
#endif /* _WIN32 */
}
}
if (rc != 0) {
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::errinfo_api_function("getaddrinfo")
- << errinfo_getaddrinfo_error(rc));
+ << boost::errinfo_api_function("getaddrinfo")
+ << errinfo_getaddrinfo_error(rc));
}
SOCKET fd = INVALID_SOCKET;
error = errno;
#endif /* _WIN32 */
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);
if (GetFD() == INVALID_SOCKET) {
Log(LogCritical, "TcpSocket")
- << "Invalid socket: " << Utility::FormatErrorNumber(error);
+ << "Invalid socket: " << Utility::FormatErrorNumber(error);
#ifndef _WIN32
BOOST_THROW_EXCEPTION(socket_error()
- << boost::errinfo_api_function(func)
- << boost::errinfo_errno(error));
+ << boost::errinfo_api_function(func)
+ << boost::errinfo_errno(error));
#else /* _WIN32 */
BOOST_THROW_EXCEPTION(socket_error()
- << boost::errinfo_api_function(func)
- << errinfo_win32_error(error));
+ << boost::errinfo_api_function(func)
+ << errinfo_win32_error(error));
#endif /* _WIN32 */
}
}
wi.Callback();
} catch (const std::exception& ex) {
Log(LogCritical, "ThreadPool")
- << "Exception thrown in event handler:\n"
- << DiagnosticInformation(ex);
+ << "Exception thrown in event handler:\n"
+ << DiagnosticInformation(ex);
} catch (...) {
Log(LogCritical, "ThreadPool", "Exception of unknown type thrown in event handler.");
}
(void) getrusage(RUSAGE_THREAD, &usage_end);
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) +
- (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);
if (et - st > 0.5) {
Log(LogWarning, "ThreadPool")
# 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
- << "Event call took " << (et - st) << "s";
+ << "Event call took " << (et - st) << "s";
# endif /* RUSAGE_THREAD */
}
#endif /* I2_DEBUG */
if (tthreads != 0) {
Log(LogNotice, "ThreadPool")
- << "Thread pool; current: " << alive << "; adjustment: " << tthreads;
+ << "Thread pool; current: " << alive << "; adjustment: " << tthreads;
}
for (int i = 0; i < -tthreads; i++)
lastStats = now;
Log(LogNotice, "ThreadPool")
- << "Pool #" << m_ID << ": Pending tasks: " << total_pending << "; Average latency: "
- << (long)(total_avg_latency * 1000 / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "ms"
- << "; Threads: " << total_alive
- << "; Pool utilization: " << (total_utilization / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "%";
+ << "Pool #" << m_ID << ": Pending tasks: " << total_pending << "; Average latency: "
+ << (long)(total_avg_latency * 1000 / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "ms"
+ << "; Threads: " << total_alive
+ << "; Pool utilization: " << (total_utilization / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "%";
}
}
}
void Timer::Uninitialize(void)
{
- {
- boost::mutex::scoped_lock lock(l_TimerMutex);
- l_StopTimerThread = true;
- l_TimerCV.notify_all();
- }
-
- if (l_TimerThread.joinable())
- l_TimerThread.join();
+ {
+ boost::mutex::scoped_lock lock(l_TimerMutex);
+ l_StopTimerThread = true;
+ l_TimerCV.notify_all();
+ }
+
+ if (l_TimerThread.joinable())
+ l_TimerThread.join();
}
/**
*
* @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
- * 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)
{
for (Timer *timer : idx) {
if (std::fabs(now - (timer->m_Next + adjustment)) <
- std::fabs(now - timer->m_Next)) {
+ std::fabs(now - timer->m_Next)) {
timer->m_Next += adjustment;
timers.push_back(timer);
}
*/
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),
- 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_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)
{
std::ostringstream msgbuf;
char errbuf[120];
{
if (m_ErrorOccurred) {
BOOST_THROW_EXCEPTION(openssl_error()
- << boost::errinfo_api_function("TlsStream::OnEvent")
- << errinfo_openssl_error(m_ErrorCode));
+ << boost::errinfo_api_function("TlsStream::OnEvent")
+ << errinfo_openssl_error(m_ErrorCode));
}
}
if (!pubkey.IsEmpty()) {
if (!SSL_CTX_use_certificate_chain_file(sslContext.get(), pubkey.CStr())) {
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::errinfo_api_function("SSL_CTX_use_certificate_chain_file")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(pubkey));
+ << boost::errinfo_api_function("SSL_CTX_use_certificate_chain_file")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(pubkey));
}
}
if (!privkey.IsEmpty()) {
if (!SSL_CTX_use_PrivateKey_file(sslContext.get(), privkey.CStr(), SSL_FILETYPE_PEM)) {
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::errinfo_api_function("SSL_CTX_use_PrivateKey_file")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(privkey));
+ << boost::errinfo_api_function("SSL_CTX_use_PrivateKey_file")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(privkey));
}
if (!SSL_CTX_check_private_key(sslContext.get())) {
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::errinfo_api_function("SSL_CTX_check_private_key")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SSL_CTX_check_private_key")
+ << errinfo_openssl_error(ERR_peek_error()));
}
}
if (!cakey.IsEmpty()) {
if (!SSL_CTX_load_verify_locations(sslContext.get(), cakey.CStr(), nullptr)) {
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::errinfo_api_function("SSL_CTX_load_verify_locations")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(cakey));
+ << boost::errinfo_api_function("SSL_CTX_load_verify_locations")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(cakey));
}
STACK_OF(X509_NAME) *cert_names;
cert_names = SSL_load_client_CA_file(cakey.CStr());
if (!cert_names) {
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::errinfo_api_function("SSL_load_client_CA_file")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(cakey));
+ << boost::errinfo_api_function("SSL_load_client_CA_file")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(cakey));
}
SSL_CTX_set_client_CA_list(sslContext.get(), cert_names);
if (SSL_CTX_set_cipher_list(context.get(), cipherList.CStr()) == 0) {
Log(LogCritical, "SSL")
- << "Cipher list '"
- << cipherList
- << "' does not specify any usable ciphers: "
- << ERR_peek_error() << ", \""
- << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
+ << "Cipher list '"
+ << cipherList
+ << "' does not specify any usable ciphers: "
+ << ERR_peek_error() << ", \""
+ << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
BOOST_THROW_EXCEPTION(openssl_error()
- << boost::errinfo_api_function("SSL_CTX_set_cipher_list")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SSL_CTX_set_cipher_list")
+ << errinfo_openssl_error(ERR_peek_error()));
}
}
if (!lookup) {
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::errinfo_api_function("X509_STORE_add_lookup")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("X509_STORE_add_lookup")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (X509_LOOKUP_load_file(lookup, crlPath.CStr(), X509_FILETYPE_PEM) != 1) {
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::errinfo_api_function("X509_LOOKUP_load_file")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(crlPath));
+ << boost::errinfo_api_function("X509_LOOKUP_load_file")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(crlPath));
}
X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
if (rc == -1) {
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::errinfo_api_function("X509_NAME_get_text_by_NID")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("X509_NAME_get_text_by_NID")
+ << errinfo_openssl_error(ERR_peek_error()));
}
return buffer;
if (!fpcert) {
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::errinfo_api_function("BIO_new")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("BIO_new")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (BIO_read_filename(fpcert, pemfile.CStr()) < 0) {
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::errinfo_api_function("BIO_read_filename")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(pemfile));
+ << boost::errinfo_api_function("BIO_read_filename")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(pemfile));
}
cert = PEM_read_bio_X509_AUX(fpcert, nullptr, nullptr, nullptr);
if (!cert) {
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::errinfo_api_function("PEM_read_bio_X509_AUX")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(pemfile));
+ << boost::errinfo_api_function("PEM_read_bio_X509_AUX")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(pemfile));
}
BIO_free(fpcert);
EC_KEY_free(eckey);
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::errinfo_api_function("EC_KEY_generate_key")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("EC_KEY_generate_key")
+ << errinfo_openssl_error(ERR_peek_error()));
}
EVP_PKEY *key = EVP_PKEY_new();
EC_KEY_free(eckey);
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::errinfo_api_function("EC_KEY_generate_key")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("EC_KEY_generate_key")
+ << errinfo_openssl_error(ERR_peek_error()));
}
Log(LogInformation, "base")
- << "Writing private key to '" << keyfile << "'.";
+ << "Writing private key to '" << keyfile << "'.";
BIO *bio = BIO_new_file(const_cast<char *>(keyfile.CStr()), "w");
EC_KEY_free(eckey);
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::errinfo_api_function("BIO_new_file")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(keyfile));
+ << boost::errinfo_api_function("BIO_new_file")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(keyfile));
}
if (!PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, 0, nullptr)) {
BIO_free(bio);
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::errinfo_api_function("PEM_write_bio_PrivateKey")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(keyfile));
+ << boost::errinfo_api_function("PEM_write_bio_PrivateKey")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(keyfile));
}
BIO_free(bio);
X509_NAME_free(subject);
Log(LogInformation, "base")
- << "Writing X509 certificate to '" << certfile << "'.";
+ << "Writing X509 certificate to '" << certfile << "'.";
bio = BIO_new_file(const_cast<char *>(certfile.CStr()), "w");
if (!bio) {
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::errinfo_api_function("BIO_new_file")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(certfile));
+ << boost::errinfo_api_function("BIO_new_file")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(certfile));
}
if (!PEM_write_bio_X509(bio, cert.get())) {
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::errinfo_api_function("PEM_write_bio_X509")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(certfile));
+ << boost::errinfo_api_function("PEM_write_bio_X509")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(certfile));
}
BIO_free(bio);
X509_REQ_sign(req, key, EVP_sha256());
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");
if (!bio) {
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::errinfo_api_function("BIO_new_file")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(csrfile));
+ << boost::errinfo_api_function("BIO_new_file")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(csrfile));
}
if (!PEM_write_bio_X509_REQ(bio, req)) {
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::errinfo_api_function("PEM_write_bio_X509")
- << errinfo_openssl_error(ERR_peek_error())
- << boost::errinfo_file_name(csrfile));
+ << boost::errinfo_api_function("PEM_write_bio_X509")
+ << errinfo_openssl_error(ERR_peek_error())
+ << boost::errinfo_file_name(csrfile));
}
BIO_free(bio);
if (!SHA1_Init(&context)) {
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::errinfo_api_function("SHA1_Init")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA1_Init")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (!SHA1_Update(&context, (unsigned char*)id.CStr(), id.GetLength())) {
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::errinfo_api_function("SHA1_Update")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA1_Update")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (!SHA1_Final(digest, &context)) {
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::errinfo_api_function("SHA1_Final")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA1_Final")
+ << errinfo_openssl_error(ERR_peek_error()));
}
BIGNUM *bn = BN_new();
if (!cakeybio) {
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>();
}
if (!privkey) {
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>();
}
{
unsigned char digest[SHA_DIGEST_LENGTH];
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];
for (int i = 0; i < SHA_DIGEST_LENGTH; i++)
if (!SHA1_Init(&context)) {
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::errinfo_api_function("SHA1_Init")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA1_Init")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (!SHA1_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) {
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::errinfo_api_function("SHA1_Update")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA1_Update")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (!SHA1_Final(digest, &context)) {
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::errinfo_api_function("SHA1_Final")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA1_Final")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (binary)
if (!SHA256_Init(&context)) {
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::errinfo_api_function("SHA256_Init")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA256_Init")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (!SHA256_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) {
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::errinfo_api_function("SHA256_Update")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA256_Update")
+ << errinfo_openssl_error(ERR_peek_error()));
}
if (!SHA256_Final(digest, &context)) {
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::errinfo_api_function("SHA256_Final")
- << errinfo_openssl_error(ERR_peek_error()));
+ << boost::errinfo_api_function("SHA256_Final")
+ << errinfo_openssl_error(ERR_peek_error()));
}
char output[SHA256_DIGEST_LENGTH*2+1];
String name = GetName();
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";
else
return name + "s";
using namespace icinga;
static void InvokeAttributeHandlerHelper(const Function::Ptr& callback,
- const Object::Ptr& object, const Value& cookie)
+ const Object::Ptr& object, const Value& cookie)
{
callback->Invoke({ object });
}
#ifndef SUN_LEN
/* 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))
#endif /* SUN_LEN */
if (fd < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("socket")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("socket")
+ << boost::errinfo_errno(errno));
}
SetFD(fd);
if (bind(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("bind")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("bind")
+ << boost::errinfo_errno(errno));
}
}
if (connect(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0 && errno != EINPROGRESS) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("connect")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("connect")
+ << boost::errinfo_errno(errno));
}
}
#endif /* _WIN32 */
free(dir);
BOOST_THROW_EXCEPTION(win32_error()
- << boost::errinfo_api_function("PathRemoveFileSpec")
- << errinfo_win32_error(GetLastError()));
+ << boost::errinfo_api_function("PathRemoveFileSpec")
+ << errinfo_win32_error(GetLastError()));
}
result = dir;
return false;
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("glob")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(pathSpec));
+ << boost::errinfo_api_function("glob")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(pathSpec));
}
if (gr.gl_pathc == 0) {
return false;
BOOST_THROW_EXCEPTION(win32_error()
- << boost::errinfo_api_function("FindFirstFile")
+ << boost::errinfo_api_function("FindFirstFile")
<< errinfo_win32_error(errorCode)
- << boost::errinfo_file_name(pathSpec));
+ << boost::errinfo_file_name(pathSpec));
}
do {
if (!FindClose(handle)) {
BOOST_THROW_EXCEPTION(win32_error()
- << boost::errinfo_api_function("FindClose")
- << errinfo_win32_error(GetLastError()));
+ << boost::errinfo_api_function("FindClose")
+ << errinfo_win32_error(GetLastError()));
}
#else /* _WIN32 */
DIR *dirp;
if (!dirp)
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("opendir")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("opendir")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
while (dirp) {
dirent *pent;
closedir(dirp);
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("readdir")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("readdir")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
}
if (!pent)
#endif /* _WIN32 */
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("mkdir")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("mkdir")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
}
}
Utility::GlobRecursive(path, "*", std::bind(&Utility::CollectPaths, _1, std::ref(paths)), GlobFile | GlobDirectory);
/* 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());
for (const String& path : paths) {
if (remove(path.CStr()) < 0)
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("remove")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("remove")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
}
#ifndef _WIN32
if (_rmdir(path.CStr()) < 0)
#endif /* _WIN32 */
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rmdir")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("rmdir")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
}
void Utility::CollectPaths(const String& path, std::vector<String>& paths)
if (!pw) {
if (errno == 0) {
Log(LogCritical, "cli")
- << "Invalid user specified: " << user;
+ << "Invalid user specified: " << user;
return false;
} else {
Log(LogCritical, "cli")
- << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return false;
}
}
if (!gr) {
if (errno == 0) {
Log(LogCritical, "cli")
- << "Invalid group specified: " << group;
+ << "Invalid group specified: " << group;
return false;
} else {
Log(LogCritical, "cli")
- << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return false;
}
}
if (chown(file.CStr(), pw->pw_uid, gr->gr_gid) < 0) {
Log(LogCritical, "cli")
- << "chown() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "chown() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return false;
}
#endif /* _WIN32 */
if (flags < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("fcntl")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("fcntl")
+ << boost::errinfo_errno(errno));
}
if (nb)
if (fcntl(fd, F_SETFL, flags) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("fcntl")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("fcntl")
+ << boost::errinfo_errno(errno));
}
}
if (flags < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("fcntl")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("fcntl")
+ << boost::errinfo_errno(errno));
}
if (cloexec)
if (fcntl(fd, F_SETFD, flags) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("fcntl")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("fcntl")
+ << boost::errinfo_errno(errno));
}
}
#endif /* _WIN32 */
if (!temp) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("localtime")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("localtime")
+ << boost::errinfo_errno(errno));
}
tmthen = *temp;
#else /* _MSC_VER */
if (!localtime_r(&tempts, &tmthen)) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("localtime_r")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("localtime_r")
+ << boost::errinfo_errno(errno));
}
#endif /* _MSC_VER */
#endif /* _WIN32 */
if (ch == '#' || ch == '&' || ch == ';' || ch == '`' || ch == '|' ||
- ch == '*' || ch == '?' || ch == '~' || ch == '<' || ch == '>' ||
- ch == '^' || ch == '(' || ch == ')' || ch == '[' || ch == ']' ||
- ch == '{' || ch == '}' || ch == '$' || ch == '\\' || ch == '\x0A' ||
- ch == '\xFF')
+ ch == '*' || ch == '?' || ch == '~' || ch == '<' || ch == '>' ||
+ ch == '^' || ch == '(' || ch == ')' || ch == '[' || ch == ']' ||
+ ch == '{' || ch == '}' || ch == '$' || ch == '\\' || ch == '\x0A' ||
+ ch == '\xFF')
escape = true;
if (escape)
if (!result) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("localtime")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("localtime")
+ << boost::errinfo_errno(errno));
}
return *result;
if (!localtime_r(&ts, &result)) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("localtime_r")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("localtime_r")
+ << boost::errinfo_errno(errno));
}
return result;
if (rename(tempFilename.CStr(), path.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempFilename));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempFilename));
}
}
}
if ((input[i] & 0xE0) == 0xC0 && length > i + 1 &&
- (input[i + 1] & 0xC0) == 0x80) {
+ (input[i + 1] & 0xC0) == 0x80) {
output += input[i];
output += input[i + 1];
i++;
}
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 + 1];
output += input[i + 2];
if (fd < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("mkstemp")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("mkstemp")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
}
try {
if (chmod(resultPath.CStr(), mode) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("chmod")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(resultPath));
+ << boost::errinfo_api_function("chmod")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(resultPath));
}
return resultPath;
#ifdef _WIN32
/* mkstemp extracted from libc/sysdeps/posix/tempname.c. Copyright
- (C) 1991-1999, 2000, 2001, 2006 Free Software Foundation, Inc.
-
- The GNU C Library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version. */
+ * (C) 1991-1999, 2000, 2001, 2006 Free Software Foundation, Inc.
+ *
+ * The GNU C Library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
#define _O_EXCL 0x0400
#define _O_CREAT 0x0100
static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/* 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
- does not exist at the time of the call to mkstemp. TMPL is
- overwritten with the result. */
+ * 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
+ * overwritten with the result.
+ */
int Utility::MksTemp(char *tmpl)
{
int len;
int save_errno = errno;
/* A lower bound on the number of temporary files to attempt to
- generate. The maximum total number of temporary file names that
- can exist for a given template is 62**6. It should never be
- necessary to try all these combinations. Instead if a reasonable
- number of names is tried (we define reasonable as 62**3) fail to
- give the system administrator the chance to remove the problems. */
+ * generate. The maximum total number of temporary file names that
+ * can exist for a given template is 62**6. It should never be
+ * necessary to try all these combinations. Instead if a reasonable
+ * number of names is tried (we define reasonable as 62**3) fail to
+ * give the system administrator the chance to remove the problems.
+ */
#define ATTEMPTS_MIN (62 * 62 * 62)
- /* The number of times to attempt to generate a temporary file. To
- conform to POSIX, this must be no smaller than TMP_MAX. */
+ /* The number of times to attempt to generate a temporary file
+ * To conform to POSIX, this must be no smaller than TMP_MAX.
+ */
#if ATTEMPTS_MIN < TMP_MAX
unsigned int attempts = TMP_MAX;
#else
GetSystemTime(&stNow);
stNow.wMilliseconds = 500;
if (!SystemTimeToFileTime(&stNow, &ftNow)) {
- errno = -1;
- return -1;
+ errno = -1;
+ return -1;
}
random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32) | (unsigned long long)ftNow.dwLowDateTime);
WorkQueue::WorkQueue(size_t maxItems, int threadCount)
: 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. */
m_StatusTimerTimeout = Utility::GetTime();
* immediately if it's being enqueued from within the WorkQueue thread.
*/
void WorkQueue::Enqueue(std::function<void (void)>&& function, WorkQueuePriority priority,
- bool allowInterleaved)
+ bool allowInterleaved)
{
bool wq_thread = IsWorkerThread();
if (!m_Spawned) {
Log(LogNotice, "WorkQueue")
- << "Spawning WorkQueue threads for '" << m_Name << "'";
+ << "Spawning WorkQueue threads for '" << m_Name << "'";
for (int i = 0; i < m_ThreadCount; i++) {
m_Threads.create_thread(std::bind(&WorkQueue::WorkerThreadProc, this));
m_Spawned = false;
Log(LogNotice, "WorkQueue")
- << "Stopped WorkQueue threads for '" << m_Name << "'";
+ << "Stopped WorkQueue threads for '" << m_Name << "'";
}
}
bool WorkQueue::HasExceptions(void) const
{
boost::mutex::scoped_lock lock(m_Mutex);
-
+
return !m_Exceptions.empty();
}
std::vector<boost::exception_ptr> WorkQueue::GetExceptions(void) const
{
boost::mutex::scoped_lock lock(m_Mutex);
-
+
return m_Exceptions;
}
for (const auto& eptr : exceptions) {
Log(LogCritical, facility)
- << DiagnosticInformation(eptr);
+ << DiagnosticInformation(eptr);
}
Log(LogCritical, facility)
- << exceptions.size() << " error" << (exceptions.size() != 1 ? "s" : "");
+ << exceptions.size() << " error" << (exceptions.size() != 1 ? "s" : "");
}
size_t WorkQueue::GetLength(void) const
/* Log if there are pending items, or 5 minute timeout is reached. */
if (pending > 0 || m_StatusTimerTimeout < now) {
Log(LogInformation, "WorkQueue")
- << "#" << m_ID << " (" << m_Name << ") "
- << "items: " << pending << ", "
- << "rate: " << std::setw(2) << GetTaskCount(60) / 60.0 << "/s "
- << "(" << GetTaskCount(60) << "/min " << GetTaskCount(60 * 5) << "/5min " << GetTaskCount(60 * 15) << "/15min);"
- << timeInfo;
+ << "#" << m_ID << " (" << m_Name << ") "
+ << "items: " << pending << ", "
+ << "rate: " << std::setw(2) << GetTaskCount(60) / 60.0 << "/s "
+ << "(" << GetTaskCount(60) << "/min " << GetTaskCount(60 * 5) << "/5min " << GetTaskCount(60 * 15) << "/15min);"
+ << timeInfo;
}
/* Reschedule next log entry in 5 minutes. */
m_ExceptionCallback(boost::current_exception());
}
- /* clear the task so whatever other resources it holds are released
- _before_ we re-acquire the mutex */
+ /* clear the task so whatever other resources it holds are released _before_ we re-acquire the mutex */
task = Task();
IncreaseTaskCount();
struct Task
{
Task(void)
- : Priority(PriorityNormal), ID(-1)
+ : Priority(PriorityNormal), ID(-1)
{ }
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;
String GetName(void) const;
void Enqueue(std::function<void (void)>&& function, WorkQueuePriority priority = PriorityNormal,
- bool allowInterleaved = false);
+ bool allowInterleaved = false);
void Join(bool stop = false);
bool IsWorkerThread(void) const;
}
CheckerComponent::CheckerComponent(void)
- : m_Stopped(false)
+ : m_Stopped(false)
{ }
void CheckerComponent::OnConfigLoaded(void)
ObjectImpl<CheckerComponent>::Start(runtimeCreated);
Log(LogInformation, "CheckerComponent")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
m_Thread = std::thread(std::bind(&CheckerComponent::CheckThreadProc, this));
void CheckerComponent::Stop(bool runtimeRemoved)
{
Log(LogInformation, "CheckerComponent")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
{
boost::mutex::scoped_lock lock(m_Mutex);
if (!forced) {
if (!checkable->IsReachable(DependencyCheckExecution)) {
Log(LogNotice, "CheckerComponent")
- << "Skipping check for object '" << checkable->GetName() << "': Dependency failed.";
+ << "Skipping check for object '" << checkable->GetName() << "': Dependency failed.";
check = false;
}
if (host && !service && (!checkable->GetEnableActiveChecks() || !IcingaApplication::GetInstance()->GetEnableHostChecks())) {
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;
}
if (host && service && (!checkable->GetEnableActiveChecks() || !IcingaApplication::GetInstance()->GetEnableServiceChecks())) {
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;
}
if (tp && !tp->IsInside(Utility::GetTime())) {
Log(LogNotice, "CheckerComponent")
- << "Skipping check for object '" << checkable->GetName()
- << "': not in check period '" << tp->GetName() << "'";
+ << "Skipping check for object '" << checkable->GetName()
+ << "': not in check period '" << tp->GetName() << "'";
check = false;
}
}
}
Log(LogDebug, "CheckerComponent")
- << "Executing check for '" << checkable->GetName() << "'";
+ << "Executing check for '" << checkable->GetName() << "'";
Checkable::IncreasePendingChecks();
}
Log(LogDebug, "CheckerComponent")
- << "Check finished for object '" << checkable->GetName() << "'";
+ << "Check finished for object '" << checkable->GetName() << "'";
}
void CheckerComponent::ResultTimerHandler(void)
boost::mutex::scoped_lock lock(m_Mutex);
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());
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)
if (!Utility::SetFileOwnership(pki_path, user, group)) {
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";
if (Utility::PathExists(key)) {
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;
}
Log(LogInformation, "cli")
- << "Generating new CSR in '" << csr << "'.";
+ << "Generating new CSR in '" << csr << "'.";
if (Utility::PathExists(key))
NodeUtility::CreateBackupFile(key, true);
String cert = pki_path + "/" + cn + ".crt";
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))
NodeUtility::CreateBackupFile(cert);
String target_ca = pki_path + "/ca.crt";
Log(LogInformation, "cli")
- << "Copying CA certificate to '" << target_ca << "'.";
+ << "Copying CA certificate to '" << target_ca << "'.";
if (Utility::PathExists(target_ca))
NodeUtility::CreateBackupFile(target_ca);
for (const String& file : { ca_path, ca, ca_key, target_ca, key, csr, cert }) {
if (!Utility::SetFileOwnership(file, user, group)) {
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 << "'.";
}
}
if (Utility::PathExists(apiUsersPath)) {
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;
}
Log(LogInformation, "cli")
- << "Adding new ApiUser '" << api_username << "' in '" << apiUsersPath << "'.";
+ << "Adding new ApiUser '" << api_username << "' in '" << apiUsersPath << "'.";
NodeUtility::CreateBackupFile(apiUsersPath);
String tempFilename = Utility::CreateTempFile(apiUsersPath + ".XXXXXX", 0644, fp);
fp << "/**\n"
- << " * The APIUser objects are used for authentication against the API.\n"
- << " */\n"
- << "object ApiUser \"" << api_username << "\" {\n"
- << " password = \"" << api_password << "\"\n"
- << " // client_cn = \"\"\n"
- << "\n"
- << " permissions = [ \"*\" ]\n"
- << "}\n";
+ << " * The APIUser objects are used for authentication against the API.\n"
+ << " */\n"
+ << "object ApiUser \"" << api_username << "\" {\n"
+ << " password = \"" << api_password << "\"\n"
+ << " // client_cn = \"\"\n"
+ << "\n"
+ << " permissions = [ \"*\" ]\n"
+ << "}\n";
fp.close();
if (rename(tempFilename.CStr(), apiUsersPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempFilename));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempFilename));
}
return true;
}
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()
("json", "encode output as JSON")
Dictionary::Ptr request = kv.second;
std::cout << kv.first
- << " | "
+ << " | "
/* << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S", request->Get("timestamp")) */
- << request->Get("timestamp")
- << " | "
- << (request->Contains("cert_response") ? "*" : " ") << " "
- << " | "
- << request->Get("subject")
- << "\n";
+ << request->Get("timestamp")
+ << " | "
+ << (request->Contains("cert_response") ? "*" : " ") << " "
+ << " | "
+ << request->Get("subject")
+ << "\n";
}
}
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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;
private:
ImpersonationLevel CASignCommand::GetImpersonationLevel(void) const
{
- return ImpersonateIcinga;
+ return ImpersonateIcinga;
}
/**
if (!Utility::PathExists(requestFile)) {
Log(LogCritical, "cli")
- << "No request exists for fingerprint '" << ap[0] << "'.";
+ << "No request exists for fingerprint '" << ap[0] << "'.";
return 1;
}
if (!certResponse) {
Log(LogCritical, "cli")
- << "Could not sign certificate for '" << subject << "'.";
+ << "Could not sign certificate for '" << subject << "'.";
return 1;
}
Utility::SaveJsonFile(requestFile, 0600, request);
Log(LogInformation, "cli")
- << "Signed certificate for '" << subject << "'.";
+ << "Signed certificate for '" << subject << "'.";
return 0;
}
continue;
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;
String fname = field.Name;
}
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
}
bool CLICommand::ParseCommand(int argc, char **argv, po::options_description& visibleDesc,
- po::options_description& hiddenDesc,
- po::positional_options_description& positionalDesc,
- po::variables_map& vm, String& cmdname, CLICommand::Ptr& command, bool autocomplete)
+ po::options_description& hiddenDesc,
+ po::positional_options_description& positionalDesc,
+ po::variables_map& vm, String& cmdname, CLICommand::Ptr& command, bool autocomplete)
{
boost::mutex::scoped_lock lock(GetRegistryMutex());
if (command && command->IsDeprecated()) {
std::cerr << ConsoleColorTag(Console_ForegroundRed | Console_Bold)
- << "Warning: CLI command '" << cmdname << "' is DEPRECATED! Please read the Changelog."
- << ConsoleColorTag(Console_Normal) << std::endl << std::endl;
+ << "Warning: CLI command '" << cmdname << "' is DEPRECATED! Please read the Changelog."
+ << 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);
}
void CLICommand::ShowCommands(int argc, char **argv, po::options_description *visibleDesc,
- po::options_description *hiddenDesc,
- ArgumentCompletionCallback globalArgCompletionCallback,
- bool autocomplete, int autoindex)
+ po::options_description *hiddenDesc,
+ ArgumentCompletionCallback globalArgCompletionCallback,
+ bool autocomplete, int autoindex)
{
boost::mutex::scoped_lock lock(GetRegistryMutex());
}
} else {
std::cout << " * " << boost::algorithm::join(vname, " ")
- << " (" << kv.second->GetShortDescription() << ")"
- << (kv.second->IsDeprecated() ? " (DEPRECATED)" : "") << std::endl;
+ << " (" << kv.second->GetShortDescription() << ")"
+ << (kv.second->IsDeprecated() ? " (DEPRECATED)" : "") << std::endl;
}
}
virtual bool IsHidden(void) const;
virtual bool IsDeprecated(void) const;
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 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;
static void Unregister(const std::vector<String>& name);
static bool ParseCommand(int argc, char **argv, boost::program_options::options_description& visibleDesc,
- boost::program_options::options_description& hiddenDesc,
- boost::program_options::positional_options_description& positionalDesc,
- boost::program_options::variables_map& vm, String& cmdname,
- CLICommand::Ptr& command, bool autocomplete);
+ boost::program_options::options_description& hiddenDesc,
+ boost::program_options::positional_options_description& positionalDesc,
+ boost::program_options::variables_map& vm, String& cmdname, CLICommand::Ptr& command, bool autocomplete);
static void ShowCommands(int argc, char **argv,
- boost::program_options::options_description *visibleDesc = nullptr,
- boost::program_options::options_description *hiddenDesc = nullptr,
- ArgumentCompletionCallback globalArgCompletionCallback = nullptr,
- bool autocomplete = false, int autoindex = -1);
+ boost::program_options::options_description *visibleDesc = nullptr,
+ boost::program_options::options_description *hiddenDesc = nullptr,
+ ArgumentCompletionCallback globalArgCompletionCallback = nullptr,
+ bool autocomplete = false, int autoindex = -1);
private:
static boost::mutex& GetRegistryMutex(void);
ShowCodeLocation(std::cout, di);
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
rl_completion_entry_function = ConsoleCommand::ConsoleCompleteHelper;
}
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()
("connect,c", po::value<std::string>(), "connect to an Icinga 2 instance")
if (state == 0) {
if (!l_ApiClient)
- matches = ConsoleHandler::GetAutocompletionSuggestions(word, *l_ScriptFrame);
+ matches = ConsoleHandler::GetAutocompletionSuggestions(word, *l_ScriptFrame);
else {
boost::mutex mutex;
boost::condition_variable cv;
Array::Ptr suggestions;
l_ApiClient->AutocompleteScript(l_Session, word, l_ScriptFrame->Sandboxed,
- std::bind(&ConsoleCommand::AutocompleteScriptCompletionHandler,
- std::ref(mutex), std::ref(cv), std::ref(ready),
- _1, _2,
- std::ref(suggestions)));
+ std::bind(&ConsoleCommand::AutocompleteScriptCompletionHandler,
+ std::ref(mutex), std::ref(cv), std::ref(ready),
+ _1, _2,
+ std::ref(suggestions)));
{
boost::mutex::scoped_lock lock(mutex);
boost::exception_ptr eptr;
l_ApiClient->ExecuteScript(l_Session, command, scriptFrame.Sandboxed,
- std::bind(&ConsoleCommand::ExecuteScriptCompletionHandler,
- std::ref(mutex), std::ref(cv), std::ref(ready),
- _1, _2,
- std::ref(result), std::ref(eptr)));
+ std::bind(&ConsoleCommand::ExecuteScriptCompletionHandler,
+ std::ref(mutex), std::ref(cv), std::ref(ready),
+ _1, _2,
+ std::ref(result), std::ref(eptr)));
{
boost::mutex::scoped_lock lock(mutex);
}
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) {
try {
eptrOut = boost::current_exception();
} catch (const std::exception& ex) {
Log(LogCritical, "ConsoleCommand")
- << "HTTP query failed: " << ex.what();
+ << "HTTP query failed: " << ex.what();
Application::Exit(EXIT_FAILURE);
}
}
}
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) {
try {
boost::rethrow_exception(eptr);
} catch (const std::exception& ex) {
Log(LogCritical, "ConsoleCommand")
- << "HTTP query failed: " << ex.what();
+ << "HTTP query failed: " << ex.what();
Application::Exit(EXIT_FAILURE);
}
}
virtual String GetShortDescription(void) const override;
virtual ImpersonationLevel GetImpersonationLevel(void) const override;
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;
static int RunScriptConsole(ScriptFrame& scriptFrame, const String& addr = String(),
- const String& session = String(), const String& commandOnce = String(), const String& commandOnceFileName = String(),
- bool syntaxOnly = false);
+ const String& session = String(), const String& commandOnce = String(), const String& commandOnceFileName = String(),
+ bool syntaxOnly = false);
private:
mutable boost::mutex m_Mutex;
mutable boost::condition_variable m_CV;
static void 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);
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
static char *ConsoleCompleteHelper(const char *word, int state);
_exit(EXIT_FAILURE);
} else if (ret == -1) {
Log(LogCritical, "cli")
- << "waitpid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "waitpid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
_exit(EXIT_FAILURE);
}
}
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()
("config,c", po::value<std::vector<std::string> >(), "parse a configuration file")
Logger::DisableTimestamp(false);
Log(LogInformation, "cli")
- << "Icinga application loader (version: " << Application::GetAppVersion()
+ << "Icinga application loader (version: " << Application::GetAppVersion()
#ifdef I2_DEBUG
- << "; debug"
+ << "; debug"
#endif /* I2_DEBUG */
- << ")";
+ << ")";
if (!vm.count("validate") && !vm.count("reload-internal")) {
pid_t runningpid = Application::ReadPidFile(Application::GetPidPath());
if (runningpid > 0) {
Log(LogCritical, "cli")
- << "Another instance of Icinga already running with PID " << runningpid;
+ << "Another instance of Icinga already running with PID " << runningpid;
return EXIT_FAILURE;
}
}
if (vm.count("reload-internal")) {
int parentpid = vm["reload-internal"].as<int>();
Log(LogInformation, "cli")
- << "Terminating previous instance of Icinga (PID " << parentpid << ")";
+ << "Terminating previous instance of Icinga (PID " << parentpid << ")";
TerminateAndWaitForEnd(parentpid);
Log(LogInformation, "cli", "Previous instance has ended, taking over now.");
}
ConfigObject::RestoreObjects(Application::GetStatePath());
} catch (const std::exception& ex) {
Log(LogCritical, "cli")
- << "Failed to restore state file: " << DiagnosticInformation(ex);
+ << "Failed to restore state file: " << DiagnosticInformation(ex);
return EXIT_FAILURE;
}
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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 int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
};
*/
if (ConfigCompiler::HasZoneConfigAuthority(zoneName) || Utility::PathExists(zonePath + "/.authoritative")) {
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;
}
if (Utility::PathExists(packagePath + "/include.conf")) {
std::unique_ptr<Expression> expr = ConfigCompiler::CompileFile(packagePath + "/include.conf",
- String(), packageName);
+ String(), packageName);
if (!ExecuteExpression(&*expr))
success = false;
}
bool DaemonUtility::LoadConfigFiles(const std::vector<std::string>& configs,
- std::vector<ConfigItem::Ptr>& newItems,
- const String& objectsFile, const String& varsfile)
+ std::vector<ConfigItem::Ptr>& newItems,
+ const String& objectsFile, const String& varsfile)
{
ActivationScope ascope;
public:
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,
- const String& objectsFile = String(), const String& varsfile = String());
+ const String& objectsFile = String(), const String& varsfile = String());
};
}
if (!Utility::PathExists(features_available_dir) ) {
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;
}
if (!Utility::PathExists(features_enabled_dir) ) {
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;
}
if (!Utility::PathExists(source) ) {
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);
continue;
}
if (Utility::PathExists(target) ) {
Log(LogWarning, "cli")
- << "Feature '" << feature << "' already enabled.";
+ << "Feature '" << feature << "' already enabled.";
continue;
}
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
String relativeSource = "../features-available/" + feature + ".conf";
if (symlink(relativeSource.CStr(), target.CStr()) < 0) {
Log(LogCritical, "cli")
- << "Cannot enable feature '" << feature << "'. Linking source '" << relativeSource << "' to target file '" << target
- << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\".";
+ << "Cannot enable feature '" << feature << "'. Linking source '" << relativeSource << "' to target file '" << target
+ << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\".";
errors.push_back(feature);
continue;
}
if (fp.fail()) {
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);
continue;
}
if (!errors.empty()) {
Log(LogCritical, "cli")
- << "Cannot enable feature(s): " << boost::algorithm::join(errors, " ");
+ << "Cannot enable feature(s): " << boost::algorithm::join(errors, " ");
errors.clear();
return 1;
}
if (!Utility::PathExists(features_enabled_dir) ) {
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;
}
if (!Utility::PathExists(target) ) {
Log(LogWarning, "cli")
- << "Feature '" << feature << "' already disabled.";
+ << "Feature '" << feature << "' already disabled.";
continue;
}
if (unlink(target.CStr()) < 0) {
Log(LogCritical, "cli")
- << "Cannot disable feature '" << feature << "'. Unlinking target file '" << target
- << "' failed with error code " << errno << ", \"" + Utility::FormatErrorNumber(errno) << "\".";
+ << "Cannot disable feature '" << feature << "'. Unlinking target file '" << target
+ << "' failed with error code " << errno << ", \"" + Utility::FormatErrorNumber(errno) << "\".";
errors.push_back(feature);
continue;
}
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()) {
Log(LogCritical, "cli")
- << "Cannot disable feature(s): " << boost::algorithm::join(errors, " ");
+ << "Cannot disable feature(s): " << boost::algorithm::join(errors, " ");
errors.clear();
return 1;
}
return 1;
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))
return 1;
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;
}
boost::algorithm::replace_all(feature, ".conf", "");
Log(LogDebug, "cli")
- << "Adding feature: " << feature;
+ << "Adding feature: " << feature;
features.push_back(feature);
}
}
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()
("zone", po::value<std::string>(), "The name of the local zone")
{
if (!ap.empty()) {
Log(LogWarning, "cli")
- << "Ignoring parameters: " << boost::algorithm::join(ap, " ");
+ << "Ignoring parameters: " << boost::algorithm::join(ap, " ");
}
if (vm.count("master"))
if (vm.count("accept-commands"))
Log(LogWarning, "cli", "Master for Node setup: Ignoring --accept-commands");
- String cn = Utility::GetFQDN();
+ String cn = Utility::GetFQDN();
- if (vm.count("cn"))
- cn = vm["cn"].as<std::string>();
+ if (vm.count("cn"))
+ cn = vm["cn"].as<std::string>();
/* check whether the user wants to generate a new certificate or not */
String existingPath = ApiListener::GetCertsDir() + "/" + cn + ".crt";
Log(LogInformation, "cli")
- << "Checking in existing certificates for common name '" << cn << "'...";
+ << "Checking in existing certificates for common name '" << cn << "'...";
if (Utility::PathExists(existingPath)) {
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 {
Log(LogInformation, "cli")
- << "Certificates not yet generated. Running 'api setup' now.";
+ << "Certificates not yet generated. Running 'api setup' now.";
ApiSetupUtility::SetupMasterCertificates(cn);
}
ApiSetupUtility::SetupMasterEnableApi();
} else {
Log(LogInformation, "cli")
- << "'api' feature already enabled.\n";
+ << "'api' feature already enabled.\n";
}
/* write zones.conf and update with zone + endpoint information */
String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
fp << "/**\n"
- << " * The API listener is used for distributed monitoring setups.\n"
- << " */\n"
- << "object ApiListener \"api\" {\n";
+ << " * The API listener is used for distributed monitoring setups.\n"
+ << " */\n"
+ << "object ApiListener \"api\" {\n";
if (vm.count("listen")) {
std::vector<String> tokens;
}
fp << "\n"
- << " ticket_salt = TicketSalt\n"
- << "}\n";
+ << " ticket_salt = TicketSalt\n"
+ << "}\n";
fp.close();
if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempApiPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempApiPath));
}
/* update constants.conf with NodeName = CN + TicketSalt = random value */
NodeUtility::UpdateConstant("TicketSalt", salt);
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 */
if (ticket.IsEmpty()) {
Log(LogInformation, "cli")
- << "Requesting certificate without a ticket.";
+ << "Requesting certificate without a ticket.";
} else {
Log(LogInformation, "cli")
- << "Requesting certificate with ticket '" << ticket << "'.";
+ << "Requesting certificate with ticket '" << ticket << "'.";
}
/* require master host information for auto-signing requests */
master_port = tokens[1];
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) */
if (!vm.count("trustedcert")) {
Log(LogCritical, "cli")
- << "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').";
+ << "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').";
return 1;
}
std::shared_ptr<X509> trustedcert = GetX509Certificate(vm["trustedcert"].as<std::string>());
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) */
String cn = Utility::GetFQDN();
cn = vm["cn"].as<std::string>();
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 */
if (!Utility::SetFileOwnership(pki_path, user, group)) {
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";
/* fix permissions: root -> icinga daemon user */
if (!Utility::SetFileOwnership(key, user, group)) {
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.");
if (PkiUtility::RequestCertificate(master_host, master_port, key, cert, ca, trustedcert, ticket) > 0) {
Log(LogCritical, "cli")
- << "Failed to fetch signed certificate from parent Icinga node '"
- << master_host << ", "
- << master_port << "'. Please try again.";
+ << "Failed to fetch signed certificate from parent Icinga node '"
+ << master_host << ", "
+ << master_port << "'. Please try again.";
return 1;
}
if (!Utility::SetFileOwnership(ca, user, group)) {
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 */
if (!Utility::SetFileOwnership(cert, user, group)) {
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 */
String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
fp << "/**\n"
- << " * The API listener is used for distributed monitoring setups.\n"
- << " */\n"
- << "object ApiListener \"api\" {\n";
+ << " * The API listener is used for distributed monitoring setups.\n"
+ << " */\n"
+ << "object ApiListener \"api\" {\n";
if (vm.count("listen")) {
std::vector<String> tokens;
fp << " accept_commands = false\n";
fp << "\n"
- << "}\n";
+ << "}\n";
fp.close();
if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempApiPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempApiPath));
}
/* generate local zones.conf with zone+endpoint */
/* update constants.conf with NodeName = CN */
if (cn != Utility::GetFQDN()) {
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);
if (!Utility::SetFileOwnership(tempTicketPath, user, group)) {
Log(LogWarning, "cli")
- << "Cannot set ownership for user '" << user
- << "' group '" << group
- << "' on file '" << tempTicketPath << "'. Verify it yourself!";
+ << "Cannot set ownership for user '" << user
+ << "' group '" << group
+ << "' on file '" << tempTicketPath << "'. Verify it yourself!";
}
fp << ticket;
if (rename(tempTicketPath.CStr(), ticketPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempTicketPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempTicketPath));
}
}
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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 ImpersonationLevel GetImpersonationLevel(void) const override;
virtual int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
myGlobalZone->Set("global", true);
my_config->Add(myGlobalZone);
- }
+ }
/* store the local config */
my_config->Add(my_endpoint);
bool NodeUtility::WriteNodeConfigObjects(const String& filename, const Array::Ptr& objects)
{
Log(LogInformation, "cli")
- << "Dumping config items to file '" << filename << "'.";
+ << "Dumping config items to file '" << filename << "'.";
/* create a backup first */
CreateBackupFile(filename);
if (!Utility::SetFileOwnership(path, user, group)) {
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)) {
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;
if (rename(tempFilename.CStr(), filename.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempFilename));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempFilename));
}
return true;
if (Utility::PathExists(backup)) {
Log(LogInformation, "cli")
- << "Backup file '" << backup << "' already exists. Skipping backup.";
+ << "Backup file '" << backup << "' already exists. Skipping backup.";
return false;
}
#endif /* _WIN32 */
Log(LogInformation, "cli")
- << "Created backup file '" << backup << "'.";
+ << "Created backup file '" << backup << "'.";
return true;
}
String constantsConfPath = NodeUtility::GetConstantsConfPath();
Log(LogInformation, "cli")
- << "Updating '" << name << "' constant in '" << constantsConfPath << "'.";
+ << "Updating '" << name << "' constant in '" << constantsConfPath << "'.";
NodeUtility::CreateBackupFile(constantsConfPath);
}
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()
("verbose", "increase log level");
* @returns An exit status.
*/
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"))
Logger::SetConsoleLogSeverity(LogCritical);
*/
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundBlue)
- << "Welcome to the Icinga 2 Setup Wizard!\n"
- << "\n"
- << "We will guide you through all required configuration details.\n"
- << "\n"
- << ConsoleColorTag(Console_Normal);
+ << "Welcome to the Icinga 2 Setup Wizard!\n"
+ << "\n"
+ << "We will guide you through all required configuration details.\n"
+ << "\n"
+ << ConsoleColorTag(Console_Normal);
/* 0. master or node setup?
* 1. Ticket
std::string answer;
/* master or satellite/client setup */
std::cout << ConsoleColorTag(Console_Bold)
- << "Please specify if this is a satellite/client setup "
- << "('n' installs a master setup)" << ConsoleColorTag(Console_Normal)
- << " [Y/n]: ";
+ << "Please specify if this is a satellite/client setup "
+ << "('n' installs a master setup)" << ConsoleColorTag(Console_Normal)
+ << " [Y/n]: ";
std::getline (std::cin, answer);
boost::algorithm::to_lower(answer);
std::cout << "\n";
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen)
- << "Done.\n\n"
- << ConsoleColorTag(Console_Normal);
+ << "Done.\n\n"
+ << ConsoleColorTag(Console_Normal);
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundRed)
- << "Now restart your Icinga 2 daemon to finish the installation!\n"
- << ConsoleColorTag(Console_Normal);
+ << "Now restart your Icinga 2 daemon to finish the installation!\n"
+ << ConsoleColorTag(Console_Normal);
return 0;
}
/* CN */
std::cout << ConsoleColorTag(Console_Bold)
- << "Please specify the common name (CN)"
- << ConsoleColorTag(Console_Normal)
- << " [" << Utility::GetFQDN() << "]: ";
+ << "Please specify the common name (CN)"
+ << ConsoleColorTag(Console_Normal)
+ << " [" << Utility::GetFQDN() << "]: ";
std::getline(std::cin, answer);
String endpointBuffer;
std::cout << ConsoleColorTag(Console_Bold)
- << "\nPlease specify the parent endpoint(s) (master or satellite) where this node should connect to:"
- << ConsoleColorTag(Console_Normal) << "\n";
+ << "\nPlease specify the parent endpoint(s) (master or satellite) where this node should connect to:"
+ << ConsoleColorTag(Console_Normal) << "\n";
String parentEndpointName;
wizard_endpoint_loop_start:
std::cout << ConsoleColorTag(Console_Bold)
- << "Master/Satellite Common Name" << ConsoleColorTag(Console_Normal)
- << " (CN from your master/satellite node): ";
+ << "Master/Satellite Common Name" << ConsoleColorTag(Console_Normal)
+ << " (CN from your master/satellite node): ";
std::getline(std::cin, answer);
endpointBuffer = endpointBuffer.Trim();
std::cout << "\nDo you want to establish a connection to the parent node "
- << ConsoleColorTag(Console_Bold) << "from this node?"
- << ConsoleColorTag(Console_Normal) << " [Y/n]: ";
+ << ConsoleColorTag(Console_Bold) << "from this node?"
+ << ConsoleColorTag(Console_Normal) << " [Y/n]: ";
std::getline (std::cin, answer);
boost::algorithm::to_lower(answer);
Log(LogWarning, "cli", "Node to master/satellite connection setup skipped");
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 {
connectToParent = true;
std::cout << ConsoleColorTag(Console_Bold)
- << "Please specify the master/satellite connection information:"
- << ConsoleColorTag(Console_Normal) << "\n"
- << ConsoleColorTag(Console_Bold) << "Master/Satellite endpoint host"
- << ConsoleColorTag(Console_Normal) << " (IP address or FQDN): ";
+ << "Please specify the master/satellite connection information:"
+ << ConsoleColorTag(Console_Normal) << "\n"
+ << ConsoleColorTag(Console_Bold) << "Master/Satellite endpoint host"
+ << ConsoleColorTag(Console_Normal) << " (IP address or FQDN): ";
std::getline(std::cin, answer);
parentEndpointName = tmp;
std::cout << ConsoleColorTag(Console_Bold)
- << "Master/Satellite endpoint port" << ConsoleColorTag(Console_Normal)
- << " [" << parentEndpointPort << "]: ";
+ << "Master/Satellite endpoint port" << ConsoleColorTag(Console_Normal)
+ << " [" << parentEndpointPort << "]: ";
std::getline(std::cin, answer);
endpoints.push_back(endpointBuffer);
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);
boost::algorithm::to_lower(answer);
if (!Utility::SetFileOwnership(certsDir, user, group)) {
Log(LogWarning, "cli")
- << "Cannot set ownership for user '" << user
- << "' group '" << group
- << "' on file '" << certsDir << "'. Verify it yourself!";
+ << "Cannot set ownership for user '" << user
+ << "' group '" << group
+ << "' on file '" << certsDir << "'. Verify it yourself!";
}
String nodeCert = certsDir + "/" + cn + ".crt";
if (PkiUtility::NewCert(cn, nodeKey, Empty, nodeCert) > 0) {
Log(LogCritical, "cli")
- << "Failed to create new self-signed certificate for CN '"
- << cn << "'. Please try again.";
+ << "Failed to create new self-signed certificate for CN '"
+ << cn << "'. Please try again.";
return 1;
}
/* fix permissions: root -> icinga daemon user */
if (!Utility::SetFileOwnership(nodeKey, user, group)) {
Log(LogWarning, "cli")
- << "Cannot set ownership for user '" << user
- << "' group '" << group
- << "' on file '" << nodeKey << "'. Verify it yourself!";
+ << "Cannot set ownership for user '" << user
+ << "' group '" << group
+ << "' on file '" << nodeKey << "'. Verify it yourself!";
}
std::shared_ptr<X509> trustedParentCert;
if (connectToParent) {
//save-cert and store the master certificate somewhere
Log(LogInformation, "cli")
- << "Fetching public certificate from master ("
- << parentHost << ", " << parentPort << "):\n";
+ << "Fetching public certificate from master ("
+ << parentHost << ", " << parentPort << "):\n";
trustedParentCert = PkiUtility::FetchCert(parentHost, parentPort);
if (!trustedParentCert) {
}
std::cout << ConsoleColorTag(Console_Bold) << "Parent certificate information:\n"
- << ConsoleColorTag(Console_Normal) << PkiUtility::GetCertificateInformation(trustedParentCert)
- << ConsoleColorTag(Console_Bold) << "\nIs this information correct?"
- << ConsoleColorTag(Console_Normal) << " [y/N]: ";
+ << ConsoleColorTag(Console_Normal) << PkiUtility::GetCertificateInformation(trustedParentCert)
+ << ConsoleColorTag(Console_Bold) << "\nIs this information correct?"
+ << ConsoleColorTag(Console_Normal) << " [y/N]: ";
std::getline (std::cin, answer);
boost::algorithm::to_lower(answer);
/* Check whether we can connect to the parent node and fetch the client and CA certificate. */
if (connectToParent) {
std::cout << ConsoleColorTag(Console_Bold)
- << "\nPlease specify the request ticket generated on your Icinga 2 master "
- << ConsoleColorTag(Console_Normal) << "(optional)"
- << ConsoleColorTag(Console_Bold) << "."
- << ConsoleColorTag(Console_Normal) << "\n"
- << " (Hint: # icinga2 pki ticket --cn '" << cn << "'): ";
+ << "\nPlease specify the request ticket generated on your Icinga 2 master "
+ << ConsoleColorTag(Console_Normal) << "(optional)"
+ << ConsoleColorTag(Console_Bold) << "."
+ << ConsoleColorTag(Console_Normal) << "\n"
+ << " (Hint: # icinga2 pki ticket --cn '" << cn << "'): ";
std::getline(std::cin, answer);
if (answer.empty()) {
std::cout << ConsoleColorTag(Console_Bold) << "\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)."
- << ConsoleColorTag(Console_Normal) << "\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)."
+ << ConsoleColorTag(Console_Normal) << "\n";
}
ticket = answer;
if (ticket.IsEmpty()) {
Log(LogInformation, "cli")
- << "Requesting certificate without a ticket.";
+ << "Requesting certificate without a ticket.";
} else {
Log(LogInformation, "cli")
- << "Requesting certificate with ticket '" << ticket << "'.";
+ << "Requesting certificate with ticket '" << ticket << "'.";
}
if (Utility::PathExists(nodeCA))
NodeUtility::CreateBackupFile(nodeCert);
if (PkiUtility::RequestCertificate(parentHost, parentPort, nodeKey,
- nodeCert, nodeCA, trustedParentCert, ticket) > 0) {
+ nodeCert, nodeCA, trustedParentCert, ticket) > 0) {
Log(LogCritical, "cli")
- << "Failed to fetch signed certificate from master '"
- << parentHost << ", "
- << parentPort << "'. Please try again.";
+ << "Failed to fetch signed certificate from master '"
+ << parentHost << ", "
+ << parentPort << "'. Please try again.";
goto wizard_ticket;
}
/* fix permissions (again) when updating the signed certificate */
if (!Utility::SetFileOwnership(nodeCert, user, group)) {
Log(LogWarning, "cli")
- << "Cannot set ownership for user '" << user
- << "' group '" << group << "' on file '"
- << nodeCert << "'. Verify it yourself!";
+ << "Cannot set ownership for user '" << user
+ << "' group '" << group << "' on file '"
+ << nodeCert << "'. Verify it yourself!";
}
} else {
/* We cannot retrieve the parent certificate.
*/
std::cout << ConsoleColorTag(Console_Bold)
- << "\nNo connection to the parent node was specified.\n\n"
- << "Please copy the public CA certificate from your master/satellite\n"
- << "into '" << nodeCA << "' before starting Icinga 2.\n"
- << ConsoleColorTag(Console_Normal);
+ << "\nNo connection to the parent node was specified.\n\n"
+ << "Please copy the public CA certificate from your master/satellite\n"
+ << "into '" << nodeCA << "' before starting Icinga 2.\n"
+ << ConsoleColorTag(Console_Normal);
if (Utility::PathExists(nodeCA)) {
std::cout << ConsoleColorTag(Console_Bold)
- << "\nFound public CA certificate in '" << nodeCA << "'.\n"
- << "Please verify that it is the same as on your master/satellite.\n"
- << ConsoleColorTag(Console_Normal);
+ << "\nFound public CA certificate in '" << nodeCA << "'.\n"
+ << "Please verify that it is the same as on your master/satellite.\n"
+ << ConsoleColorTag(Console_Normal);
}
}
/* apilistener config */
std::cout << ConsoleColorTag(Console_Bold)
- << "Please specify the API bind host/port "
- << ConsoleColorTag(Console_Normal) << "(optional)"
- << ConsoleColorTag(Console_Bold) << ":\n";
+ << "Please specify the API bind host/port "
+ << ConsoleColorTag(Console_Normal) << "(optional)"
+ << ConsoleColorTag(Console_Bold) << ":\n";
std::cout << ConsoleColorTag(Console_Bold)
- << "Bind Host" << ConsoleColorTag(Console_Normal) << " []: ";
+ << "Bind Host" << ConsoleColorTag(Console_Normal) << " []: ";
std::getline(std::cin, answer);
bindHost = bindHost.Trim();
std::cout << ConsoleColorTag(Console_Bold)
- << "Bind Port" << ConsoleColorTag(Console_Normal) << " []: ";
+ << "Bind Port" << ConsoleColorTag(Console_Normal) << " []: ";
std::getline(std::cin, answer);
bindPort = bindPort.Trim();
std::cout << ConsoleColorTag(Console_Bold) << "\n"
- << "Accept config from parent node?" << ConsoleColorTag(Console_Normal)
- << " [y/N]: ";
+ << "Accept config from parent node?" << ConsoleColorTag(Console_Normal)
+ << " [y/N]: ";
std::getline(std::cin, answer);
boost::algorithm::to_lower(answer);
choice = answer;
String acceptConfig = choice.Contains("y") ? "true" : "false";
std::cout << ConsoleColorTag(Console_Bold)
- << "Accept commands from parent node?" << ConsoleColorTag(Console_Normal)
- << " [y/N]: ";
+ << "Accept commands from parent node?" << ConsoleColorTag(Console_Normal)
+ << " [y/N]: ";
std::getline(std::cin, answer);
boost::algorithm::to_lower(answer);
choice = answer;
std::cout << "\n";
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen)
- << "Reconfiguring Icinga...\n"
- << ConsoleColorTag(Console_Normal);
+ << "Reconfiguring Icinga...\n"
+ << ConsoleColorTag(Console_Normal);
/* disable the notifications feature on client nodes */
Log(LogInformation, "cli", "Disabling the Notification feature.");
String tempApiConfPath = Utility::CreateTempFile(apiConfPath + ".XXXXXX", 0644, fp);
fp << "/**\n"
- << " * The API listener is used for distributed monitoring setups.\n"
- << " */\n"
- << "object ApiListener \"api\" {\n"
- << " accept_config = " << acceptConfig << "\n"
- << " accept_commands = " << acceptCommands << "\n";
+ << " * The API listener is used for distributed monitoring setups.\n"
+ << " */\n"
+ << "object ApiListener \"api\" {\n"
+ << " accept_config = " << acceptConfig << "\n"
+ << " accept_commands = " << acceptCommands << "\n";
if (!bindHost.IsEmpty())
fp << " bind_host = \"" << bindHost << "\"\n";
if (rename(tempApiConfPath.CStr(), apiConfPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempApiConfPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempApiConfPath));
}
/* apilistener config */
if (cn != Utility::GetFQDN()) {
Log(LogWarning, "cli")
- << "CN '" << cn << "' does not match the default FQDN '"
- << Utility::GetFQDN() << "'. Requires update for NodeName constant in constants.conf!";
+ << "CN '" << cn << "' does not match the default FQDN '"
+ << Utility::GetFQDN() << "'. Requires update for NodeName constant in constants.conf!";
}
NodeUtility::UpdateConstant("NodeName", cn);
if (!Utility::SetFileOwnership(tempTicketPath, user, group)) {
Log(LogWarning, "cli")
- << "Cannot set ownership for user '" << user
- << "' group '" << group
- << "' on file '" << tempTicketPath << "'. Verify it yourself!";
+ << "Cannot set ownership for user '" << user
+ << "' group '" << group
+ << "' on file '" << tempTicketPath << "'. Verify it yourself!";
}
fp << ticket;
if (rename(tempTicketPath.CStr(), ticketPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempTicketPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempTicketPath));
}
}
/* CN */
std::cout << ConsoleColorTag(Console_Bold)
- << "Please specify the common name" << ConsoleColorTag(Console_Normal)
- << " (CN) [" << Utility::GetFQDN() << "]: ";
+ << "Please specify the common name" << ConsoleColorTag(Console_Normal)
+ << " (CN) [" << Utility::GetFQDN() << "]: ";
std::getline(std::cin, answer);
cn = cn.Trim();
std::cout << ConsoleColorTag(Console_Bold | Console_ForegroundGreen)
- << "Reconfiguring Icinga...\n"
- << ConsoleColorTag(Console_Normal);
+ << "Reconfiguring Icinga...\n"
+ << ConsoleColorTag(Console_Normal);
/* check whether the user wants to generate a new certificate or not */
String existing_path = ApiListener::GetCertsDir() + "/" + cn + ".crt";
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)) {
std::cout << "Certificate '" << existing_path << "' for CN '"
- << cn << "' already existing. Skipping certificate generation.\n";
+ << cn << "' already existing. Skipping certificate generation.\n";
} else {
std::cout << "Certificates not yet generated. Running 'api setup' now.\n";
ApiSetupUtility::SetupMasterCertificates(cn);
}
std::cout << ConsoleColorTag(Console_Bold)
- << "Generating master configuration for Icinga 2.\n"
- << ConsoleColorTag(Console_Normal);
+ << "Generating master configuration for Icinga 2.\n"
+ << ConsoleColorTag(Console_Normal);
ApiSetupUtility::SetupMasterApiUser();
if (!FeatureUtility::CheckFeatureEnabled("api"))
/* apilistener config */
std::cout << ConsoleColorTag(Console_Bold)
- << "Please specify the API bind host/port "
- << ConsoleColorTag(Console_Normal) << "(optional)"
- << ConsoleColorTag(Console_Bold) << ":\n";
+ << "Please specify the API bind host/port "
+ << ConsoleColorTag(Console_Normal) << "(optional)"
+ << ConsoleColorTag(Console_Bold) << ":\n";
std::cout << ConsoleColorTag(Console_Bold)
- << "Bind Host" << ConsoleColorTag(Console_Normal) << " []: ";
+ << "Bind Host" << ConsoleColorTag(Console_Normal) << " []: ";
std::getline(std::cin, answer);
bindHost = bindHost.Trim();
std::cout << ConsoleColorTag(Console_Bold)
- << "Bind Port" << ConsoleColorTag(Console_Normal) << " []: ";
+ << "Bind Port" << ConsoleColorTag(Console_Normal) << " []: ";
std::getline(std::cin, answer);
String tempApiConfPath = Utility::CreateTempFile(apiConfPath + ".XXXXXX", 0644, fp);
fp << "/**\n"
- << " * The API listener is used for distributed monitoring setups.\n"
- << " */\n"
- << "object ApiListener \"api\" {\n";
+ << " * The API listener is used for distributed monitoring setups.\n"
+ << " */\n"
+ << "object ApiListener \"api\" {\n";
if (!bindHost.IsEmpty())
fp << " bind_host = \"" << bindHost << "\"\n";
fp << " bind_port = " << bindPort << "\n";
fp << "\n"
- << " ticket_salt = TicketSalt\n"
- << "}\n";
+ << " ticket_salt = TicketSalt\n"
+ << "}\n";
fp.close();
if (rename(tempApiConfPath.CStr(), apiConfPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempApiConfPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempApiConfPath));
}
/* update constants.conf with NodeName = CN + TicketSalt = random value */
if (cn != Utility::GetFQDN()) {
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);
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 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:
int ClientSetup(void) const;
}
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()
("count,c", "display object counts by types")
if (!Utility::PathExists(objectfile)) {
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.");
return 1;
}
}
Log(LogNotice, "cli")
- << "Parsed " << objects_count << " objects.";
+ << "Parsed " << objects_count << " objects.";
return 0;
}
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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;
private:
}
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()
("cn", po::value<std::string>(), "Common Name")
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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 int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
}
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()
- ("key", po::value<std::string>(), "Key file path (input)")
- ("cert", po::value<std::string>(), "Certificate file path (input + output)")
- ("ca", po::value<std::string>(), "CA file path (output)")
- ("trustedcert", po::value<std::string>(), "Trusted certificate file path (input)")
- ("host", po::value<std::string>(), "Icinga 2 host")
- ("port", po::value<std::string>(), "Icinga 2 port")
- ("ticket", po::value<std::string>(), "Icinga 2 PKI ticket");
+ ("key", po::value<std::string>(), "Key file path (input)")
+ ("cert", po::value<std::string>(), "Certificate file path (input + output)")
+ ("ca", po::value<std::string>(), "CA file path (output)")
+ ("trustedcert", po::value<std::string>(), "Trusted certificate file path (input)")
+ ("host", po::value<std::string>(), "Icinga 2 host")
+ ("port", po::value<std::string>(), "Icinga 2 port")
+ ("ticket", po::value<std::string>(), "Icinga 2 PKI ticket");
}
std::vector<String> PKIRequestCommand::GetArgumentSuggestions(const String& argument, const String& word) const
ticket = vm["ticket"].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>()),
- ticket);
+ vm["cert"].as<std::string>(), vm["ca"].as<std::string>(), GetX509Certificate(vm["trustedcert"].as<std::string>()),
+ ticket);
}
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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 int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
}
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()
- ("key", po::value<std::string>(), "Key file path (input), obsolete")
- ("cert", po::value<std::string>(), "Certificate file path (input), obsolete")
- ("trustedcert", po::value<std::string>(), "Trusted certificate file path (output)")
- ("host", po::value<std::string>(), "Icinga 2 host")
- ("port", po::value<std::string>()->default_value("5665"), "Icinga 2 port");
+ ("key", po::value<std::string>(), "Key file path (input), obsolete")
+ ("cert", po::value<std::string>(), "Certificate file path (input), obsolete")
+ ("trustedcert", po::value<std::string>(), "Trusted certificate file path (output)")
+ ("host", po::value<std::string>(), "Icinga 2 host")
+ ("port", po::value<std::string>()->default_value("5665"), "Icinga 2 port");
}
std::vector<String> PKISaveCertCommand::GetArgumentSuggestions(const String& argument, const String& word) const
String port = vm["port"].as<std::string>();
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::cout << PkiUtility::GetCertificateInformation(cert) << "\n";
std::cout << ConsoleColorTag(Console_ForegroundRed)
- << "***\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"
- << "***\n\n"
- << ConsoleColorTag(Console_Normal);
+ << "***\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"
+ << "***\n\n"
+ << ConsoleColorTag(Console_Normal);
return PkiUtility::WriteCert(cert, vm["trustedcert"].as<std::string>());
}
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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 int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
}
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()
- ("csr", po::value<std::string>(), "CSR file path (input)")
- ("cert", po::value<std::string>(), "Certificate file path (output)");
+ ("csr", po::value<std::string>(), "CSR file path (input)")
+ ("cert", po::value<std::string>(), "Certificate file path (output)");
}
std::vector<String> PKISignCSRCommand::GetArgumentSuggestions(const String& argument, const String& word) const
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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 int Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const override;
}
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()
- ("cn", po::value<std::string>(), "Certificate common name")
- ("salt", po::value<std::string>(), "Ticket salt");
+ ("cn", po::value<std::string>(), "Certificate common name")
+ ("salt", po::value<std::string>(), "Ticket salt");
}
/**
virtual String GetDescription(void) const override;
virtual String GetShortDescription(void) const override;
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;
};
if (sev == LogWarning) {
*m_Stream
- << '\n' << ConsoleColorTag(Console_ForegroundYellow, m_ConsoleType) << std::string(24, '#') << '\n'
- << ConsoleColorTag(Console_Normal, m_ConsoleType) << str
- << ConsoleColorTag(Console_ForegroundYellow, m_ConsoleType) << std::string(24, '#') << "\n\n"
- << ConsoleColorTag(Console_Normal, m_ConsoleType);
+ << '\n' << ConsoleColorTag(Console_ForegroundYellow, m_ConsoleType) << std::string(24, '#') << '\n'
+ << ConsoleColorTag(Console_Normal, m_ConsoleType) << str
+ << ConsoleColorTag(Console_ForegroundYellow, m_ConsoleType) << std::string(24, '#') << "\n\n"
+ << ConsoleColorTag(Console_Normal, m_ConsoleType);
} else if (sev == LogCritical) {
*m_Stream
- << '\n' << ConsoleColorTag(Console_ForegroundRed, m_ConsoleType) << std::string(24, '#') << '\n'
- << ConsoleColorTag(Console_Normal, m_ConsoleType) << str
- << ConsoleColorTag(Console_ForegroundRed, m_ConsoleType) << std::string(24, '#') << "\n\n"
- << ConsoleColorTag(Console_Normal, m_ConsoleType);
+ << '\n' << ConsoleColorTag(Console_ForegroundRed, m_ConsoleType) << std::string(24, '#') << '\n'
+ << ConsoleColorTag(Console_Normal, m_ConsoleType) << str
+ << ConsoleColorTag(Console_ForegroundRed, m_ConsoleType) << std::string(24, '#') << "\n\n"
+ << ConsoleColorTag(Console_Normal, m_ConsoleType);
} else
*m_Stream
- << ConsoleColorTag(color, m_ConsoleType) << str
- << ConsoleColorTag(Console_Normal, m_ConsoleType);
+ << ConsoleColorTag(color, m_ConsoleType) << str
+ << ConsoleColorTag(Console_Normal, m_ConsoleType);
}
bool GetStreamHealth(void) const
bool TroubleshootCommand::GeneralInfo(InfoLog& log, const boost::program_options::variables_map& vm)
{
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
InfoLogLine(log)
- << "\tApplication version: " << Application::GetAppVersion() << '\n'
- << "\tInstallation root: " << Application::GetPrefixDir() << '\n'
- << "\tSysconf directory: " << Application::GetSysconfDir() << '\n'
- << "\tRun directory: " << Application::GetRunDir() << '\n'
- << "\tLocal state directory: " << Application::GetLocalStateDir() << '\n'
- << "\tPackage data directory: " << Application::GetPkgDataDir() << '\n'
- << "\tState path: " << Application::GetStatePath() << '\n'
- << "\tObjects path: " << Application::GetObjectsPath() << '\n'
- << "\tVars path: " << Application::GetVarsPath() << '\n'
- << "\tPID path: " << Application::GetPidPath() << '\n';
+ << "\tApplication version: " << Application::GetAppVersion() << '\n'
+ << "\tInstallation root: " << Application::GetPrefixDir() << '\n'
+ << "\tSysconf directory: " << Application::GetSysconfDir() << '\n'
+ << "\tRun directory: " << Application::GetRunDir() << '\n'
+ << "\tLocal state directory: " << Application::GetLocalStateDir() << '\n'
+ << "\tPackage data directory: " << Application::GetPkgDataDir() << '\n'
+ << "\tState path: " << Application::GetStatePath() << '\n'
+ << "\tObjects path: " << Application::GetObjectsPath() << '\n'
+ << "\tVars path: " << Application::GetVarsPath() << '\n'
+ << "\tPID path: " << Application::GetPidPath() << '\n';
InfoLogLine(log)
- << '\n';
+ << '\n';
return true;
}
bool TroubleshootCommand::ObjectInfo(InfoLog& log, const boost::program_options::variables_map& vm, Dictionary::Ptr& logs, const String& path)
{
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();
std::set<String> configs;
if (!Utility::PathExists(objectfile)) {
InfoLogLine(log, 0, LogCritical)
- << "Cannot open object file '" << objectfile << "'.\n"
- << "FAILED: This probably means you have a fault configuration.\n";
+ << "Cannot open object file '" << objectfile << "'.\n"
+ << "FAILED: This probably means you have a fault configuration.\n";
return false;
} else {
InfoLog *OFile = nullptr;
OFile = new InfoLog(path+"-objects", false);
if (!OFile->GetStreamHealth()) {
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;
OFile = nullptr;
} else
InfoLogLine(log)
- << "Printing all objects to " << path+"-objects\n";
+ << "Printing all objects to " << path+"-objects\n";
}
}
CheckObjectFile(objectfile, log, OFile, OConsole, logs, configs);
if (vm.count("include-vars")) {
if (vm.count("console")) {
InfoLogLine(log, Console_ForegroundBlue)
- << "\n[begin: varsfile]\n";
+ << "\n[begin: varsfile]\n";
if (!PrintVarsFile(path, true))
InfoLogLine(log, 0, LogWarning)
- << "Failed to print vars file\n";
+ << "Failed to print vars file\n";
InfoLogLine(log, Console_ForegroundBlue)
- << "[end: varsfile]\n";
+ << "[end: varsfile]\n";
} else {
if (PrintVarsFile(path, false))
InfoLogLine(log)
- << "Successfully printed all variables to " << path+"-vars\n";
+ << "Successfully printed all variables to " << path+"-vars\n";
else
InfoLogLine(log, 0, LogWarning)
- << "Failed to print vars to " << path+"-vars\n";
+ << "Failed to print vars to " << path+"-vars\n";
}
}
InfoLogLine(log)
- << '\n';
+ << '\n';
return true;
}
bool TroubleshootCommand::ReportInfo(InfoLog& log, const boost::program_options::variables_map& vm, Dictionary::Ptr& logs)
{
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);
PrintCrashReports(log);
InfoLogLine(log)
- << '\n';
+ << '\n';
return true;
}
bool TroubleshootCommand::ConfigInfo(InfoLog& log, const boost::program_options::variables_map& vm)
{
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)
- << "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")) {
InfoLogLine(log, 0, LogWarning)
- << "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"
- << "and provide it with your support request.\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"
+ << "and provide it with your support request.\n";
}
if (!PrintFile(log, Application::GetSysconfDir() + "/icinga2/zones.conf")) {
InfoLogLine(log, 0, LogWarning)
- << "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";
+ << "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";
}
InfoLogLine(log)
- << '\n';
+ << '\n';
return true;
}
numLines = lines;
InfoLogLine(log, Console_ForegroundCyan)
- << "[begin: '" << file << "' line: " << lines-numLines << "]\n";
+ << "[begin: '" << file << "' line: " << lines-numLines << "]\n";
for (int k = 0; k < numLines; k++) {
InfoLogLine(log, Console_ForegroundCyan)
- << "# ";
+ << "# ";
InfoLogLine(log)
- << ringBuf[k] << '\n';
+ << ringBuf[k] << '\n';
}
text.close();
InfoLogLine(log, Console_ForegroundCyan)
- << "[end: '" << file << "' line: " << lines << "]\n\n";
+ << "[end: '" << file << "' line: " << lines << "]\n\n";
return numLines;
}
std::vector<String> enabled_features;
if (!FeatureUtility::GetFeatures(disabled_features, true) ||
- !FeatureUtility::GetFeatures(enabled_features, false)) {
+ !FeatureUtility::GetFeatures(enabled_features, false)) {
InfoLogLine(log, 0, LogCritical)
- << "Failed to collect enabled and/or disabled features. Check\n"
- << FeatureUtility::GetFeaturesAvailablePath() << '\n'
- << FeatureUtility::GetFeaturesEnabledPath() << '\n';
+ << "Failed to collect enabled and/or disabled features. Check\n"
+ << FeatureUtility::GetFeaturesAvailablePath() << '\n'
+ << FeatureUtility::GetFeaturesEnabledPath() << '\n';
return false;
}
features->Set(feature, true);
InfoLogLine(log)
- << "Enabled features:\n";
+ << "Enabled features:\n";
InfoLogLine(log, Console_ForegroundGreen)
- << '\t' << boost::algorithm::join(enabled_features, " ") << '\n';
+ << '\t' << boost::algorithm::join(enabled_features, " ") << '\n';
InfoLogLine(log)
- << "Disabled features:\n";
+ << "Disabled features:\n";
InfoLogLine(log, Console_ForegroundRed)
- << '\t' << boost::algorithm::join(disabled_features, " ") << '\n';
+ << '\t' << boost::algorithm::join(disabled_features, " ") << '\n';
if (!features->Get("checker").ToBool())
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())
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())
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;
}
try {
Utility::Glob(spath, std::bind(&GetLatestReport, _1, std::ref(bestTimestamp),
- std::ref(bestFilename)), GlobFile);
+ std::ref(bestFilename)), GlobFile);
}
#ifdef _WIN32
catch (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
InfoLogLine(log, 0, LogWarning)
- << Application::GetLocalStateDir() << "/log/icinga2/crash/ does not exist\n";
+ << Application::GetLocalStateDir() << "/log/icinga2/crash/ does not exist\n";
return false;
}
}
InfoLogLine(log, 0, LogWarning)
- << "Error printing crash reports\n";
+ << "Error printing crash reports\n";
return false;
}
#else
catch (...) {
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;
}
if (!bestTimestamp)
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 {
InfoLogLine(log)
- << "Latest crash report is from " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", Utility::GetTime()) << '\n'
- << "File: " << bestFilename << "\n\n";
+ << "Latest crash report is from " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", Utility::GetTime()) << '\n'
+ << "File: " << bestFilename << "\n\n";
PrintFile(log, bestFilename);
InfoLogLine(log)
- << '\n';
+ << '\n';
}
return true;
std::string line;
InfoLogLine(log, Console_ForegroundCyan)
- << "[begin: '" << path << "']\n";
+ << "[begin: '" << path << "']\n";
while (std::getline(text, line)) {
InfoLogLine(log, Console_ForegroundCyan)
- << "# ";
+ << "# ";
InfoLogLine(log)
- << line << '\n';
+ << line << '\n';
}
InfoLogLine(log, Console_ForegroundCyan)
- << "[end: '" << path << "']\n";
+ << "[end: '" << path << "']\n";
return true;
}
//print is supposed allow the user to print the object file
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)
- << "Checking object file from " << objectfile << '\n';
+ << "Checking object file from " << objectfile << '\n';
std::fstream fp;
fp.open(objectfile.CStr(), std::ios_base::in);
if (!fp.is_open()) {
InfoLogLine(log, 0, LogWarning)
- << "Could not open object file.\n";
+ << "Could not open object file.\n";
return;
}
ObjectListUtility::PrintObject(sStream, first, message, type_count, "", "");
if (OFile) {
InfoLogLine(*OFile)
- << sStream.str();
+ << sStream.str();
sStream.flush();
}
}
if (!countTotal) {
InfoLogLine(log, 0, LogCritical)
- << "No objects found in objectfile.\n";
+ << "No objects found in objectfile.\n";
return;
}
//Print objects with count
InfoLogLine(log)
- << "Found the " << countTotal << " objects:\n"
- << " Type" << std::string(typeL-4, ' ') << " : Count\n";
+ << "Found the " << countTotal << " objects:\n"
+ << " Type" << std::string(typeL-4, ' ') << " : Count\n";
for (const Dictionary::Pair& kv : type_count) {
InfoLogLine(log)
- << " " << kv.first << std::string(typeL - kv.first.GetLength(), ' ')
- << " : " << kv.second << '\n';
+ << " " << kv.first << std::string(typeL - kv.first.GetLength(), ' ')
+ << " : " << kv.second << '\n';
}
InfoLogLine(log)
- << '\n';
+ << '\n';
TroubleshootCommand::PrintObjectOrigin(log, configs);
}
{
if (!logs->GetLength()) {
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 {
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);
for (const Dictionary::Pair& kv : logs) {
InfoLogLine(log)
- << "Logger " << kv.first << " at path: " << kv.second << '\n';
+ << "Logger " << kv.first << " at path: " << kv.second << '\n';
if (!Tail(kv.second, 20, log)) {
InfoLogLine(log, 0, LogWarning)
- << kv.second << " either does not exist or is empty\n";
+ << kv.second << " either does not exist or is empty\n";
}
}
}
void TroubleshootCommand::PrintObjectOrigin(InfoLog& log, const std::set<String>& configSet)
{
InfoLogLine(log)
- << "The objects origins are:\n";
+ << "The objects origins are:\n";
for (const String& config : configSet) {
InfoLogLine(log)
- << " " << config << '\n';
+ << " " << config << '\n';
}
}
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()
("console,c", "print to console instead of file")
{
#ifdef _WIN32 //Dislikes ':' in filenames
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
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*/
InfoLog *log;
double goTime = Utility::GetTime();
InfoLogLine(*log)
- << appName << " -- Troubleshooting help:\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";
+ << appName << " -- Troubleshooting help:\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";
InfoLogLine(*log, Console_ForegroundMagenta)
- << std::string(52, '=') << "\n\n";
+ << std::string(52, '=') << "\n\n";
if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
appName = appName.SubStr(3, appName.GetLength() - 3);
Dictionary::Ptr logs = new Dictionary;
if (!GeneralInfo(*log, vm) ||
- !FeatureInfo(*log, vm) ||
- !ObjectInfo(*log, vm, logs, path) ||
- !ReportInfo(*log, vm, logs) ||
- !ConfigInfo(*log, vm)) {
+ !FeatureInfo(*log, vm) ||
+ !ObjectInfo(*log, vm, logs, path) ||
+ !ReportInfo(*log, vm, logs) ||
+ !ConfigInfo(*log, vm)) {
InfoLogLine(*log, 0, LogCritical)
- << "Could not recover from critical failure, exiting.\n";
+ << "Could not recover from critical failure, exiting.\n";
delete log;
return 3;
double endTime = Utility::GetTime();
InfoLogLine(*log, Console_ForegroundMagenta)
- << std::string(52, '=') << '\n';
+ << std::string(52, '=') << '\n';
InfoLogLine(*log, Console_ForegroundGreen)
- << "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime)
- << "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n";
+ << "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime)
+ << "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n";
if (!vm.count("console")) {
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)
- << "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n\n";
+ << "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime)
+ << "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n\n";
std::cout << "General log file: '" << path << "'\n";
std::cout << "Objects log file: '" << path << "-objects'\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;
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 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:
class InfoLog;
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 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,
- Dictionary::Ptr& logs);
+ Dictionary::Ptr& logs);
static bool ConfigInfo(InfoLog& log, const boost::program_options::variables_map& vm);
static int Tail(const String& file, const int numLines, InfoLog& log);
static bool PrintFile(InfoLog& log, const String& path);
static bool CheckConfig(void);
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 void PrintLoggers(InfoLog& log, Dictionary::Ptr& logs);
static void PrintObjectOrigin(InfoLog& log, const std::set<String>& configSet);
virtual String GetShortDescription(void) const override;
virtual int GetMinArguments(void) const override;
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;
};
if (!Utility::PathExists(varsfile)) {
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.");
return 1;
}
fp.close();
Log(LogNotice, "cli")
- << "Parsed " << variables_count << " variables.";
+ << "Parsed " << variables_count << " variables.";
}
ObjectImpl<CheckResultReader>::Start(runtimeCreated);
Log(LogInformation, "CheckResultReader")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
#ifndef _WIN32
m_ReadTimer = new Timer();
void CheckResultReader::Stop(bool runtimeRemoved)
{
Log(LogInformation, "CheckResultReader")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
ObjectImpl<CheckResultReader>::Stop(runtimeRemoved);
}
/* Remove the checkresult files. */
if (unlink(path.CStr()) < 0)
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("unlink")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("unlink")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
if (unlink(crfile.CStr()) < 0)
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("unlink")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(crfile));
+ << boost::errinfo_api_function("unlink")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(crfile));
Checkable::Ptr checkable;
if (!host) {
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;
}
if (!service) {
Log(LogWarning, "CheckResultReader")
- << "Ignoring checkresult file for host '" << attrs["host_name"]
- << "', service '" << attrs["service_description"] << "': Service does not exist.";
+ << "Ignoring checkresult file for host '" << attrs["host_name"]
+ << "', service '" << attrs["service_description"] << "': Service does not exist.";
return;
}
checkable->ProcessCheckResult(result);
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
* as we receive check result files for a host/service we won't execute any
ObjectImpl<CompatLogger>::Start(runtimeCreated);
Log(LogInformation, "CompatLogger")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
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));
void CompatLogger::Stop(bool runtimeRemoved)
{
Log(LogInformation, "CompatLogger")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
ObjectImpl<CompatLogger>::Stop(runtimeRemoved);
}
bool reachable_before = vars_before->Get("reachable");
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. */
}
if (service) {
msgbuf << "SERVICE ALERT: "
- << host->GetName() << ";"
- << service->GetShortName() << ";"
- << Service::StateToString(service->GetState()) << ";"
- << Service::StateTypeToString(service->GetStateType()) << ";"
- << attempt_after << ";"
- << output << ""
- << "";
+ << host->GetName() << ";"
+ << service->GetShortName() << ";"
+ << Service::StateToString(service->GetState()) << ";"
+ << Service::StateTypeToString(service->GetStateType()) << ";"
+ << attempt_after << ";"
+ << output << ""
+ << "";
} else {
String state = Host::StateToString(Host::CalculateState(static_cast<ServiceState>(state_after)));
msgbuf << "HOST ALERT: "
- << host->GetName() << ";"
- << CompatUtility::GetHostStateString(host) << ";"
- << Host::StateTypeToString(host->GetStateType()) << ";"
- << attempt_after << ";"
- << output << ""
- << "";
+ << host->GetName() << ";"
+ << CompatUtility::GetHostStateString(host) << ";"
+ << Host::StateTypeToString(host->GetStateType()) << ";"
+ << attempt_after << ";"
+ << output << ""
+ << "";
}
* @threadsafety Always.
*/
void CompatLogger::NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
- const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr,
- const String& author, const String& comment_text, const String& command_name)
+ const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr,
+ const String& author, const String& comment_text, const String& command_name)
{
Host::Ptr host;
Service::Ptr service;
String archiveFile = GetLogDir() + "/archives/icinga-" + Utility::FormatDateTime("%m-%d-%Y-%H", Utility::GetTime()) + ".log";
Log(LogNotice, "CompatLogger")
- << "Rotating compat log file '" << tempFile << "' -> '" << archiveFile << "'";
+ << "Rotating compat log file '" << tempFile << "' -> '" << archiveFile << "'";
(void) rename(tempFile.CStr(), archiveFile.CStr());
}
if (!m_OutputFile) {
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;
}
std::ostringstream msgbuf;
msgbuf << "CURRENT HOST STATE: "
- << host->GetName() << ";"
- << CompatUtility::GetHostStateString(host) << ";"
- << Host::StateTypeToString(host->GetStateType()) << ";"
- << host->GetCheckAttempt() << ";"
- << output << "";
+ << host->GetName() << ";"
+ << CompatUtility::GetHostStateString(host) << ";"
+ << Host::StateTypeToString(host->GetStateType()) << ";"
+ << host->GetCheckAttempt() << ";"
+ << output << "";
WriteLine(msgbuf.str());
}
std::ostringstream msgbuf;
msgbuf << "CURRENT SERVICE STATE: "
- << host->GetName() << ";"
- << service->GetShortName() << ";"
- << Service::StateToString(service->GetState()) << ";"
- << Service::StateTypeToString(service->GetStateType()) << ";"
- << service->GetCheckAttempt() << ";"
- << output << "";
+ << host->GetName() << ";"
+ << service->GetShortName() << ";"
+ << Service::StateToString(service->GetState()) << ";"
+ << Service::StateTypeToString(service->GetStateType()) << ";"
+ << service->GetCheckAttempt() << ";"
+ << output << "";
WriteLine(msgbuf.str());
}
if (!temp) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("localtime")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("localtime")
+ << boost::errinfo_errno(errno));
}
tmthen = *temp;
#else /* _MSC_VER */
if (!localtime_r(&now, &tmthen)) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("localtime_r")
- << boost::errinfo_errno(errno));
+ << boost::errinfo_api_function("localtime_r")
+ << boost::errinfo_errno(errno));
}
#endif /* _MSC_VER */
time_t ts = mktime(&tmthen);
Log(LogNotice, "CompatLogger")
- << "Rescheduling rotation timer for compat log '"
- << GetName() << "' to '" << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S %z", ts) << "'";
+ << "Rescheduling rotation timer for compat log '"
+ << GetName() << "' to '" << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S %z", ts) << "'";
m_RotationTimer->Reschedule(ts);
}
ObjectImpl<CompatLogger>::ValidateRotationMethod(value, utils);
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."));
}
}
void CheckResultHandler(const Checkable::Ptr& service, const CheckResult::Ptr& cr);
void NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& service,
- const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr,
- const String& author, const String& comment_text, const String& command_name);
+ const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr,
+ const String& author, const String& comment_text, const String& command_name);
void FlappingChangedHandler(const Checkable::Ptr& checkable);
void EnableFlappingChangedHandler(const Checkable::Ptr& checkable);
void TriggerDowntimeHandler(const Downtime::Ptr& downtime);
ObjectImpl<ExternalCommandListener>::Start(runtimeCreated);
Log(LogInformation, "ExternalCommandListener")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
#ifndef _WIN32
m_CommandThread = std::thread(std::bind(&ExternalCommandListener::CommandPipeThread, this, GetCommandPath()));
void ExternalCommandListener::Stop(bool runtimeRemoved)
{
Log(LogInformation, "ExternalCommandListener")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
ObjectImpl<ExternalCommandListener>::Stop(runtimeRemoved);
}
} else {
if (unlink(commandPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("unlink")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(commandPath));
+ << boost::errinfo_api_function("unlink")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(commandPath));
}
}
}
if (!fifo_ok && mkfifo(commandPath.CStr(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0) {
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;
}
* fifo to get the right mask. */
if (chmod(commandPath.CStr(), mode) < 0) {
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;
}
if (fd < 0) {
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;
}
continue;
Log(LogWarning, "ExternalCommandListener")
- << "Cannot read from command pipe." << DiagnosticInformation(ex);
+ << "Cannot read from command pipe." << DiagnosticInformation(ex);
break;
}
try {
Log(LogInformation, "ExternalCommandListener")
- << "Executing external command: " << command;
+ << "Executing external command: " << command;
ExternalCommandProcessor::Execute(command);
} catch (const std::exception& ex) {
Log(LogWarning, "ExternalCommandListener")
- << "External command failed: " << DiagnosticInformation(ex, false);
+ << "External command failed: " << DiagnosticInformation(ex, false);
Log(LogNotice, "ExternalCommandListener")
- << "External command failed: " << DiagnosticInformation(ex, true);
+ << "External command failed: " << DiagnosticInformation(ex, true);
}
}
}
ObjectImpl<StatusDataWriter>::Start(runtimeCreated);
Log(LogInformation, "StatusDataWriter")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
m_ObjectsCacheOutdated = true;
void StatusDataWriter::Stop(bool runtimeRemoved)
{
Log(LogInformation, "StatusDataWriter")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
ObjectImpl<StatusDataWriter>::Stop(runtimeRemoved);
}
if (service)
fp << "servicecomment {" << "\n"
- << "\t" << "service_description=" << service->GetShortName() << "\n";
+ << "\t" << "service_description=" << service->GetShortName() << "\n";
else
fp << "hostcomment {" << "\n";
fp << "\t" "host_name=" << host->GetName() << "\n"
- "\t" "comment_id=" << comment->GetLegacyId() << "\n"
- "\t" "entry_time=" << comment->GetEntryTime() << "\n"
- "\t" "entry_type=" << comment->GetEntryType() << "\n"
- "\t" "persistent=" "1" "\n"
- "\t" "author=" << comment->GetAuthor() << "\n"
- "\t" "comment_data=" << comment->GetText() << "\n"
- "\t" "expires=" << (comment->GetExpireTime() != 0 ? 1 : 0) << "\n"
- "\t" "expire_time=" << comment->GetExpireTime() << "\n"
- "\t" "}" "\n"
- "\n";
+ "\t" "comment_id=" << comment->GetLegacyId() << "\n"
+ "\t" "entry_time=" << comment->GetEntryTime() << "\n"
+ "\t" "entry_type=" << comment->GetEntryType() << "\n"
+ "\t" "persistent=" "1" "\n"
+ "\t" "author=" << comment->GetAuthor() << "\n"
+ "\t" "comment_data=" << comment->GetText() << "\n"
+ "\t" "expires=" << (comment->GetExpireTime() != 0 ? 1 : 0) << "\n"
+ "\t" "expire_time=" << comment->GetExpireTime() << "\n"
+ "\t" "}" "\n"
+ "\n";
}
}
void StatusDataWriter::DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& tp)
{
fp << "define timeperiod {" "\n"
- "\t" "timeperiod_name" "\t" << tp->GetName() << "\n"
- "\t" "alias" "\t" << tp->GetName() << "\n";
+ "\t" "timeperiod_name" "\t" << tp->GetName() << "\n"
+ "\t" "alias" "\t" << tp->GetName() << "\n";
Dictionary::Ptr ranges = tp->GetRanges();
}
}
- fp << "\t" "}" "\n"
- "\n";
+ fp << "\t" "}" "\n" "\n";
}
void StatusDataWriter::DumpCommand(std::ostream& fp, const Command::Ptr& command)
{
fp << "define command {" "\n"
- "\t" "command_name\t";
+ "\t" "command_name\t";
fp << CompatUtility::GetCommandName(command) << "\n";
DumpCustomAttributes(fp, command);
- fp << "\n" "\t" "}" "\n"
- "\n";
+ fp << "\n" "\t" "}" "\n" "\n";
}
void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Checkable::Ptr& checkable)
if (service)
fp << "servicedowntime {" << "\n"
- "\t" "service_description=" << service->GetShortName() << "\n";
+ "\t" "service_description=" << service->GetShortName() << "\n";
else
fp << "hostdowntime {" "\n";
triggeredByLegacy = triggeredByObj->GetLegacyId();
fp << "\t" << "host_name=" << host->GetName() << "\n"
- "\t" "downtime_id=" << downtime->GetLegacyId() << "\n"
- "\t" "entry_time=" << downtime->GetEntryTime() << "\n"
- "\t" "start_time=" << downtime->GetStartTime() << "\n"
- "\t" "end_time=" << downtime->GetEndTime() << "\n"
- "\t" "triggered_by=" << triggeredByLegacy << "\n"
- "\t" "fixed=" << static_cast<long>(downtime->GetFixed()) << "\n"
- "\t" "duration=" << static_cast<long>(downtime->GetDuration()) << "\n"
- "\t" "is_in_effect=" << (downtime->IsInEffect() ? 1 : 0) << "\n"
- "\t" "author=" << downtime->GetAuthor() << "\n"
- "\t" "comment=" << downtime->GetComment() << "\n"
- "\t" "trigger_time=" << downtime->GetTriggerTime() << "\n"
- "\t" "}" "\n"
- "\n";
+ "\t" "downtime_id=" << downtime->GetLegacyId() << "\n"
+ "\t" "entry_time=" << downtime->GetEntryTime() << "\n"
+ "\t" "start_time=" << downtime->GetStartTime() << "\n"
+ "\t" "end_time=" << downtime->GetEndTime() << "\n"
+ "\t" "triggered_by=" << triggeredByLegacy << "\n"
+ "\t" "fixed=" << static_cast<long>(downtime->GetFixed()) << "\n"
+ "\t" "duration=" << static_cast<long>(downtime->GetDuration()) << "\n"
+ "\t" "is_in_effect=" << (downtime->IsInEffect() ? 1 : 0) << "\n"
+ "\t" "author=" << downtime->GetAuthor() << "\n"
+ "\t" "comment=" << downtime->GetComment() << "\n"
+ "\t" "trigger_time=" << downtime->GetTriggerTime() << "\n"
+ "\t" "}" "\n"
+ "\n";
}
}
void StatusDataWriter::DumpHostStatus(std::ostream& fp, const Host::Ptr& host)
{
- fp << "hoststatus {" << "\n"
- << "\t" << "host_name=" << host->GetName() << "\n";
+ fp << "hoststatus {" "\n" "\t" "host_name=" << host->GetName() << "\n";
{
ObjectLock olock(host);
/* ugly but cgis parse only that */
fp << "\t" "last_time_up=" << host->GetLastStateUp() << "\n"
- "\t" "last_time_down=" << host->GetLastStateDown() << "\n"
- "\t" "last_time_unreachable=" << host->GetLastStateUnreachable() << "\n";
+ "\t" "last_time_down=" << host->GetLastStateDown() << "\n"
+ "\t" "last_time_unreachable=" << host->GetLastStateUnreachable() << "\n";
- fp << "\t" "}" "\n"
- "\n";
+ fp << "\t" "}" "\n" "\n";
DumpDowntimes(fp, host);
DumpComments(fp, host);
String address6 = host->GetAddress6();
fp << "define host {" "\n"
- "\t" "host_name" "\t" << host->GetName() << "\n";
+ "\t" "host_name" "\t" << host->GetName() << "\n";
if (!display_name.IsEmpty()) {
- fp << "\t" "display_name" "\t" << host->GetDisplayName() << "\n"
- "\t" "alias" "\t" << host->GetDisplayName() << "\n";
+ fp << "\t" "display_name" "\t" << host->GetDisplayName() << "\n"
+ "\t" "alias" "\t" << host->GetDisplayName() << "\n";
}
if (!address.IsEmpty())
- fp << "\t" "address" "\t" << address << "\n";
+ fp << "\t" "address" "\t" << address << "\n";
if (!address6.IsEmpty())
- fp << "\t" "address6" "\t" << address6 << "\n";
+ fp << "\t" "address6" "\t" << address6 << "\n";
if (!notes.IsEmpty())
- fp << "\t" "notes" "\t" << notes << "\n";
+ fp << "\t" "notes" "\t" << notes << "\n";
if (!notes_url.IsEmpty())
- fp << "\t" "notes_url" "\t" << notes_url << "\n";
+ fp << "\t" "notes_url" "\t" << notes_url << "\n";
if (!action_url.IsEmpty())
- fp << "\t" "action_url" "\t" << action_url << "\n";
+ fp << "\t" "action_url" "\t" << action_url << "\n";
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())
- 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();
ObjectLock olock(host);
fp << "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(host) << "\n"
- "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(host) << "\n"
- "\t" "max_check_attempts" "\t" << host->GetMaxCheckAttempts() << "\n"
- "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(host) << "\n"
- "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(host) << "\n"
- "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(host) << "\n"
- "\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(host) << "\n"
- "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(host) << "\n"
- "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(host) << "\n";
+ "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(host) << "\n"
+ "\t" "max_check_attempts" "\t" << host->GetMaxCheckAttempts() << "\n"
+ "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(host) << "\n"
+ "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(host) << "\n"
+ "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(host) << "\n"
+ "\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(host) << "\n"
+ "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(host) << "\n"
+ "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(host) << "\n";
CheckCommand::Ptr checkcommand = host->GetCheckCommand();
if (checkcommand)
fp << "\n";
fp << "\t" << "initial_state" "\t" "o" "\n"
- "\t" "low_flap_threshold" "\t" << host->GetFlappingThresholdLow() << "\n"
- "\t" "high_flap_threshold" "\t" << host->GetFlappingThresholdHigh() << "\n"
- "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(host) << "\n"
- "\t" "check_freshness" "\t" "1" "\n";
+ "\t" "low_flap_threshold" "\t" << host->GetFlappingThresholdLow() << "\n"
+ "\t" "high_flap_threshold" "\t" << host->GetFlappingThresholdHigh() << "\n"
+ "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(host) << "\n"
+ "\t" "check_freshness" "\t" "1" "\n";
fp << "\t" "host_groups" "\t";
bool first = true;
DumpCustomAttributes(fp, host);
- fp << "\t" "}" "\n"
- "\n";
+ fp << "\t" "}" "\n" "\n";
}
void StatusDataWriter::DumpCheckableStatusAttrs(std::ostream& fp, const Checkable::Ptr& checkable)
CheckCommand::Ptr checkcommand = checkable->GetCheckCommand();
fp << "\t" << "check_command=" << CompatUtility::GetCommandName(checkcommand) << "!" << CompatUtility::GetCheckableCommandArgs(checkable) << "\n"
- "\t" "event_handler=" << CompatUtility::GetCommandName(eventcommand) << "\n"
- "\t" "check_period=" << CompatUtility::GetCheckableCheckPeriod(checkable) << "\n"
- "\t" "check_interval=" << CompatUtility::GetCheckableCheckInterval(checkable) << "\n"
- "\t" "retry_interval=" << CompatUtility::GetCheckableRetryInterval(checkable) << "\n"
- "\t" "has_been_checked=" << CompatUtility::GetCheckableHasBeenChecked(checkable) << "\n"
- "\t" "should_be_scheduled=" << checkable->GetEnableActiveChecks() << "\n"
- "\t" "event_handler_enabled=" << CompatUtility::GetCheckableEventHandlerEnabled(checkable) << "\n";
+ "\t" "event_handler=" << CompatUtility::GetCommandName(eventcommand) << "\n"
+ "\t" "check_period=" << CompatUtility::GetCheckableCheckPeriod(checkable) << "\n"
+ "\t" "check_interval=" << CompatUtility::GetCheckableCheckInterval(checkable) << "\n"
+ "\t" "retry_interval=" << CompatUtility::GetCheckableRetryInterval(checkable) << "\n"
+ "\t" "has_been_checked=" << CompatUtility::GetCheckableHasBeenChecked(checkable) << "\n"
+ "\t" "should_be_scheduled=" << checkable->GetEnableActiveChecks() << "\n"
+ "\t" "event_handler_enabled=" << CompatUtility::GetCheckableEventHandlerEnabled(checkable) << "\n";
if (cr) {
- fp << "\t" << "check_execution_time=" << Convert::ToString(cr->CalculateExecutionTime()) << "\n"
- "\t" "check_latency=" << Convert::ToString(cr->CalculateLatency()) << "\n";
+ fp << "\t" << "check_execution_time=" << Convert::ToString(cr->CalculateExecutionTime()) << "\n"
+ "\t" "check_latency=" << Convert::ToString(cr->CalculateLatency()) << "\n";
}
Host::Ptr host;
if (service) {
fp << "\t" "current_state=" << service->GetState() << "\n"
- "\t" "last_hard_state=" << service->GetLastHardState() << "\n"
- "\t" "last_time_ok=" << static_cast<int>(service->GetLastStateOK()) << "\n"
- "\t" "last_time_warn=" << static_cast<int>(service->GetLastStateWarning()) << "\n"
- "\t" "last_time_critical=" << static_cast<int>(service->GetLastStateCritical()) << "\n"
- "\t" "last_time_unknown=" << static_cast<int>(service->GetLastStateUnknown()) << "\n";
+ "\t" "last_hard_state=" << service->GetLastHardState() << "\n"
+ "\t" "last_time_ok=" << static_cast<int>(service->GetLastStateOK()) << "\n"
+ "\t" "last_time_warn=" << static_cast<int>(service->GetLastStateWarning()) << "\n"
+ "\t" "last_time_critical=" << static_cast<int>(service->GetLastStateCritical()) << "\n"
+ "\t" "last_time_unknown=" << static_cast<int>(service->GetLastStateUnknown()) << "\n";
} else {
fp << "\t" "current_state=" << CompatUtility::GetHostCurrentState(host) << "\n"
- "\t" "last_hard_state=" << host->GetLastHardState() << "\n"
- "\t" "last_time_up=" << static_cast<int>(host->GetLastStateUp()) << "\n"
- "\t" "last_time_down=" << static_cast<int>(host->GetLastStateDown()) << "\n";
+ "\t" "last_hard_state=" << host->GetLastHardState() << "\n"
+ "\t" "last_time_up=" << static_cast<int>(host->GetLastStateUp()) << "\n"
+ "\t" "last_time_down=" << static_cast<int>(host->GetLastStateDown()) << "\n";
}
fp << "\t" "state_type=" << checkable->GetStateType() << "\n"
- "\t" "plugin_output=" << CompatUtility::GetCheckResultOutput(cr) << "\n"
- "\t" "long_plugin_output=" << CompatUtility::GetCheckResultLongOutput(cr) << "\n"
- "\t" "performance_data=" << CompatUtility::GetCheckResultPerfdata(cr) << "\n";
+ "\t" "plugin_output=" << CompatUtility::GetCheckResultOutput(cr) << "\n"
+ "\t" "long_plugin_output=" << CompatUtility::GetCheckResultLongOutput(cr) << "\n"
+ "\t" "performance_data=" << CompatUtility::GetCheckResultPerfdata(cr) << "\n";
if (cr) {
- fp << "\t" << "check_source=" << cr->GetCheckSource() << "\n"
- "\t" "last_check=" << static_cast<long>(cr->GetScheduleEnd()) << "\n";
+ fp << "\t" << "check_source=" << cr->GetCheckSource() << "\n"
+ "\t" "last_check=" << static_cast<long>(cr->GetScheduleEnd()) << "\n";
}
fp << "\t" << "next_check=" << static_cast<long>(checkable->GetNextCheck()) << "\n"
- "\t" "current_attempt=" << checkable->GetCheckAttempt() << "\n"
- "\t" "max_attempts=" << checkable->GetMaxCheckAttempts() << "\n"
- "\t" "last_state_change=" << static_cast<long>(checkable->GetLastStateChange()) << "\n"
- "\t" "last_hard_state_change=" << static_cast<long>(checkable->GetLastHardStateChange()) << "\n"
- "\t" "last_update=" << static_cast<long>(time(nullptr)) << "\n"
- "\t" "notifications_enabled=" << CompatUtility::GetCheckableNotificationsEnabled(checkable) << "\n"
- "\t" "active_checks_enabled=" << CompatUtility::GetCheckableActiveChecksEnabled(checkable) << "\n"
- "\t" "passive_checks_enabled=" << CompatUtility::GetCheckablePassiveChecksEnabled(checkable) << "\n"
- "\t" "flap_detection_enabled=" << CompatUtility::GetCheckableFlapDetectionEnabled(checkable) << "\n"
- "\t" "is_flapping=" << CompatUtility::GetCheckableIsFlapping(checkable) << "\n"
- "\t" "percent_state_change=" << CompatUtility::GetCheckablePercentStateChange(checkable) << "\n"
- "\t" "problem_has_been_acknowledged=" << CompatUtility::GetCheckableProblemHasBeenAcknowledged(checkable) << "\n"
- "\t" "acknowledgement_type=" << CompatUtility::GetCheckableAcknowledgementType(checkable) << "\n"
- "\t" "acknowledgement_end_time=" << checkable->GetAcknowledgementExpiry() << "\n"
- "\t" "scheduled_downtime_depth=" << checkable->GetDowntimeDepth() << "\n"
- "\t" "last_notification=" << CompatUtility::GetCheckableNotificationLastNotification(checkable) << "\n"
- "\t" "next_notification=" << CompatUtility::GetCheckableNotificationNextNotification(checkable) << "\n"
- "\t" "current_notification_number=" << CompatUtility::GetCheckableNotificationNotificationNumber(checkable) << "\n"
- "\t" "is_reachable=" << CompatUtility::GetCheckableIsReachable(checkable) << "\n";
+ "\t" "current_attempt=" << checkable->GetCheckAttempt() << "\n"
+ "\t" "max_attempts=" << checkable->GetMaxCheckAttempts() << "\n"
+ "\t" "last_state_change=" << static_cast<long>(checkable->GetLastStateChange()) << "\n"
+ "\t" "last_hard_state_change=" << static_cast<long>(checkable->GetLastHardStateChange()) << "\n"
+ "\t" "last_update=" << static_cast<long>(time(nullptr)) << "\n"
+ "\t" "notifications_enabled=" << CompatUtility::GetCheckableNotificationsEnabled(checkable) << "\n"
+ "\t" "active_checks_enabled=" << CompatUtility::GetCheckableActiveChecksEnabled(checkable) << "\n"
+ "\t" "passive_checks_enabled=" << CompatUtility::GetCheckablePassiveChecksEnabled(checkable) << "\n"
+ "\t" "flap_detection_enabled=" << CompatUtility::GetCheckableFlapDetectionEnabled(checkable) << "\n"
+ "\t" "is_flapping=" << CompatUtility::GetCheckableIsFlapping(checkable) << "\n"
+ "\t" "percent_state_change=" << CompatUtility::GetCheckablePercentStateChange(checkable) << "\n"
+ "\t" "problem_has_been_acknowledged=" << CompatUtility::GetCheckableProblemHasBeenAcknowledged(checkable) << "\n"
+ "\t" "acknowledgement_type=" << CompatUtility::GetCheckableAcknowledgementType(checkable) << "\n"
+ "\t" "acknowledgement_end_time=" << checkable->GetAcknowledgementExpiry() << "\n"
+ "\t" "scheduled_downtime_depth=" << checkable->GetDowntimeDepth() << "\n"
+ "\t" "last_notification=" << CompatUtility::GetCheckableNotificationLastNotification(checkable) << "\n"
+ "\t" "next_notification=" << CompatUtility::GetCheckableNotificationNextNotification(checkable) << "\n"
+ "\t" "current_notification_number=" << CompatUtility::GetCheckableNotificationNotificationNumber(checkable) << "\n"
+ "\t" "is_reachable=" << CompatUtility::GetCheckableIsReachable(checkable) << "\n";
}
void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& service)
Host::Ptr host = service->GetHost();
fp << "servicestatus {" "\n"
- "\t" "host_name=" << host->GetName() << "\n"
- "\t" "service_description=" << service->GetShortName() << "\n";
+ "\t" "host_name=" << host->GetName() << "\n"
+ "\t" "service_description=" << service->GetShortName() << "\n";
{
ObjectLock olock(service);
DumpCheckableStatusAttrs(fp, service);
}
- fp << "\t" "}" "\n"
- "\n";
+ fp << "\t" "}" "\n" "\n";
DumpDowntimes(fp, service);
DumpComments(fp, service);
ObjectLock olock(service);
fp << "define service {" "\n"
- "\t" "host_name" "\t" << host->GetName() << "\n"
- "\t" "service_description" "\t" << service->GetShortName() << "\n"
- "\t" "display_name" "\t" << service->GetDisplayName() << "\n"
- "\t" "check_period" "\t" << CompatUtility::GetCheckableCheckPeriod(service) << "\n"
- "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(service) << "\n"
- "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(service) << "\n"
- "\t" "max_check_attempts" "\t" << service->GetMaxCheckAttempts() << "\n"
- "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(service) << "\n"
- "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(service) << "\n"
- "\t" "flap_detection_enabled" "\t" << CompatUtility::GetCheckableFlapDetectionEnabled(service) << "\n"
- "\t" "is_volatile" "\t" << CompatUtility::GetCheckableIsVolatile(service) << "\n"
- "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(service) << "\n"
- "\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(service) << "\n"
- "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(service) << "\n"
- "\t" "notification_period" "\t" << "" << "\n"
- "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(service) << "\n";
+ "\t" "host_name" "\t" << host->GetName() << "\n"
+ "\t" "service_description" "\t" << service->GetShortName() << "\n"
+ "\t" "display_name" "\t" << service->GetDisplayName() << "\n"
+ "\t" "check_period" "\t" << CompatUtility::GetCheckableCheckPeriod(service) << "\n"
+ "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(service) << "\n"
+ "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(service) << "\n"
+ "\t" "max_check_attempts" "\t" << service->GetMaxCheckAttempts() << "\n"
+ "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(service) << "\n"
+ "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(service) << "\n"
+ "\t" "flap_detection_enabled" "\t" << CompatUtility::GetCheckableFlapDetectionEnabled(service) << "\n"
+ "\t" "is_volatile" "\t" << CompatUtility::GetCheckableIsVolatile(service) << "\n"
+ "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(service) << "\n"
+ "\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(service) << "\n"
+ "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(service) << "\n"
+ "\t" "notification_period" "\t" << "" << "\n"
+ "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(service) << "\n";
CheckCommand::Ptr checkcommand = service->GetCheckCommand();
if (checkcommand)
String icon_image_alt = service->GetIconImageAlt();
fp << "\t" "initial_state" "\t" "o" "\n"
- "\t" "low_flap_threshold" "\t" << service->GetFlappingThresholdLow() << "\n"
- "\t" "high_flap_threshold" "\t" << service->GetFlappingThresholdHigh() << "\n"
- "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(service) << "\n"
- "\t" "check_freshness" << "\t" "1" "\n";
+ "\t" "low_flap_threshold" "\t" << service->GetFlappingThresholdLow() << "\n"
+ "\t" "high_flap_threshold" "\t" << service->GetFlappingThresholdHigh() << "\n"
+ "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(service) << "\n"
+ "\t" "check_freshness" << "\t" "1" "\n";
if (!notes.IsEmpty())
- fp << "\t" "notes" "\t" << notes << "\n";
+ fp << "\t" "notes" "\t" << notes << "\n";
if (!notes_url.IsEmpty())
- fp << "\t" "notes_url" "\t" << notes_url << "\n";
+ fp << "\t" "notes_url" "\t" << notes_url << "\n";
if (!action_url.IsEmpty())
- fp << "\t" "action_url" "\t" << action_url << "\n";
+ fp << "\t" "action_url" "\t" << action_url << "\n";
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())
- 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";
DumpCustomAttributes(fp, service);
- fp << "\t" "}" "\n"
- "\n";
+ fp << "\t" "}" "\n" "\n";
}
void StatusDataWriter::DumpCustomAttributes(std::ostream& fp, const CustomVarObject::Ptr& object)
objectfp << std::fixed;
objectfp << "# Icinga objects cache file" "\n"
- "# This file is auto-generated. Do not modify this file." "\n"
- "\n";
+ "# This file is auto-generated. Do not modify this file." "\n"
+ "\n";
for (const Host::Ptr& host : ConfigType::GetObjectsByType<Host>()) {
std::ostringstream tempobjectfp;
if (!notes.IsEmpty())
tempobjectfp << "\t" "notes" "\t" << notes << "\n";
if (!notes_url.IsEmpty())
- tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n";
+ tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n";
if (!action_url.IsEmpty())
- tempobjectfp << "\t" "action_url" "\t" << action_url << "\n";
+ tempobjectfp << "\t" "action_url" "\t" << action_url << "\n";
DumpCustomAttributes(tempobjectfp, hg);
tempobjectfp << "\t" "members" "\t";
DumpNameList(tempobjectfp, hg->GetMembers());
- tempobjectfp << "\n"
- "\t" "}" "\n";
+ tempobjectfp << "\n" "\t" "}" "\n";
objectfp << tempobjectfp.str();
}
String action_url = sg->GetActionUrl();
tempobjectfp << "define servicegroup {" "\n"
- "\t" "servicegroup_name" "\t" << sg->GetName() << "\n";
+ "\t" "servicegroup_name" "\t" << sg->GetName() << "\n";
if (!display_name.IsEmpty())
tempobjectfp << "\t" "alias" "\t" << display_name << "\n";
if (!notes.IsEmpty())
tempobjectfp << "\t" "notes" "\t" << notes << "\n";
if (!notes_url.IsEmpty())
- tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n";
+ tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n";
if (!action_url.IsEmpty())
- tempobjectfp << "\t" "action_url" "\t" << action_url << "\n";
+ tempobjectfp << "\t" "action_url" "\t" << action_url << "\n";
DumpCustomAttributes(tempobjectfp, sg);
DumpStringList(tempobjectfp, sglist);
- tempobjectfp << "\n"
- "}" "\n";
+ tempobjectfp << "\n" "}" "\n";
objectfp << tempobjectfp.str();
}
tempobjectfp << "\t" "pager" "\t" << pager << "\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_notifications_enabled" "\t" "1" "\n"
- "\t" "service_notifications_enabled" "\t" "1" "\n"
- "\t" "}" "\n"
- "\n";
+ "\t" "host_notification_options""\t" "d,u,r,f,s" "\n"
+ "\t" "host_notifications_enabled" "\t" "1" "\n"
+ "\t" "service_notifications_enabled" "\t" "1" "\n"
+ "\t" "}" "\n"
+ "\n";
objectfp << tempobjectfp.str();
}
if (!parent) {
Log(LogDebug, "StatusDataWriter")
- << "Missing parent for dependency '" << dep->GetName() << "'.";
+ << "Missing parent for dependency '" << dep->GetName() << "'.";
continue;
}
if (!child) {
Log(LogDebug, "StatusDataWriter")
- << "Missing child for dependency '" << dep->GetName() << "'.";
+ << "Missing child for dependency '" << dep->GetName() << "'.";
continue;
}
/* Icinga 1.x only allows host->host, service->service dependencies */
if (!child_service && !parent_service) {
objectfp << "define hostdependency {" "\n"
- "\t" "dependent_host_name" "\t" << child_host->GetName() << "\n"
- "\t" "host_name" "\t" << parent_host->GetName() << "\n"
- "\t" "execution_failure_criteria" "\t" << criteria << "\n"
- "\t" "notification_failure_criteria" "\t" << criteria << "\n"
- "\t" "}" "\n"
- "\n";
+ "\t" "dependent_host_name" "\t" << child_host->GetName() << "\n"
+ "\t" "host_name" "\t" << parent_host->GetName() << "\n"
+ "\t" "execution_failure_criteria" "\t" << criteria << "\n"
+ "\t" "notification_failure_criteria" "\t" << criteria << "\n"
+ "\t" "}" "\n"
+ "\n";
} else if (child_service && parent_service){
objectfp << "define servicedependency {" "\n"
- "\t" "dependent_host_name" "\t" << child_service->GetHost()->GetName() << "\n"
- "\t" "dependent_service_description" "\t" << child_service->GetShortName() << "\n"
- "\t" "host_name" "\t" << parent_service->GetHost()->GetName() << "\n"
- "\t" "service_description" "\t" << parent_service->GetShortName() << "\n"
- "\t" "execution_failure_criteria" "\t" << criteria << "\n"
- "\t" "notification_failure_criteria" "\t" << criteria << "\n"
- "\t" "}" "\n"
- "\n";
+ "\t" "dependent_host_name" "\t" << child_service->GetHost()->GetName() << "\n"
+ "\t" "dependent_service_description" "\t" << child_service->GetShortName() << "\n"
+ "\t" "host_name" "\t" << parent_service->GetHost()->GetName() << "\n"
+ "\t" "service_description" "\t" << parent_service->GetShortName() << "\n"
+ "\t" "execution_failure_criteria" "\t" << criteria << "\n"
+ "\t" "notification_failure_criteria" "\t" << criteria << "\n"
+ "\t" "}" "\n"
+ "\n";
}
}
if (rename(tempObjectsPath.CStr(), objectsPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempObjectsPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempObjectsPath));
}
}
statusfp << std::fixed;
statusfp << "# Icinga status file" "\n"
- "# This file is auto-generated. Do not modify this file." "\n"
- "\n";
+ "# This file is auto-generated. Do not modify this file." "\n"
+ "\n";
statusfp << "info {" "\n"
- "\t" "created=" << Utility::GetTime() << "\n"
- "\t" "version=" << Application::GetAppVersion() << "\n"
- "\t" "}" "\n"
- "\n";
+ "\t" "created=" << Utility::GetTime() << "\n"
+ "\t" "version=" << Application::GetAppVersion() << "\n"
+ "\t" "}" "\n"
+ "\n";
statusfp << "programstatus {" "\n"
- "\t" "icinga_pid=" << Utility::GetPid() << "\n"
- "\t" "daemon_mode=1" "\n"
- "\t" "program_start=" << static_cast<long>(Application::GetStartTime()) << "\n"
- "\t" "active_host_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableHostChecks() ? 1 : 0) << "\n"
- "\t" "passive_host_checks_enabled=1" "\n"
- "\t" "active_service_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableServiceChecks() ? 1 : 0) << "\n"
- "\t" "passive_service_checks_enabled=1" "\n"
- "\t" "check_service_freshness=1" "\n"
- "\t" "check_host_freshness=1" "\n"
- "\t" "enable_notifications=" << (IcingaApplication::GetInstance()->GetEnableNotifications() ? 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_failure_prediction=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" "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" "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_comment_id=" << Comment::GetNextCommentID() << "\n";
+ "\t" "icinga_pid=" << Utility::GetPid() << "\n"
+ "\t" "daemon_mode=1" "\n"
+ "\t" "program_start=" << static_cast<long>(Application::GetStartTime()) << "\n"
+ "\t" "active_host_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableHostChecks() ? 1 : 0) << "\n"
+ "\t" "passive_host_checks_enabled=1" "\n"
+ "\t" "active_service_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableServiceChecks() ? 1 : 0) << "\n"
+ "\t" "passive_service_checks_enabled=1" "\n"
+ "\t" "check_service_freshness=1" "\n"
+ "\t" "check_host_freshness=1" "\n"
+ "\t" "enable_notifications=" << (IcingaApplication::GetInstance()->GetEnableNotifications() ? 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_failure_prediction=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" "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" "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_comment_id=" << Comment::GetNextCommentID() << "\n";
statusfp << "\t" "}" "\n"
- "\n";
+ "\n";
for (const Host::Ptr& host : ConfigType::GetObjectsByType<Host>()) {
std::ostringstream tempstatusfp;
if (rename(tempStatusPath.CStr(), statusPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempStatusPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempStatusPath));
}
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)
}
ActivationScope::ActivationScope(const ActivationContext::Ptr& context)
- : m_Context(context)
+ : m_Context(context)
{
if (!m_Context)
m_Context = new ActivationContext();
ApplyRule::TypeMap ApplyRule::m_Types;
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,
- bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope)
+ 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)
: 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
}
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 String& fvvar, const std::shared_ptr<Expression>& fterm, bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope)
+ 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)
{
m_Rules[sourceType].push_back(ApplyRule(targetType, name, expression, filter, package, fkvar, fvvar, fterm, ignoreOnError, di, scope));
}
for (const ApplyRule& rule : kv.second) {
if (!rule.HasMatches())
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!";
}
}
}
bool EvaluateFilter(ScriptFrame& frame) const;
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,
- bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope);
+ 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);
static std::vector<ApplyRule>& GetRules(const String& type);
static void RegisterType(const String& sourceType, const std::vector<String>& targetTypes);
static RuleMap m_Rules;
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,
- bool ignoreOnError, const DebugInfo& di, const Dictionary::Ptr& scope);
+ 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);
};
}
while (*yptr)
yyextra->m_LexBuffer << *yptr++;
- }
+ }
<STRING><<EOF>> {
BOOST_THROW_EXCEPTION(ScriptError("End-of-file while in string literal", DebugInfoRange(yyextra->m_LocationBegin, *yylloc)));
}
$$ = 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;
}
;
* Constructor for the ConfigCompiler class.
*
* @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 zone The zone.
*/
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_Eof(false), m_OpenBraces(0)
+ m_Eof(false), m_OpenBraces(0)
{
InitializeScanner();
}
}
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 {
expressions.emplace_back(CompileFile(file, zone, package));
} catch (const std::exception& ex) {
Log(LogWarning, "ConfigCompiler")
- << "Cannot compile file '"
- << file << "': " << DiagnosticInformation(ex);
+ << "Cannot compile file '"
+ << file << "': " << DiagnosticInformation(ex);
}
}
* @param debuginfo Debug information.
*/
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;
* @param debuginfo Debug information.
*/
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;
* @param debuginfo Debug information.
*/
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 newRelativeBase = relativeBase;
* @returns Configuration items.
*/
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 + "'");
* @returns Configuration items.
*/
std::unique_ptr<Expression> ConfigCompiler::CompileFile(const String& path, const String& zone,
- const String& package)
+ const String& package)
{
CONTEXT("Compiling configuration file '" + path + "'");
<< boost::errinfo_file_name(path));
Log(LogNotice, "ConfigCompiler")
- << "Compiling config file: " << path;
+ << "Compiling config file: " << path;
return CompileStream(path, &stream, zone, package);
}
* @returns Configuration items.
*/
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);
return CompileStream(path, &stream, zone, package);
void ConfigCompiler::AddIncludeSearchDir(const String& dir)
{
Log(LogInformation, "ConfigCompiler")
- << "Adding include search dir: " << dir;
+ << "Adding include search dir: " << dir;
m_IncludeSearchDirs.push_back(dir);
}
}
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;
{
public:
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);
std::unique_ptr<Expression> Compile(void);
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(),
- const String& package = String());
+ const String& package = String());
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);
String GetPackage(void) const;
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,
- 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,
- 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,
- 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);
void *GetScanner(void) const;
}
ConfigCompilerContext::ConfigCompilerContext(void)
- : m_ObjectsFP(nullptr)
+ : m_ObjectsFP(nullptr)
{ }
void ConfigCompilerContext::OpenObjectsFile(const String& filename)
if (rename(m_ObjectsTempFile.CStr(), m_ObjectsPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(m_ObjectsTempFile));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(m_ObjectsTempFile));
}
}
* @param debuginfo Debug information.
*/
ConfigItem::ConfigItem(const Type::Ptr& type, const String& name,
- bool abstract, const std::shared_ptr<Expression>& exprl,
- const std::shared_ptr<Expression>& filter, bool defaultTmpl, bool ignoreOnError,
- const DebugInfo& debuginfo, const Dictionary::Ptr& scope,
- const String& zone, const String& package)
+ bool abstract, const std::shared_ptr<Expression>& exprl,
+ const std::shared_ptr<Expression>& filter, bool defaultTmpl, bool ignoreOnError,
+ const DebugInfo& debuginfo, const Dictionary::Ptr& scope,
+ const String& zone, const String& package)
: m_Type(type), m_Name(name), m_Abstract(abstract),
- m_Expression(exprl), m_Filter(filter),
- m_DefaultTmpl(defaultTmpl), m_IgnoreOnError(ignoreOnError),
- m_DebugInfo(debuginfo), m_Scope(scope), m_Zone(zone),
- m_Package(package)
+ m_Expression(exprl), m_Filter(filter),
+ m_DefaultTmpl(defaultTmpl), m_IgnoreOnError(ignoreOnError),
+ m_DebugInfo(debuginfo), m_Scope(scope), m_Zone(zone),
+ m_Package(package)
{
}
{
#ifdef I2_DEBUG
Log(LogDebug, "ConfigItem")
- << "Commit called for ConfigItem Type=" << GetType() << ", Name=" << GetName();
+ << "Commit called for ConfigItem Type=" << GetType() << ", Name=" << GetName();
#endif /* I2_DEBUG */
/* Make sure the type is valid. */
} catch (const std::exception& ex) {
if (m_IgnoreOnError) {
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);
} catch (ValidationError& ex) {
if (m_IgnoreOnError) {
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);
} catch (const std::exception& ex) {
if (m_IgnoreOnError) {
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);
if (it != items.end()) {
std::ostringstream msgbuf;
msgbuf << "A configuration item of type '" << m_Type->GetName()
- << "' and name '" << GetName() << "' already exists ("
- << it->second->GetDebugInfo() << "), new declaration: " << GetDebugInfo();
+ << "' and name '" << GetName() << "' already exists ("
+ << it->second->GetDebugInfo() << "), new declaration: " << GetDebugInfo();
BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str()));
}
} catch (const std::exception& ex) {
if (item->m_IgnoreOnError) {
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();
for (const ItemCountMap::value_type& kv : itemCounts) {
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()) << ".";
}
}
#ifdef I2_DEBUG
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 */
upq.Enqueue(std::bind(&ConfigObject::PreActivate, object));
}
#ifdef I2_DEBUG
Log(LogDebug, "ConfigItem")
- << "Activating object '" << object->GetName() << "' of type '" << object->GetReflectionType()->GetName() << "'";
+ << "Activating object '" << object->GetName() << "' of type '" << object->GetReflectionType()->GetName() << "'";
#endif /* I2_DEBUG */
upq.Enqueue(std::bind(&ConfigObject::Activate, object, runtimeCreated));
}
continue;
Log(LogNotice, "ConfigItem")
- << "Removing ignored item path '" << path << "'.";
+ << "Removing ignored item path '" << path << "'.";
(void) unlink(path.CStr());
}
DECLARE_PTR_TYPEDEFS(ConfigItem);
ConfigItem(const Type::Ptr& type, const String& name, bool abstract,
- const std::shared_ptr<Expression>& exprl,
- const std::shared_ptr<Expression>& filter,
- bool defaultTmpl, bool ignoreOnError, const DebugInfo& debuginfo,
- const Dictionary::Ptr& scope, const String& zone,
- const String& package);
+ const std::shared_ptr<Expression>& exprl,
+ const std::shared_ptr<Expression>& filter,
+ bool defaultTmpl, bool ignoreOnError, const DebugInfo& debuginfo,
+ const Dictionary::Ptr& scope, const String& zone,
+ const String& package);
Type::Ptr GetType(void) const;
String GetName(void) const;
ConfigObject::Ptr GetObject(void) const;
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 ActivateItems(WorkQueue& upq, const std::vector<ConfigItem::Ptr>& newItems, bool runtimeCreated = false, bool silent = false, bool withModAttrs = false);
static IgnoredItemList m_IgnoredItems;
static ConfigItem::Ptr GetObjectUnlocked(const String& type,
- const String& name);
+ const String& name);
ConfigObject::Ptr Commit(bool discard = true);
templateArray->Add(m_Name);
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
if (!m_Abstract) {
exprl->MakeInline();
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);
}
frame.DecreaseStackDepth();
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();
CHECK_RESULT(nameres);
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
}
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
{ }
DebugHint(Dictionary::Ptr&& hints)
- : m_Hints(std::move(hints))
+ : m_Hints(std::move(hints))
{ }
void AddMessage(const String& message, const DebugInfo& di)
public:
template<typename T>
ExpressionResult(const T& value, ExpressionResultCode code = ResultOK)
- : m_Value(value), m_Code(code)
+ : m_Value(value), m_Code(code)
{ }
operator const Value&(void) const
{
public:
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))
{ }
{
public:
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> fterm, std::map<String, std::unique_ptr<Expression> >&& closedVars, bool ignoreOnError,
- std::unique_ptr<Expression> expression, const DebugInfo& debugInfo = DebugInfo())
+ 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> expression, const DebugInfo& debugInfo = DebugInfo())
: 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_FTerm(std::move(fterm)), m_IgnoreOnError(ignoreOnError), m_ClosedVars(std::move(closedVars)),
- m_Expression(std::move(expression))
+ 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_Expression(std::move(expression))
{ }
protected:
{
public:
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,
- bool defaultTmpl, bool ignoreOnError, std::unique_ptr<Expression> expression, const DebugInfo& debugInfo = DebugInfo())
+ 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())
: 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_IgnoreOnError(ignoreOnError), m_ClosedVars(std::move(closedVars)), m_Expression(std::move(expression))
+ 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))
{ }
protected:
{
public:
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)),
- 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:
{
public:
BreakpointExpression(const DebugInfo& debugInfo = DebugInfo())
- : DebuggableExpression(debugInfo)
+ : DebuggableExpression(debugInfo)
{ }
protected:
}
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);
bool ignoreOnError, const std::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
{
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;
}
if (!GetEnableHa()) {
Log(LogDebug, "DbConnection")
- << "HA functionality disabled. Won't pause IDO connection: " << GetName();
+ << "HA functionality disabled. Won't pause IDO connection: " << GetName();
SetHAMode(HARunEverywhere);
}
ObjectImpl<DbConnection>::Start(runtimeCreated);
Log(LogInformation, "DbConnection")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
DbObject::OnQuery.connect(std::bind(&DbConnection::ExecuteQuery, this, _1));
DbObject::OnMultipleQueries.connect(std::bind(&DbConnection::ExecuteMultipleQueries, this, _1));
void DbConnection::Stop(bool runtimeRemoved)
{
Log(LogInformation, "DbConnection")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
ObjectImpl<DbConnection>::Stop(runtimeRemoved);
}
ConfigObject::Resume();
Log(LogInformation, "DbConnection")
- << "Resuming IDO connection: " << GetName();
+ << "Resuming IDO connection: " << GetName();
m_CleanUpTimer = new Timer();
m_CleanUpTimer->SetInterval(60);
ConfigObject::Pause();
Log(LogInformation, "DbConnection")
- << "Pausing IDO connection: " << GetName();
+ << "Pausing IDO connection: " << GetName();
m_CleanUpTimer.reset();
void DbConnection::UpdateProgramStatus(void)
{
Log(LogNotice, "DbConnection")
- << "Updating programstatus table.";
+ << "Updating programstatus table.";
std::vector<DbQuery> queries;
CleanUpExecuteQuery(tables[i].name, tables[i].time_column, now - max_age);
Log(LogNotice, "DbConnection")
- << "Cleanup (" << tables[i].name << "): " << max_age
- << " now: " << now
- << " old: " << now - max_age;
+ << "Cleanup (" << tables[i].name << "): " << max_age
+ << " now: " << now
+ << " old: " << now - max_age;
}
}
int filter = FilterArrayToInt(value, DbQuery::GetCategoryFilterMap(), 0);
if (filter != DbCatEverything && (filter & ~(DbCatInvalid | DbCatEverything | DbCatConfig | DbCatState |
- DbCatAcknowledgement | DbCatComment | DbCatDowntime | DbCatEventHandler | DbCatExternalCommand |
- DbCatFlapping | DbCatLog | DbCatNotification | DbCatProgramStatus | DbCatRetention |
- DbCatStateHistory)) != 0)
+ DbCatAcknowledgement | DbCatComment | DbCatDowntime | DbCatEventHandler | DbCatExternalCommand |
+ DbCatFlapping | DbCatLog | DbCatNotification | DbCatProgramStatus | DbCatRetention |
+ DbCatStateHistory)) != 0)
BOOST_THROW_EXCEPTION(ValidationError(this, { "categories" }, "categories filter is invalid."));
}
is_reachable = 1;
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) {
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;
Service::Ptr service;
/* acknowledgements */
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")
- << "add acknowledgement history for '" << checkable->GetName() << "'";
+ << "add acknowledgement history for '" << checkable->GetName() << "'";
double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
void DbEvents::AddAcknowledgement(const Checkable::Ptr& checkable, AcknowledgementType type)
{
Log(LogDebug, "DbEvents")
- << "add acknowledgement for '" << checkable->GetName() << "'";
+ << "add acknowledgement for '" << checkable->GetName() << "'";
AddAcknowledgementInternal(checkable, type, true);
}
void DbEvents::RemoveAcknowledgement(const Checkable::Ptr& checkable)
{
Log(LogDebug, "DbEvents")
- << "remove acknowledgement for '" << checkable->GetName() << "'";
+ << "remove acknowledgement for '" << checkable->GetName() << "'";
AddAcknowledgementInternal(checkable, AcknowledgementNone, false);
}
/* notifications */
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")
- << "add notification history for '" << checkable->GetName() << "'";
+ << "add notification history for '" << checkable->GetName() << "'";
/* start and end happen at the same time */
double now = Utility::GetTime();
for (const User::Ptr& user : users) {
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;
query2.Table = "contactnotifications";
void DbEvents::AddStateChangeHistory(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, StateType type)
{
Log(LogDebug, "DbEvents")
- << "add state change history for '" << checkable->GetName() << "'";
+ << "add state change history for '" << checkable->GetName() << "'";
double ts = cr->GetExecutionEnd();
std::pair<unsigned long, unsigned long> state_time_bag = CompatUtility::ConvertTimestamp(ts);
bool reachable_before = vars_before->Get("reachable");
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. */
}
if (service) {
msgbuf << "SERVICE ALERT: "
- << host->GetName() << ";"
- << service->GetShortName() << ";"
- << Service::StateToString(service->GetState()) << ";"
- << Service::StateTypeToString(service->GetStateType()) << ";"
- << attempt_after << ";"
- << output << ""
- << "";
+ << host->GetName() << ";"
+ << service->GetShortName() << ";"
+ << Service::StateToString(service->GetState()) << ";"
+ << Service::StateTypeToString(service->GetStateType()) << ";"
+ << attempt_after << ";"
+ << output << ""
+ << "";
switch (service->GetState()) {
case ServiceOK:
break;
default:
Log(LogCritical, "DbEvents")
- << "Unknown service state: " << state_after;
+ << "Unknown service state: " << state_after;
return;
}
} else {
msgbuf << "HOST ALERT: "
- << host->GetName() << ";"
- << CompatUtility::GetHostStateString(host) << ";"
- << Host::StateTypeToString(host->GetStateType()) << ";"
- << attempt_after << ";"
- << output << ""
- << "";
+ << host->GetName() << ";"
+ << CompatUtility::GetHostStateString(host) << ";"
+ << Host::StateTypeToString(host->GetStateType()) << ";"
+ << attempt_after << ";"
+ << output << ""
+ << "";
switch (host->GetState()) {
case HostUp:
break;
default:
Log(LogCritical, "DbEvents")
- << "Unknown host state: " << state_after;
+ << "Unknown host state: " << state_after;
return;
}
}
void DbEvents::AddNotificationSentLogHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const User::Ptr& user,
- NotificationType notification_type, const CheckResult::Ptr& cr,
- const String& author, const String& comment_text)
+ NotificationType notification_type, const CheckResult::Ptr& cr,
+ const String& author, const String& comment_text)
{
CheckCommand::Ptr commandObj = checkable->GetCheckCommand();
if (service) {
msgbuf << "SERVICE NOTIFICATION: "
- << user->GetName() << ";"
- << host->GetName() << ";"
- << service->GetShortName() << ";"
- << notification_type_str << " "
- << "(" << Service::StateToString(service->GetState()) << ");"
- << check_command << ";"
- << output << author_comment
- << "";
+ << user->GetName() << ";"
+ << host->GetName() << ";"
+ << service->GetShortName() << ";"
+ << notification_type_str << " "
+ << "(" << Service::StateToString(service->GetState()) << ");"
+ << check_command << ";"
+ << output << author_comment
+ << "";
} else {
msgbuf << "HOST NOTIFICATION: "
- << user->GetName() << ";"
- << host->GetName() << ";"
- << notification_type_str << " "
- << "(" << Host::StateToString(host->GetState()) << ");"
- << check_command << ";"
- << output << author_comment
- << "";
+ << user->GetName() << ";"
+ << host->GetName() << ";"
+ << notification_type_str << " "
+ << "(" << Host::StateToString(host->GetState()) << ");"
+ << check_command << ";"
+ << output << author_comment
+ << "";
}
AddLogHistory(checkable, msgbuf.str(), LogEntryTypeHostNotification);
if (service) {
msgbuf << "SERVICE FLAPPING ALERT: "
- << host->GetName() << ";"
- << service->GetShortName() << ";"
- << flapping_state_str << "; "
- << flapping_output
- << "";
+ << host->GetName() << ";"
+ << service->GetShortName() << ";"
+ << flapping_state_str << "; "
+ << flapping_output
+ << "";
} else {
msgbuf << "HOST FLAPPING ALERT: "
- << host->GetName() << ";"
- << flapping_state_str << "; "
- << flapping_output
- << "";
+ << host->GetName() << ";"
+ << flapping_state_str << "; "
+ << flapping_output
+ << "";
}
AddLogHistory(checkable, msgbuf.str(), LogEntryTypeInfoMessage);
if (service) {
msgbuf << "SERVICE FLAPPING ALERT: "
- << host->GetName() << ";"
- << service->GetShortName() << ";"
- << flapping_state_str << "; "
- << flapping_output
- << "";
+ << host->GetName() << ";"
+ << service->GetShortName() << ";"
+ << flapping_state_str << "; "
+ << flapping_output
+ << "";
} else {
msgbuf << "HOST FLAPPING ALERT: "
- << host->GetName() << ";"
- << flapping_state_str << "; "
- << flapping_output
- << "";
+ << host->GetName() << ";"
+ << flapping_state_str << "; "
+ << flapping_output
+ << "";
}
AddLogHistory(checkable, msgbuf.str(), LogEntryTypeInfoMessage);
void DbEvents::AddLogHistory(const Checkable::Ptr& checkable, String buffer, LogEntryType type)
{
Log(LogDebug, "DbEvents")
- << "add log entry history for '" << checkable->GetName() << "'";
+ << "add log entry history for '" << checkable->GetName() << "'";
double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
void DbEvents::AddFlappingChangedHistory(const Checkable::Ptr& checkable)
{
Log(LogDebug, "DbEvents")
- << "add flapping history for '" << checkable->GetName() << "'";
+ << "add flapping history for '" << checkable->GetName() << "'";
double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
void DbEvents::AddEnableFlappingChangedHistory(const Checkable::Ptr& checkable)
{
Log(LogDebug, "DbEvents")
- << "add flapping history for '" << checkable->GetName() << "'";
+ << "add flapping history for '" << checkable->GetName() << "'";
double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
return;
Log(LogDebug, "DbEvents")
- << "add checkable check history for '" << checkable->GetName() << "'";
+ << "add checkable check history for '" << checkable->GetName() << "'";
Host::Ptr host;
Service::Ptr service;
void DbEvents::AddEventHandlerHistory(const Checkable::Ptr& checkable)
{
Log(LogDebug, "DbEvents")
- << "add eventhandler history for '" << checkable->GetName() << "'";
+ << "add eventhandler history for '" << checkable->GetName() << "'";
double now = Utility::GetTime();
std::pair<unsigned long, unsigned long> time_bag = CompatUtility::ConvertTimestamp(now);
enum LogEntryType
{
- LogEntryTypeRuntimeError = 1,
- LogEntryTypeRuntimeWarning = 2,
- LogEntryTypeVerificationError = 4,
- LogEntryTypeVerificationWarning = 8,
- LogEntryTypeConfigError = 16,
- LogEntryTypeConfigWarning = 32,
- LogEntryTypeProcessInfo = 64,
- LogEntryTypeEventHandler = 128,
- LogEntryTypeExternalCommand = 512,
- LogEntryTypeHostUp = 1024,
- LogEntryTypeHostDown = 2048,
- LogEntryTypeHostUnreachable = 4096,
- LogEntryTypeServiceOk = 8192,
- LogEntryTypeServiceUnknown = 16384,
- LogEntryTypeServiceWarning = 32768,
- LogEntryTypeServiceCritical = 65536,
- LogEntryTypePassiveCheck = 1231072,
- LogEntryTypeInfoMessage = 262144,
- LogEntryTypeHostNotification = 524288,
- LogEntryTypeServiceNotification = 1048576
+ LogEntryTypeRuntimeError = 1,
+ LogEntryTypeRuntimeWarning = 2,
+ LogEntryTypeVerificationError = 4,
+ LogEntryTypeVerificationWarning = 8,
+ LogEntryTypeConfigError = 16,
+ LogEntryTypeConfigWarning = 32,
+ LogEntryTypeProcessInfo = 64,
+ LogEntryTypeEventHandler = 128,
+ LogEntryTypeExternalCommand = 512,
+ LogEntryTypeHostUp = 1024,
+ LogEntryTypeHostDown = 2048,
+ LogEntryTypeHostUnreachable = 4096,
+ LogEntryTypeServiceOk = 8192,
+ LogEntryTypeServiceUnknown = 16384,
+ LogEntryTypeServiceWarning = 32768,
+ LogEntryTypeServiceCritical = 65536,
+ LogEntryTypePassiveCheck = 1231072,
+ LogEntryTypeInfoMessage = 262144,
+ LogEntryTypeHostNotification = 524288,
+ LogEntryTypeServiceNotification = 1048576
};
/**
static void AddCommentHistory(const Comment::Ptr& comment);
static void AddDowntimeHistory(const Downtime::Ptr& downtime);
static void AddAcknowledgementHistory(const Checkable::Ptr& checkable, const String& author, const String& comment,
- AcknowledgementType type, bool notify, double expiry);
+ AcknowledgementType type, bool notify, double expiry);
/* notification & contactnotification history */
static void 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 std::set<User::Ptr>& users, NotificationType type, const CheckResult::Ptr& cr, const String& author,
+ const String& text);
/* statehistory */
static void AddStateChangeHistory(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, StateType type);
static void AddTriggerDowntimeLogHistory(const Downtime::Ptr& downtime);
static void AddRemoveDowntimeLogHistory(const Downtime::Ptr& downtime);
static void AddNotificationSentLogHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
- const User::Ptr& user, NotificationType notification_type, const CheckResult::Ptr& cr, const String& author,
- const String& comment_text);
+ const User::Ptr& user, NotificationType notification_type, const CheckResult::Ptr& cr, const String& author,
+ const String& comment_text);
static void AddFlappingChangedLogHistory(const Checkable::Ptr& checkable);
static void AddEnableFlappingChangedLogHistory(const Checkable::Ptr& checkable);
name2 = service->GetShortName();
} else {
if (object->GetReflectionType() == CheckCommand::TypeInstance ||
- object->GetReflectionType() == EventCommand::TypeInstance ||
- object->GetReflectionType() == NotificationCommand::TypeInstance) {
+ object->GetReflectionType() == EventCommand::TypeInstance ||
+ object->GetReflectionType() == NotificationCommand::TypeInstance) {
Command::Ptr command = dynamic_pointer_cast<Command>(object);
name1 = CompatUtility::GetCommandName(command);
}
Endpoint::Ptr endpoint = static_pointer_cast<Endpoint>(GetObject());
Log(LogDebug, "EndpointDbObject")
- << "update status for endpoint '" << endpoint->GetName() << "'";
+ << "update status for endpoint '" << endpoint->GetName() << "'";
fields->Set("identity", endpoint->GetName());
fields->Set("node", IcingaApplication::GetInstance()->GetNodeName());
bool connected = EndpointIsConnected(endpoint);
Log(LogDebug, "EndpointDbObject")
- << "update is_connected=" << connected << " for endpoint '" << endpoint->GetName() << "'";
+ << "update is_connected=" << connected << " for endpoint '" << endpoint->GetName() << "'";
DbQuery query1;
query1.Table = "endpointstatus";
continue;
Log(LogDebug, "HostDbObject")
- << "host parents: " << parent->GetName();
+ << "host parents: " << parent->GetName();
/* parents: host_id, parent_host_object_id */
Dictionary::Ptr fields1 = new Dictionary();
/* host dependencies */
Log(LogDebug, "HostDbObject")
- << "host dependencies for '" << host->GetName() << "'";
+ << "host dependencies for '" << host->GetName() << "'";
queries.clear();
if (!parent) {
Log(LogDebug, "HostDbObject")
- << "Missing parent for dependency '" << dep->GetName() << "'.";
+ << "Missing parent for dependency '" << dep->GetName() << "'.";
continue;
}
int state_filter = dep->GetStateFilter();
Log(LogDebug, "HostDbObject")
- << "parent host: " << parent->GetName();
+ << "parent host: " << parent->GetName();
Dictionary::Ptr fields2 = new Dictionary();
fields2->Set("host_object_id", parent);
DbObject::OnMultipleQueries(queries);
Log(LogDebug, "HostDbObject")
- << "host contacts: " << host->GetName();
+ << "host contacts: " << host->GetName();
queries.clear();
for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(host)) {
Log(LogDebug, "HostDbObject")
- << "host contacts: " << user->GetName();
+ << "host contacts: " << user->GetName();
Dictionary::Ptr fields_contact = new Dictionary();
fields_contact->Set("host_id", DbValue::FromObjectInsertID(host));
DbObject::OnMultipleQueries(queries);
Log(LogDebug, "HostDbObject")
- << "host contactgroups: " << host->GetName();
+ << "host contactgroups: " << host->GetName();
queries.clear();
for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(host)) {
Log(LogDebug, "HostDbObject")
- << "host contactgroups: " << usergroup->GetName();
+ << "host contactgroups: " << usergroup->GetName();
Dictionary::Ptr fields_contact = new Dictionary();
fields_contact->Set("host_id", DbValue::FromObjectInsertID(host));
REGISTER_SCRIPTFUNCTION_NS(Internal, IdoCheck, &IdoCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void IdoCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
CheckCommand::Ptr commandObj = checkable->GetCheckCommand();
Value raw_command = commandObj->GetCommandLine();
resolvers.emplace_back("icinga", IcingaApplication::GetInstance());
String idoType = MacroProcessor::ResolveMacros("$ido_type$", resolvers, checkable->GetLastCheckResult(),
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
String idoName = MacroProcessor::ResolveMacros("$ido_name$", resolvers, checkable->GetLastCheckResult(),
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
if (resolvedMacros && !useResolvedMacros)
return;
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
IdoCheckTask(void);
/* service dependencies */
Log(LogDebug, "ServiceDbObject")
- << "service dependencies for '" << service->GetName() << "'";
+ << "service dependencies for '" << service->GetName() << "'";
queries.clear();
if (!parent) {
Log(LogDebug, "ServiceDbObject")
- << "Missing parent for dependency '" << dep->GetName() << "'.";
+ << "Missing parent for dependency '" << dep->GetName() << "'.";
continue;
}
Log(LogDebug, "ServiceDbObject")
- << "service parents: " << parent->GetName();
+ << "service parents: " << parent->GetName();
int state_filter = dep->GetStateFilter();
/* service contacts, contactgroups */
Log(LogDebug, "ServiceDbObject")
- << "service contacts: " << service->GetName();
+ << "service contacts: " << service->GetName();
queries.clear();
for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) {
Log(LogDebug, "ServiceDbObject")
- << "service contacts: " << user->GetName();
+ << "service contacts: " << user->GetName();
Dictionary::Ptr fields_contact = new Dictionary();
fields_contact->Set("service_id", DbValue::FromObjectInsertID(service));
DbObject::OnMultipleQueries(queries);
Log(LogDebug, "ServiceDbObject")
- << "service contactgroups: " << service->GetName();
+ << "service contactgroups: " << service->GetName();
queries.clear();
for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) {
Log(LogDebug, "ServiceDbObject")
- << "service contactgroups: " << usergroup->GetName();
+ << "service contactgroups: " << usergroup->GetName();
Dictionary::Ptr fields_contact = new Dictionary();
fields_contact->Set("service_id", DbValue::FromObjectInsertID(service));
Zone::Ptr zone = static_pointer_cast<Zone>(GetObject());
Log(LogDebug, "ZoneDbObject")
- << "update status for zone '" << zone->GetName() << "'";
+ << "update status for zone '" << zone->GetName() << "'";
Dictionary::Ptr fields = new Dictionary();
fields->Set("parent_zone_object_id", zone->GetParent());
DbConnection::Resume();
Log(LogInformation, "IdoMysqlConnection")
- << "'" << GetName() << "' resumed.";
+ << "'" << GetName() << "' resumed.";
SetConnected(false);
void IdoMysqlConnection::Pause(void)
{
Log(LogInformation, "IdoMysqlConnection")
- << "'" << GetName() << "' paused.";
+ << "'" << GetName() << "' paused.";
m_ReconnectTimer.reset();
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Rescheduling disconnect task.";
+ << "Rescheduling disconnect task.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::Disconnect, this), PriorityHigh);
Log(LogCritical, "IdoMysqlConnection", "Exception during database operation: Verify that your database is operational!");
Log(LogDebug, "IdoMysqlConnection")
- << "Exception during database operation: " << DiagnosticInformation(exp);
+ << "Exception during database operation: " << DiagnosticInformation(exp);
if (GetConnected()) {
mysql_close(&m_Connection);
{
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling new transaction and finishing async queries.";
+ << "Scheduling new transaction and finishing async queries.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalNewTransaction, this), PriorityHigh);
{
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling reconnect task.";
+ << "Scheduling reconnect task.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::Reconnect, this), PriorityLow);
/* connection */
if (!mysql_init(&m_Connection)) {
Log(LogCritical, "IdoMysqlConnection")
- << "mysql_init() failed: out of memory";
+ << "mysql_init() failed: out of memory";
BOOST_THROW_EXCEPTION(std::bad_alloc());
}
if (!mysql_real_connect(&m_Connection, host, user, passwd, db, port, socket_path, CLIENT_FOUND_ROWS | CLIENT_MULTI_STATEMENTS)) {
Log(LogCritical, "IdoMysqlConnection")
- << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port
- << "' " << (enableSsl ? "(SSL enabled) " : "") << "failed: \"" << mysql_error(&m_Connection) << "\"";
+ << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port
+ << "' " << (enableSsl ? "(SSL enabled) " : "") << "failed: \"" << mysql_error(&m_Connection) << "\"";
BOOST_THROW_EXCEPTION(std::runtime_error(mysql_error(&m_Connection)));
}
SetConnected(false);
Log(LogCritical, "IdoMysqlConnection")
- << "Schema version '" << version << "' does not match the required version '"
- << IDO_COMPAT_SCHEMA_VERSION << "' (or newer)! Please check the upgrade documentation at "
- << "https://docs.icinga.com/icinga2/latest/doc/module/icinga2/chapter/upgrading-icinga-2#upgrading-mysql-db";
+ << "Schema version '" << version << "' does not match the required version '"
+ << IDO_COMPAT_SCHEMA_VERSION << "' (or newer)! Please check the upgrade documentation at "
+ << "https://docs.icinga.com/icinga2/latest/doc/module/icinga2/chapter/upgrading-icinga-2#upgrading-mysql-db";
BOOST_THROW_EXCEPTION(std::runtime_error("Schema version mismatch."));
}
if (my_endpoint && GetHAMode() == HARunOnce) {
/* get the current endpoint writing to programstatus table */
result = Query("SELECT UNIX_TIMESTAMP(status_update_time) AS status_update_time, endpoint_name FROM " +
- GetTablePrefix() + "programstatus WHERE instance_id = " + Convert::ToString(m_InstanceID));
+ GetTablePrefix() + "programstatus WHERE instance_id = " + Convert::ToString(m_InstanceID));
row = FetchRow(result);
DiscardRows(result);
double status_update_age = Utility::GetTime() - status_update_time;
Log(LogNotice, "IdoMysqlConnection")
- << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago.";
+ << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago.";
if (status_update_age < GetFailoverTimeout()) {
mysql_close(&m_Connection);
/* activate the IDO only, if we're authoritative in this zone */
if (IsPaused()) {
Log(LogNotice, "IdoMysqlConnection")
- << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out.";
+ << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out.";
mysql_close(&m_Connection);
SetConnected(false);
}
Log(LogInformation, "IdoMysqlConnection")
- << "MySQL IDO instance id: " << static_cast<long>(m_InstanceID) << " (schema version: '" + version + "')";
+ << "MySQL IDO instance id: " << static_cast<long>(m_InstanceID) << " (schema version: '" + version + "')";
/* set session time zone to utc */
Query("SET SESSION TIME_ZONE='+00:00'");
/* record connection */
Query("INSERT INTO " + GetTablePrefix() + "conninfo " +
- "(instance_id, connect_time, last_checkin_time, agent_name, agent_version, connect_type, data_start_time) VALUES ("
- + Convert::ToString(static_cast<long>(m_InstanceID)) + ", NOW(), NOW(), 'icinga2 db_ido_mysql', '" + Escape(Application::GetAppVersion())
- + "', '" + (reconnect ? "RECONNECT" : "INITIAL") + "', NOW())");
+ "(instance_id, connect_time, last_checkin_time, agent_name, agent_version, connect_type, data_start_time) VALUES ("
+ + Convert::ToString(static_cast<long>(m_InstanceID)) + ", NOW(), NOW(), 'icinga2 db_ido_mysql', '" + Escape(Application::GetAppVersion())
+ + "', '" + (reconnect ? "RECONNECT" : "INITIAL") + "', NOW())");
/* clear config tables for the initial config dump */
PrepareDatabase();
continue;
Log(LogNotice, "IdoMysqlConnection")
- << "Deactivate deleted object name1: '" << dbobj->GetName1()
- << "' name2: '" << dbobj->GetName2() + "'.";
+ << "Deactivate deleted object name1: '" << dbobj->GetName1()
+ << "' name2: '" << dbobj->GetName2() + "'.";
DeactivateObject(dbobj);
}
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling session table clear and finish connect task.";
+ << "Scheduling session table clear and finish connect task.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::ClearTablesBySession, this), PriorityLow);
FinishAsyncQueries();
Log(LogInformation, "IdoMysqlConnection")
- << "Finished reconnecting to MySQL IDO database in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
+ << "Finished reconnecting to MySQL IDO database in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
Query("COMMIT");
Query("BEGIN");
void IdoMysqlConnection::ClearTableBySession(const String& table)
{
Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
- Convert::ToString(static_cast<long>(m_InstanceID)) + " AND session_token <> " +
- Convert::ToString(GetSessionToken()));
+ Convert::ToString(static_cast<long>(m_InstanceID)) + " AND session_token <> " +
+ Convert::ToString(GetSessionToken()));
}
void IdoMysqlConnection::AsyncQuery(const String& query, const std::function<void (const IdoMysqlResult&)>& callback)
count++;
Log(LogDebug, "IdoMysqlConnection")
- << "Query: " << aq.Query;
+ << "Query: " << aq.Query;
querybuf << aq.Query;
num_bytes += size_query;
Log(LogCritical, "IdoMysqlConnection", msgbuf.str());
BOOST_THROW_EXCEPTION(
- database_error()
+ database_error()
<< errinfo_message(mysql_error(&m_Connection))
<< errinfo_database_query(query)
);
Log(LogCritical, "IdoMysqlConnection", msgbuf.str());
BOOST_THROW_EXCEPTION(
- database_error()
+ database_error()
<< errinfo_message(mysql_error(&m_Connection))
<< errinfo_database_query(query)
);
Log(LogCritical, "IdoMysqlConnection", msgbuf.str());
BOOST_THROW_EXCEPTION(
- database_error()
+ database_error()
<< errinfo_message(mysql_error(&m_Connection))
<< errinfo_database_query(query)
);
FinishAsyncQueries();
Log(LogDebug, "IdoMysqlConnection")
- << "Query: " << query;
+ << "Query: " << query;
IncreaseQueryCount();
Log(LogCritical, "IdoMysqlConnection", msgbuf.str());
BOOST_THROW_EXCEPTION(
- database_error()
+ database_error()
<< errinfo_message(mysql_error(&m_Connection))
<< errinfo_database_query(query)
);
Log(LogCritical, "IdoMysqlConnection", msgbuf.str());
BOOST_THROW_EXCEPTION(
- database_error()
+ database_error()
<< errinfo_message(mysql_error(&m_Connection))
<< errinfo_database_query(query)
);
{
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling object activation task for '" << dbobj->GetName1() << "!" << dbobj->GetName2() << "'.";
+ << "Scheduling object activation task for '" << dbobj->GetName1() << "!" << dbobj->GetName2() << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalActivateObject, this, dbobj), PriorityLow);
if (!dbref.IsValid()) {
if (!dbobj->GetName2().IsEmpty()) {
qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, name2, is_active) VALUES ("
- << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
- << "'" << Escape(dbobj->GetName1()) << "', '" << Escape(dbobj->GetName2()) << "', 1)";
+ << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
+ << "'" << Escape(dbobj->GetName1()) << "', '" << Escape(dbobj->GetName2()) << "', 1)";
} else {
qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, is_active) VALUES ("
- << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
- << "'" << Escape(dbobj->GetName1()) << "', 1)";
+ << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
+ << "'" << Escape(dbobj->GetName1()) << "', 1)";
}
Query(qbuf.str());
{
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling object deactivation task for '" << dbobj->GetName1() << "!" << dbobj->GetName2() << "'.";
+ << "Scheduling object deactivation task for '" << dbobj->GetName1() << "!" << dbobj->GetName2() << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalDeactivateObject, this, dbobj), PriorityLow);
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling execute query task, type " << query.Type << ", table '" << query.Table << "'.";
+ << "Scheduling execute query task, type " << query.Type << ", table '" << query.Table << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalExecuteQuery, this, query, -1), query.Priority, true);
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling multiple execute query task, type " << queries[0].Type << ", table '" << queries[0].Table << "'.";
+ << "Scheduling multiple execute query task, type " << queries[0].Type << ", table '" << queries[0].Table << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalExecuteMultipleQueries, this, queries), queries[0].Priority, true);
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling multiple execute query task again: Cannot execute query now. Type '"
- << query.Type << "', table '" << query.Table << "', queue size: '" << GetPendingQueryCount() << "'.";
+ << "Scheduling multiple execute query task again: Cannot execute query now. Type '"
+ << query.Type << "', table '" << query.Table << "', queue size: '" << GetPendingQueryCount() << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalExecuteMultipleQueries, this, queries), query.Priority);
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling execute query task again: Cannot execute query now. Type '"
- << typeOverride << "', table '" << query.Table << "', queue size: '" << GetPendingQueryCount() << "'.";
+ << "Scheduling execute query task again: Cannot execute query now. Type '"
+ << typeOverride << "', table '" << query.Table << "', queue size: '" << GetPendingQueryCount() << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalExecuteQuery, this, query, typeOverride), query.Priority);
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling execute query task again: Cannot execute query now. Type '"
- << typeOverride << "', table '" << query.Table << "', queue size: '" << GetPendingQueryCount() << "'.";
+ << "Scheduling execute query task again: Cannot execute query now. Type '"
+ << typeOverride << "', table '" << query.Table << "', queue size: '" << GetPendingQueryCount() << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Scheduling execute query task again: Cannot extract required INSERT/UPDATE fields, key '"
- << kv.first << "', val '" << kv.second << "', type " << typeOverride << ", table '" << query.Table << "'.";
+ << "Scheduling execute query task again: Cannot extract required INSERT/UPDATE fields, key '"
+ << kv.first << "', val '" << kv.second << "', type " << typeOverride << ", table '" << query.Table << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Rescheduling DELETE/INSERT query: Upsert UPDATE did not affect rows, type " << type << ", table '" << query.Table << "'.";
+ << "Rescheduling DELETE/INSERT query: Upsert UPDATE did not affect rows, type " << type << ", table '" << query.Table << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalExecuteQuery, this, query, DbQueryDelete | DbQueryInsert), query.Priority);
{
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "IdoMysqlConnection")
- << "Rescheduling cleanup query for table '" << table << "' and column '"
- << time_column << "'. max_age is set to '" << max_age << "'.";
+ << "Rescheduling cleanup query for table '" << table << "' and column '"
+ << time_column << "'. max_age is set to '" << max_age << "'.";
#endif /* I2_DEBUG */
m_QueryQueue.Enqueue(std::bind(&IdoMysqlConnection::InternalCleanUpExecuteQuery, this, table, time_column, max_age), PriorityLow, true);
return;
AsyncQuery("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
- Convert::ToString(static_cast<long>(m_InstanceID)) + " AND " + time_column +
- " < FROM_UNIXTIME(" + Convert::ToString(static_cast<long>(max_age)) + ")");
+ Convert::ToString(static_cast<long>(m_InstanceID)) + " AND " + time_column +
+ " < FROM_UNIXTIME(" + Convert::ToString(static_cast<long>(max_age)) + ")");
}
void IdoMysqlConnection::FillIDCache(const DbType::Ptr& type)
DbConnection::Resume();
Log(LogInformation, "IdoPgsqlConnection")
- << "'" << GetName() << "' resumed.";
+ << "'" << GetName() << "' resumed.";
SetConnected(false);
void IdoPgsqlConnection::Pause(void)
{
Log(LogInformation, "IdoPgsqlConnection")
- << "'" << GetName() << "' paused.";
+ << "'" << GetName() << "' paused.";
m_ReconnectTimer.reset();
Log(LogWarning, "IdoPgsqlConnection", "Exception during database operation: Verify that your database is operational!");
Log(LogDebug, "IdoPgsqlConnection")
- << "Exception during database operation: " << DiagnosticInformation(exp);
+ << "Exception during database operation: " << DiagnosticInformation(exp);
if (GetConnected()) {
PQfinish(m_Connection);
SetConnected(false);
Log(LogCritical, "IdoPgsqlConnection")
- << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port
- << "' failed: \"" << message << "\"";
+ << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port
+ << "' failed: \"" << message << "\"";
BOOST_THROW_EXCEPTION(std::runtime_error(message));
}
SetConnected(false);
Log(LogCritical, "IdoPgsqlConnection")
- << "Schema version '" << version << "' does not match the required version '"
- << IDO_COMPAT_SCHEMA_VERSION << "' (or newer)! Please check the upgrade documentation at "
- << "https://docs.icinga.com/icinga2/latest/doc/module/icinga2/chapter/upgrading-icinga-2#upgrading-postgresql-db";
+ << "Schema version '" << version << "' does not match the required version '"
+ << IDO_COMPAT_SCHEMA_VERSION << "' (or newer)! Please check the upgrade documentation at "
+ << "https://docs.icinga.com/icinga2/latest/doc/module/icinga2/chapter/upgrading-icinga-2#upgrading-postgresql-db";
BOOST_THROW_EXCEPTION(std::runtime_error("Schema version mismatch."));
}
if (my_endpoint && GetHAMode() == HARunOnce) {
/* get the current endpoint writing to programstatus table */
result = Query("SELECT UNIX_TIMESTAMP(status_update_time) AS status_update_time, endpoint_name FROM " +
- GetTablePrefix() + "programstatus WHERE instance_id = " + Convert::ToString(m_InstanceID));
+ GetTablePrefix() + "programstatus WHERE instance_id = " + Convert::ToString(m_InstanceID));
row = FetchRow(result, 0);
String endpoint_name;
double status_update_age = Utility::GetTime() - status_update_time;
Log(LogNotice, "IdoPgsqlConnection")
- << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago.";
+ << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago.";
if (status_update_age < GetFailoverTimeout()) {
PQfinish(m_Connection);
/* activate the IDO only, if we're authoritative in this zone */
if (IsPaused()) {
Log(LogNotice, "IdoPgsqlConnection")
- << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out.";
+ << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out.";
PQfinish(m_Connection);
SetConnected(false);
}
Log(LogInformation, "IdoPgsqlConnection")
- << "pgSQL IDO instance id: " << static_cast<long>(m_InstanceID) << " (schema version: '" + version + "')";
+ << "pgSQL IDO instance id: " << static_cast<long>(m_InstanceID) << " (schema version: '" + version + "')";
Query("BEGIN");
/* record connection */
Query("INSERT INTO " + GetTablePrefix() + "conninfo " +
- "(instance_id, connect_time, last_checkin_time, agent_name, agent_version, connect_type, data_start_time) VALUES ("
- + Convert::ToString(static_cast<long>(m_InstanceID)) + ", NOW(), NOW(), E'icinga2 db_ido_pgsql', E'" + Escape(Application::GetAppVersion())
- + "', E'" + (reconnect ? "RECONNECT" : "INITIAL") + "', NOW())");
+ "(instance_id, connect_time, last_checkin_time, agent_name, agent_version, connect_type, data_start_time) VALUES ("
+ + Convert::ToString(static_cast<long>(m_InstanceID)) + ", NOW(), NOW(), E'icinga2 db_ido_pgsql', E'" + Escape(Application::GetAppVersion())
+ + "', E'" + (reconnect ? "RECONNECT" : "INITIAL") + "', NOW())");
/* clear config tables for the initial config dump */
PrepareDatabase();
continue;
Log(LogNotice, "IdoPgsqlConnection")
- << "Deactivate deleted object name1: '" << dbobj->GetName1()
- << "' name2: '" << dbobj->GetName2() + "'.";
+ << "Deactivate deleted object name1: '" << dbobj->GetName1()
+ << "' name2: '" << dbobj->GetName2() + "'.";
DeactivateObject(dbobj);
}
return;
Log(LogInformation, "IdoPgsqlConnection")
- << "Finished reconnecting to PostgreSQL IDO database in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
+ << "Finished reconnecting to PostgreSQL IDO database in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
Query("COMMIT");
Query("BEGIN");
void IdoPgsqlConnection::ClearTableBySession(const String& table)
{
Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
- Convert::ToString(static_cast<long>(m_InstanceID)) + " AND session_token <> " +
- Convert::ToString(GetSessionToken()));
+ Convert::ToString(static_cast<long>(m_InstanceID)) + " AND session_token <> " +
+ Convert::ToString(GetSessionToken()));
}
IdoPgsqlResult IdoPgsqlConnection::Query(const String& query)
AssertOnWorkQueue();
Log(LogDebug, "IdoPgsqlConnection")
- << "Query: " << query;
+ << "Query: " << query;
IncreaseQueryCount();
if (!result) {
String message = PQerrorMessage(m_Connection);
Log(LogCritical, "IdoPgsqlConnection")
- << "Error \"" << message << "\" when executing query \"" << query << "\"";
+ << "Error \"" << message << "\" when executing query \"" << query << "\"";
BOOST_THROW_EXCEPTION(
- database_error()
+ database_error()
<< errinfo_message(message)
<< errinfo_database_query(query)
);
PQclear(result);
Log(LogCritical, "IdoPgsqlConnection")
- << "Error \"" << message << "\" when executing query \"" << query << "\"";
+ << "Error \"" << message << "\" when executing query \"" << query << "\"";
BOOST_THROW_EXCEPTION(
- database_error()
+ database_error()
<< errinfo_message(message)
<< errinfo_database_query(query)
);
ASSERT(row);
Log(LogDebug, "IdoPgsqlConnection")
- << "Sequence Value: " << row->Get("id");
+ << "Sequence Value: " << row->Get("id");
return DbReference(Convert::ToLong(row->Get("id")));
}
if (!dbref.IsValid()) {
if (!dbobj->GetName2().IsEmpty()) {
qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, name2, is_active) VALUES ("
- << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
- << "E'" << Escape(dbobj->GetName1()) << "', E'" << Escape(dbobj->GetName2()) << "', 1)";
+ << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
+ << "E'" << Escape(dbobj->GetName1()) << "', E'" << Escape(dbobj->GetName2()) << "', 1)";
} else {
qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, is_active) VALUES ("
- << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
- << "E'" << Escape(dbobj->GetName1()) << "', 1)";
+ << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
+ << "E'" << Escape(dbobj->GetName1()) << "', 1)";
}
Query(qbuf.str());
return;
Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
- Convert::ToString(static_cast<long>(m_InstanceID)) + " AND " + time_column +
- " < TO_TIMESTAMP(" + Convert::ToString(static_cast<long>(max_age)) + ")");
+ Convert::ToString(static_cast<long>(m_InstanceID)) + " AND " + time_column +
+ " < TO_TIMESTAMP(" + Convert::ToString(static_cast<long>(max_age)) + ")");
}
void IdoPgsqlConnection::FillIDCache(const DbType::Ptr& type)
Value Demo::DemoMessageHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr&)
{
Log(LogInformation, "Demo")
- << "Got demo message from '" << origin->FromClient->GetEndpoint()->GetName() << "'";
+ << "Got demo message from '" << origin->FromClient->GetEndpoint()->GetName() << "'";
return Empty;
}
REGISTER_APIACTION(generate_ticket, "", &ApiActions::GenerateTicket);
Dictionary::Ptr ApiActions::CreateResult(int code, const String& status,
- const Dictionary::Ptr& additional)
+ const Dictionary::Ptr& additional)
{
Dictionary::Ptr result = new Dictionary();
result->Set("code", code);
}
Dictionary::Ptr ApiActions::ProcessCheckResult(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = static_pointer_cast<Checkable>(object);
if (!checkable)
return ApiActions::CreateResult(404,
- "Cannot process passive check result for non-existent object.");
+ "Cannot process passive check result for non-existent object.");
if (!checkable->GetEnablePassiveChecks())
return ApiActions::CreateResult(403, "Passive checks are disabled for object '" + checkable->GetName() + "'.");
state = ServiceCritical;
else
return ApiActions::CreateResult(400, "Invalid 'exit_status' for Host "
- + checkable->GetName() + ".");
+ + checkable->GetName() + ".");
} else {
state = PluginUtility::ExitStatusToState(exitStatus);
}
}
Dictionary::Ptr ApiActions::RescheduleCheck(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = static_pointer_cast<Checkable>(object);
}
Dictionary::Ptr ApiActions::SendCustomNotification(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = static_pointer_cast<Checkable>(object);
checkable->SetForceNextNotification(true);
Checkable::OnNotificationsRequested(checkable, NotificationCustom, checkable->GetLastCheckResult(),
- HttpUtility::GetLastParameter(params, "author"), HttpUtility::GetLastParameter(params, "comment"), nullptr);
+ HttpUtility::GetLastParameter(params, "author"), HttpUtility::GetLastParameter(params, "comment"), nullptr);
return ApiActions::CreateResult(200, "Successfully sent custom notification for object '" + checkable->GetName() + "'.");
}
Dictionary::Ptr ApiActions::DelayNotification(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = static_pointer_cast<Checkable>(object);
}
Dictionary::Ptr ApiActions::AcknowledgeProblem(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = static_pointer_cast<Checkable>(object);
}
Comment::AddComment(checkable, CommentAcknowledgement, HttpUtility::GetLastParameter(params, "author"),
- HttpUtility::GetLastParameter(params, "comment"), persistent, timestamp);
+ HttpUtility::GetLastParameter(params, "comment"), persistent, timestamp);
checkable->AcknowledgeProblem(HttpUtility::GetLastParameter(params, "author"),
- HttpUtility::GetLastParameter(params, "comment"), sticky, notify, persistent, timestamp);
+ HttpUtility::GetLastParameter(params, "comment"), sticky, notify, persistent, timestamp);
return ApiActions::CreateResult(200, "Successfully acknowledged problem for object '" + checkable->GetName() + "'.");
}
Dictionary::Ptr ApiActions::RemoveAcknowledgement(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = static_pointer_cast<Checkable>(object);
if (!checkable)
return ApiActions::CreateResult(404,
- "Cannot remove acknowlegement for non-existent checkable object "
- + object->GetName() + ".");
+ "Cannot remove acknowlegement for non-existent checkable object "
+ + object->GetName() + ".");
checkable->ClearAcknowledgement();
checkable->RemoveCommentsByType(CommentAcknowledgement);
}
Dictionary::Ptr ApiActions::AddComment(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = static_pointer_cast<Checkable>(object);
return ApiActions::CreateResult(400, "Comments require author and comment.");
String commentName = Comment::AddComment(checkable, CommentUser,
- HttpUtility::GetLastParameter(params, "author"),
- HttpUtility::GetLastParameter(params, "comment"), false, 0);
+ HttpUtility::GetLastParameter(params, "author"),
+ HttpUtility::GetLastParameter(params, "comment"), false, 0);
Comment::Ptr comment = Comment::GetByName(commentName);
additional->Set("legacy_id", comment->GetLegacyId());
return ApiActions::CreateResult(200, "Successfully added comment '"
- + commentName + "' for object '" + checkable->GetName()
- + "'.", additional);
+ + commentName + "' for object '" + checkable->GetName()
+ + "'.", additional);
}
Dictionary::Ptr ApiActions::RemoveComment(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = dynamic_pointer_cast<Checkable>(object);
}
Dictionary::Ptr ApiActions::ScheduleDowntime(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = static_pointer_cast<Checkable>(object);
return ApiActions::CreateResult(404, "Can't schedule downtime for non-existent object.");
if (!params->Contains("start_time") || !params->Contains("end_time") ||
- !params->Contains("author") || !params->Contains("comment")) {
+ !params->Contains("author") || !params->Contains("comment")) {
return ApiActions::CreateResult(400, "Options 'start_time', 'end_time', 'author' and 'comment' are required");
}
double endTime = HttpUtility::GetLastParameter(params, "end_time");
String downtimeName = Downtime::AddDowntime(checkable, author, comment, startTime, endTime,
- fixed, triggerName, duration);
+ fixed, triggerName, duration);
Downtime::Ptr downtime = Downtime::GetByName(downtimeName);
Array::Ptr childDowntimes = new Array();
Log(LogCritical, "ApiActions")
- << "Processing child options " << childOptions << " for downtime " << downtimeName;
+ << "Processing child options " << childOptions << " for downtime " << downtimeName;
for (const Checkable::Ptr& child : checkable->GetAllChildren()) {
Log(LogCritical, "ApiActions")
- << "Scheduling downtime for child object " << child->GetName();
+ << "Scheduling downtime for child object " << child->GetName();
String childDowntimeName = Downtime::AddDowntime(child, author, comment, startTime, endTime,
- fixed, triggerName, duration);
+ fixed, triggerName, duration);
Log(LogCritical, "ApiActions")
- << "Add child downtime '" << childDowntimeName << "'.";
+ << "Add child downtime '" << childDowntimeName << "'.";
Downtime::Ptr childDowntime = Downtime::GetByName(childDowntimeName);
}
return ApiActions::CreateResult(200, "Successfully scheduled downtime '" +
- downtimeName + "' for object '" + checkable->GetName() + "'.", additional);
+ downtimeName + "' for object '" + checkable->GetName() + "'.", additional);
}
Dictionary::Ptr ApiActions::RemoveDowntime(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Checkable::Ptr checkable = dynamic_pointer_cast<Checkable>(object);
}
Dictionary::Ptr ApiActions::ShutdownProcess(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Application::RequestShutdown();
}
Dictionary::Ptr ApiActions::RestartProcess(const ConfigObject::Ptr& object,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
Application::RequestRestart();
}
Dictionary::Ptr ApiActions::GenerateTicket(const ConfigObject::Ptr&,
- const Dictionary::Ptr& params)
+ const Dictionary::Ptr& params)
{
if (!params->Contains("cn"))
return ApiActions::CreateResult(400, "Option 'cn' is required");
additional->Set("ticket", ticket);
return ApiActions::CreateResult(200, "Generated PKI ticket '" + ticket + "' for common name '"
- + cn + "'.", additional);
+ + cn + "'.", additional);
}
}
void ApiEvents::NotificationSentToAllUsersHandler(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 MessageOrigin::Ptr& origin)
+ const Checkable::Ptr& checkable, const std::set<User::Ptr>& users, NotificationType type,
+ const CheckResult::Ptr& cr, const String& author, const String& text, const MessageOrigin::Ptr& origin)
{
std::vector<EventQueue::Ptr> queues = EventQueue::GetQueuesForType("Notification");
}
void ApiEvents::AcknowledgementSetHandler(const Checkable::Ptr& checkable,
- const String& author, const String& comment, AcknowledgementType type,
- bool notify, bool persistent, double expiry, const MessageOrigin::Ptr& origin)
+ const String& author, const String& comment, AcknowledgementType type,
+ bool notify, bool persistent, double expiry, const MessageOrigin::Ptr& origin)
{
std::vector<EventQueue::Ptr> queues = EventQueue::GetQueuesForType("AcknowledgementSet");
static void NotificationSentToAllUsersHandler(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 MessageOrigin::Ptr& origin);
+ const std::set<User::Ptr>& users, NotificationType type, const CheckResult::Ptr& cr, const String& author,
+ const String& text, const MessageOrigin::Ptr& origin);
static void FlappingChangedHandler(const Checkable::Ptr& checkable, const MessageOrigin::Ptr& origin);
static void AcknowledgementSetHandler(const Checkable::Ptr& checkable,
- const String& author, const String& comment, AcknowledgementType type,
- bool notify, bool persistent, double expiry, const MessageOrigin::Ptr& origin);
+ const String& author, const String& comment, AcknowledgementType type,
+ bool notify, bool persistent, double expiry, const MessageOrigin::Ptr& origin);
static void AcknowledgementClearedHandler(const Checkable::Ptr& checkable, const MessageOrigin::Ptr& origin);
static void CommentAddedHandler(const Comment::Ptr& comment);
/* remove acknowledgements */
if (GetAcknowledgement() == AcknowledgementNormal ||
- (GetAcknowledgement() == AcknowledgementSticky && IsStateOK(new_state))) {
+ (GetAcknowledgement() == AcknowledgementSticky && IsStateOK(new_state))) {
ClearAcknowledgement();
}
#ifdef I2_DEBUG /* I2_DEBUG */
Log(LogDebug, "Checkable")
- << "Flapping: Checkable " << GetName()
- << " was: " << was_flapping
- << " is: " << is_flapping
- << " threshold low: " << GetFlappingThresholdLow()
- << " threshold high: " << GetFlappingThresholdHigh()
- << "% current: " << GetFlappingCurrent() << "%.";
+ << "Flapping: Checkable " << GetName()
+ << " was: " << was_flapping
+ << " is: " << is_flapping
+ << " threshold low: " << GetFlappingThresholdLow()
+ << " threshold high: " << GetFlappingThresholdHigh()
+ << "% current: " << GetFlappingCurrent() << "%.";
#endif /* I2_DEBUG */
OnNewCheckResult(this, cr, origin);
if (hardChange || (is_volatile && !(IsStateOK(old_state) && IsStateOK(new_state)))) {
OnStateChange(this, cr, StateTypeHard, origin);
Log(LogNotice, "Checkable")
- << "State Change: Checkable '" << GetName() << "' hard state change from " << old_state_str << " to " << new_state_str << " detected." << (is_volatile ? " Checkable is volatile." : "");
+ << "State Change: Checkable '" << GetName() << "' hard state change from " << old_state_str << " to " << new_state_str << " detected." << (is_volatile ? " Checkable is volatile." : "");
}
/* Whether a state change happened or the state type is SOFT (must be logged too). */
else if (stateChange || GetStateType() == StateTypeSoft) {
OnStateChange(this, cr, StateTypeSoft, origin);
Log(LogNotice, "Checkable")
- << "State Change: Checkable '" << GetName() << "' soft state change from " << old_state_str << " to " << new_state_str << " detected.";
+ << "State Change: Checkable '" << GetName() << "' soft state change from " << old_state_str << " to " << new_state_str << " detected.";
}
if (GetStateType() == StateTypeSoft || hardChange || recovery ||
- (is_volatile && !(IsStateOK(old_state) && IsStateOK(new_state))))
+ (is_volatile && !(IsStateOK(old_state) && IsStateOK(new_state))))
ExecuteEventHandler();
/* Flapping start/end notifications */
OnNotificationsRequested(this, NotificationFlappingStart, cr, "", "", nullptr);
Log(LogNotice, "Checkable")
- << "Flapping Start: Checkable '" << GetName() << "' started flapping (Current flapping value "
- << GetFlappingCurrent() << "% > high threshold " << GetFlappingThresholdHigh() << "%).";
+ << "Flapping Start: Checkable '" << GetName() << "' started flapping (Current flapping value "
+ << GetFlappingCurrent() << "% > high threshold " << GetFlappingThresholdHigh() << "%).";
NotifyFlapping(origin);
} else if (!in_downtime && was_flapping && !is_flapping) {
OnNotificationsRequested(this, NotificationFlappingEnd, cr, "", "", nullptr);
Log(LogNotice, "Checkable")
- << "Flapping Stop: Checkable '" << GetName() << "' stopped flapping (Current flapping value "
- << GetFlappingCurrent() << "% < low threshold " << GetFlappingThresholdLow() << "%).";
+ << "Flapping Stop: Checkable '" << GetName() << "' stopped flapping (Current flapping value "
+ << GetFlappingCurrent() << "% < low threshold " << GetFlappingThresholdLow() << "%).";
NotifyFlapping(origin);
}
listener->SyncSendMessage(endpoint, message);
/* Re-schedule the check so we don't run it again until after we've received
- a check result from the remote instance. The check will be re-scheduled
- using the proper check interval once we've received a check result. */
+ * a check result from the remote instance. The check will be re-scheduled
+ * using the proper check interval once we've received a check result.
+ */
SetNextCheck(Utility::GetTime() + GetCheckCommand()->GetTimeout() + 30);
} else if (!endpoint->GetSyncing() && Application::GetInstance()->GetStartTime() < Utility::GetTime() - 300) {
/* fail to perform check on unconnected endpoint */
{
if (rstack > 20) {
Log(LogWarning, "Checkable")
- << "Too many nested dependencies for service '" << GetName() << "': Dependency failed.";
+ << "Too many nested dependencies for service '" << GetName() << "': Dependency failed.";
return false;
}
return;
Log(LogNotice, "Checkable")
- << "Executing event handler '" << ec->GetName() << "' for service '" << GetName() << "'";
+ << "Executing event handler '" << ec->GetName() << "' for service '" << GetName() << "'";
Dictionary::Ptr macros;
Endpoint::Ptr endpoint = GetCommandEndpoint();
using namespace icinga;
boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const std::set<User::Ptr>&,
- const NotificationType&, const CheckResult::Ptr&, const String&, const String&,
- const MessageOrigin::Ptr&)> Checkable::OnNotificationSentToAllUsers;
+ const NotificationType&, const CheckResult::Ptr&, const String&, const String&,
+ const MessageOrigin::Ptr&)> Checkable::OnNotificationSentToAllUsers;
boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const User::Ptr&,
- const NotificationType&, const CheckResult::Ptr&, const String&, const String&, const String&,
- const MessageOrigin::Ptr&)> Checkable::OnNotificationSentToUser;
+ const NotificationType&, const CheckResult::Ptr&, const String&, const String&, const String&,
+ const MessageOrigin::Ptr&)> Checkable::OnNotificationSentToUser;
void Checkable::ResetNotificationNumbers(void)
{
if (!IcingaApplication::GetInstance()->GetEnableNotifications() || !GetEnableNotifications()) {
if (!force) {
Log(LogInformation, "Checkable")
- << "Notifications are disabled for service '" << GetName() << "'.";
+ << "Notifications are disabled for service '" << GetName() << "'.";
return;
}
}
Log(LogInformation, "Checkable")
- << "Checking for configured notifications for object '" << GetName() << "'";
+ << "Checking for configured notifications for object '" << GetName() << "'";
std::set<Notification::Ptr> notifications = GetNotifications();
if (notifications.empty())
Log(LogInformation, "Checkable")
- << "Checkable '" << GetName() << "' does not have any notifications.";
+ << "Checkable '" << GetName() << "' does not have any notifications.";
Log(LogDebug, "Checkable")
- << "Checkable '" << GetName() << "' has " << notifications.size() << " notification(s).";
+ << "Checkable '" << GetName() << "' has " << notifications.size() << " notification(s).";
for (const Notification::Ptr& notification : notifications) {
try {
notification->BeginExecuteNotification(type, cr, force, false, author, text);
} catch (const std::exception& ex) {
Log(LogWarning, "Checkable")
- << "Exception occured during notification for service '"
- << GetName() << "': " << DiagnosticInformation(ex);
+ << "Exception occured during notification for service '"
+ << GetName() << "': " << DiagnosticInformation(ex);
}
}
}
if (checkableZone && cmdZone != checkableZone && cmdZone->GetParent() != checkableZone) {
BOOST_THROW_EXCEPTION(ValidationError(this, { "command_endpoint" },
- "Command endpoint must be in zone '" + checkableZone->GetName() + "' or in a direct child zone thereof."));
+ "Command endpoint must be in zone '" + checkableZone->GetName() + "' or in a direct child zone thereof."));
}
}
}
static boost::signals2::signal<void (const Checkable::Ptr&, const CheckResult::Ptr&, StateType, const MessageOrigin::Ptr&)> OnStateChange;
static boost::signals2::signal<void (const Checkable::Ptr&, const CheckResult::Ptr&, std::set<Checkable::Ptr>, const MessageOrigin::Ptr&)> OnReachabilityChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, NotificationType, const CheckResult::Ptr&,
- const String&, const String&, const MessageOrigin::Ptr&)> OnNotificationsRequested;
+ const String&, const String&, const MessageOrigin::Ptr&)> OnNotificationsRequested;
static boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const User::Ptr&,
- const NotificationType&, const CheckResult::Ptr&, const String&, const String&, const String&,
- const MessageOrigin::Ptr&)> OnNotificationSentToUser;
+ const NotificationType&, const CheckResult::Ptr&, const String&, const String&, const String&,
+ const MessageOrigin::Ptr&)> OnNotificationSentToUser;
static boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const std::set<User::Ptr>&,
- const NotificationType&, const CheckResult::Ptr&, const String&,
- const String&, const MessageOrigin::Ptr&)> OnNotificationSentToAllUsers;
+ const NotificationType&, const CheckResult::Ptr&, const String&,
+ const String&, const MessageOrigin::Ptr&)> OnNotificationSentToAllUsers;
static boost::signals2::signal<void (const Checkable::Ptr&, const String&, const String&, AcknowledgementType,
- bool, bool, double, const MessageOrigin::Ptr&)> OnAcknowledgementSet;
+ bool, bool, double, const MessageOrigin::Ptr&)> OnAcknowledgementSet;
static boost::signals2::signal<void (const Checkable::Ptr&, const MessageOrigin::Ptr&)> OnAcknowledgementCleared;
static boost::signals2::signal<void (const Checkable::Ptr&)> OnNextCheckUpdated;
static boost::signals2::signal<void (const Checkable::Ptr&)> OnEventCommandExecuted;
/* Event Handler */
void ExecuteEventHandler(const Dictionary::Ptr& resolvedMacros = nullptr,
- bool useResolvedMacros = false);
+ bool useResolvedMacros = false);
intrusive_ptr<EventCommand> GetEventCommand(void) const;
REGISTER_TYPE(CheckCommand);
void CheckCommand::Execute(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
GetExecute()->Invoke({
- checkable,
- cr,
- resolvedMacros,
- useResolvedMacros
+ checkable,
+ cr,
+ resolvedMacros,
+ useResolvedMacros
});
}
DECLARE_OBJECTNAME(CheckCommand);
virtual void Execute(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros = nullptr,
- bool useResolvedMacros = false);
+ const Dictionary::Ptr& resolvedMacros = nullptr,
+ bool useResolvedMacros = false);
};
}
{
struct CheckableCheckStatistics {
- double min_latency;
- double max_latency;
- double avg_latency;
- double min_execution_time;
- double max_execution_time;
- double avg_execution_time;
+ double min_latency;
+ double max_latency;
+ double avg_latency;
+ double min_execution_time;
+ double max_execution_time;
+ double avg_execution_time;
};
struct ServiceStatistics {
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'check result' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'check result' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && !origin->FromZone->CanAccessObject(checkable) && endpoint != checkable->GetCommandEndpoint()) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'check result' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'check result' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'next check changed' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'next check changed' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && !origin->FromZone->CanAccessObject(checkable)) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'next check changed' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'next check changed' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'next notification changed' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'next notification changed' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && !origin->FromZone->CanAccessObject(notification)) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'next notification changed' message for notification '" << notification->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'next notification changed' message for notification '" << notification->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'force next check changed' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'force next check changed' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && !origin->FromZone->CanAccessObject(checkable)) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'force next check' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'force next check' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'force next notification changed' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'force next notification changed' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && !origin->FromZone->CanAccessObject(checkable)) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'force next notification' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'force next notification' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
}
void ClusterEvents::AcknowledgementSetHandler(const Checkable::Ptr& checkable,
- const String& author, const String& comment, AcknowledgementType type,
- bool notify, bool persistent, double expiry, const MessageOrigin::Ptr& origin)
+ const String& author, const String& comment, AcknowledgementType type,
+ bool notify, bool persistent, double expiry, const MessageOrigin::Ptr& origin)
{
ApiListener::Ptr listener = ApiListener::GetInstance();
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'acknowledgement set' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'acknowledgement set' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && !origin->FromZone->CanAccessObject(checkable)) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'acknowledgement set' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'acknowledgement set' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
checkable->AcknowledgeProblem(params->Get("author"), params->Get("comment"),
- static_cast<AcknowledgementType>(static_cast<int>(params->Get("acktype"))),
- params->Get("notify"), params->Get("persistent"), params->Get("expiry"), origin);
+ static_cast<AcknowledgementType>(static_cast<int>(params->Get("acktype"))),
+ params->Get("notify"), params->Get("persistent"), params->Get("expiry"), origin);
return Empty;
}
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'acknowledgement cleared' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'acknowledgement cleared' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && !origin->FromZone->CanAccessObject(checkable)) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'acknowledgement cleared' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'acknowledgement cleared' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
if (!sourceEndpoint || (origin->FromZone && !Zone::GetLocalZone()->IsChildOf(origin->FromZone))) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'execute command' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'execute command' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (!listener->GetAcceptCommands()) {
Log(LogWarning, "ApiListener")
- << "Ignoring command. '" << listener->GetName() << "' does not accept commands.";
+ << "Ignoring command. '" << listener->GetName() << "' does not accept commands.";
Host::Ptr host = new Host();
Dictionary::Ptr attrs = new Dictionary();
} else if (command_type == "event_command") {
if (!EventCommand::GetByName(command)) {
Log(LogWarning, "ClusterEvents")
- << "Event command '" << command << "' does not exist.";
+ << "Event command '" << command << "' does not exist.";
return Empty;
}
} else
}
void ClusterEvents::SendNotificationsHandler(const Checkable::Ptr& checkable, NotificationType type,
- const CheckResult::Ptr& cr, const String& author, const String& text, const MessageOrigin::Ptr& origin)
+ const CheckResult::Ptr& cr, const String& author, const String& text, const MessageOrigin::Ptr& origin)
{
ApiListener::Ptr listener = ApiListener::GetInstance();
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'send notification' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'send notification' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && origin->FromZone != Zone::GetLocalZone()) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'send custom notification' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'send custom notification' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
}
void ClusterEvents::NotificationSentUserHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const User::Ptr& user,
- NotificationType notificationType, const CheckResult::Ptr& cr, const String& author, const String& commentText, const String& command,
- const MessageOrigin::Ptr& origin)
+ NotificationType notificationType, const CheckResult::Ptr& cr, const String& author, const String& commentText, const String& command,
+ const MessageOrigin::Ptr& origin)
{
ApiListener::Ptr listener = ApiListener::GetInstance();
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'sent notification to user' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'sent notification to user' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && origin->FromZone != Zone::GetLocalZone()) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'send notification to user' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'send notification to user' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
}
void ClusterEvents::NotificationSentToAllUsersHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const std::set<User::Ptr>& users,
- NotificationType notificationType, const CheckResult::Ptr& cr, const String& author, const String& commentText, const MessageOrigin::Ptr& origin)
+ NotificationType notificationType, const CheckResult::Ptr& cr, const String& author, const String& commentText, const MessageOrigin::Ptr& origin)
{
ApiListener::Ptr listener = ApiListener::GetInstance();
if (!endpoint) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'sent notification to all users' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'sent notification to all users' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
if (origin->FromZone && origin->FromZone != Zone::GetLocalZone()) {
Log(LogNotice, "ClusterEvents")
- << "Discarding 'sent notification to all users' message for checkable '" << checkable->GetName()
- << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
+ << "Discarding 'sent notification to all users' message for checkable '" << checkable->GetName()
+ << "' from '" << origin->FromClient->GetIdentity() << "': Unauthorized access.";
return Empty;
}
static Value ForceNextNotificationChangedAPIHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params);
static void AcknowledgementSetHandler(const Checkable::Ptr& checkable, const String& author, const String& comment, AcknowledgementType type,
- bool notify, bool persistent, double expiry, const MessageOrigin::Ptr& origin);
+ bool notify, bool persistent, double expiry, const MessageOrigin::Ptr& origin);
static Value AcknowledgementSetAPIHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params);
static void AcknowledgementClearedHandler(const Checkable::Ptr& checkable, const MessageOrigin::Ptr& origin);
static Dictionary::Ptr MakeCheckResultMessage(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr);
static void SendNotificationsHandler(const Checkable::Ptr& checkable, NotificationType type,
- const CheckResult::Ptr& cr, const String& author, const String& text, const MessageOrigin::Ptr& origin);
+ const CheckResult::Ptr& cr, const String& author, const String& text, const MessageOrigin::Ptr& origin);
static Value SendNotificationsAPIHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params);
static void NotificationSentUserHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const User::Ptr& user,
- NotificationType notificationType, const CheckResult::Ptr& cr, const String& author, const String& commentText, const String& command, const MessageOrigin::Ptr& origin);
+ NotificationType notificationType, const CheckResult::Ptr& cr, const String& author, const String& commentText, const String& command, const MessageOrigin::Ptr& origin);
static Value NotificationSentUserAPIHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params);
static void NotificationSentToAllUsersHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const std::set<User::Ptr>& users,
- NotificationType notificationType, const CheckResult::Ptr& cr, const String& author, const String& commentText, const MessageOrigin::Ptr& origin);
+ NotificationType notificationType, const CheckResult::Ptr& cr, const String& author, const String& commentText, const MessageOrigin::Ptr& origin);
static Value NotificationSentToAllUsersAPIHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params);
};
}
String Comment::AddComment(const Checkable::Ptr& checkable, CommentType entryType, const String& author,
- const String& text, bool persistent, double expireTime, const String& id, const MessageOrigin::Ptr& origin)
+ const String& text, bool persistent, double expireTime, const String& id, const MessageOrigin::Ptr& origin)
{
String fullName;
BOOST_THROW_EXCEPTION(std::runtime_error("Could not create comment."));
Log(LogNotice, "Comment")
- << "Added comment '" << comment->GetName() << "'.";
+ << "Added comment '" << comment->GetName() << "'.";
return fullName;
}
return;
Log(LogNotice, "Comment")
- << "Removed comment '" << comment->GetName() << "' from object '" << comment->GetCheckable()->GetName() << "'.";
+ << "Removed comment '" << comment->GetName() << "' from object '" << comment->GetCheckable()->GetName() << "'.";
Array::Ptr errors = new Array();
static int GetNextCommentID(void);
static String AddComment(const intrusive_ptr<Checkable>& checkable, CommentType entryType,
- const String& author, const String& text, bool persistent, double expireTime,
- const String& id = String(), const MessageOrigin::Ptr& origin = nullptr);
+ const String& author, const String& text, bool persistent, double expireTime,
+ const String& id = String(), const MessageOrigin::Ptr& origin = nullptr);
static void RemoveComment(const String& id, const MessageOrigin::Ptr& origin = nullptr);
unsigned long notification_state_filter = GetCheckableNotificationStateFilter(host);
if ((notification_state_filter & ServiceCritical) ||
- (notification_state_filter & ServiceWarning))
+ (notification_state_filter & ServiceWarning))
return 1;
return 0;
notification_options.push_back("r");
}
if ((notification_type_filter & NotificationFlappingStart) ||
- (notification_type_filter & NotificationFlappingEnd)) {
+ (notification_type_filter & NotificationFlappingEnd)) {
notification_options.push_back("f");
}
if ((notification_type_filter & NotificationDowntimeStart) ||
- (notification_type_filter & NotificationDowntimeEnd) ||
- (notification_type_filter & NotificationDowntimeRemoved)) {
+ (notification_type_filter & NotificationDowntimeEnd) ||
+ (notification_type_filter & NotificationDowntimeRemoved)) {
notification_options.push_back("s");
}
unsigned long notification_type_filter = GetCheckableNotificationTypeFilter(checkable);
if ((notification_type_filter & NotificationFlappingStart) ||
- (notification_type_filter & NotificationFlappingEnd))
+ (notification_type_filter & NotificationFlappingEnd))
return 1;
return 0;
unsigned long notification_type_filter = GetCheckableNotificationTypeFilter(checkable);
if ((notification_type_filter & NotificationDowntimeStart) ||
- (notification_type_filter & NotificationDowntimeEnd) ||
- (notification_type_filter & NotificationDowntimeRemoved))
+ (notification_type_filter & NotificationDowntimeEnd) ||
+ (notification_type_filter & NotificationDowntimeRemoved))
return 1;
return 0;
/* ignore if it's the same checkable object */
if (parent == GetChild()) {
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' passed: Parent and child " << (parentService ? "service" : "host") << " are identical.";
+ << "Dependency '" << GetName() << "' passed: Parent and child " << (parentService ? "service" : "host") << " are identical.";
return true;
}
/* ignore pending */
if (!parent->GetLastCheckResult()) {
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' passed: Parent " << (parentService ? "service" : "host") << " '" << parent->GetName() << "' hasn't been checked yet.";
+ << "Dependency '" << GetName() << "' passed: Parent " << (parentService ? "service" : "host") << " '" << parent->GetName() << "' hasn't been checked yet.";
return true;
}
/* ignore soft states */
if (parent->GetStateType() == StateTypeSoft) {
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' passed: Parent " << (parentService ? "service" : "host") << " '" << parent->GetName() << "' is in a soft state.";
+ << "Dependency '" << GetName() << "' passed: Parent " << (parentService ? "service" : "host") << " '" << parent->GetName() << "' is in a soft state.";
return true;
}
} else {
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' failed: Parent " << (parentService ? "service" : "host") << " '" << parent->GetName() << "' is in a soft state.";
+ << "Dependency '" << GetName() << "' failed: Parent " << (parentService ? "service" : "host") << " '" << parent->GetName() << "' is in a soft state.";
}
int state;
/* check state */
if (state & GetStateFilter()) {
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' passed: Parent " << (parentService ? "service" : "host") << " '" << parent->GetName() << "' matches state filter.";
+ << "Dependency '" << GetName() << "' passed: Parent " << (parentService ? "service" : "host") << " '" << parent->GetName() << "' matches state filter.";
return true;
}
TimePeriod::Ptr tp = GetPeriod();
if (tp && !tp->IsInside(Utility::GetTime())) {
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' passed: Outside time period.";
+ << "Dependency '" << GetName() << "' passed: Outside time period.";
return true;
}
if (dt == DependencyCheckExecution && !GetDisableChecks()) {
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' passed: Checks are not disabled.";
+ << "Dependency '" << GetName() << "' passed: Checks are not disabled.";
return true;
} else if (dt == DependencyNotification && !GetDisableNotifications()) {
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' passed: Notifications are not disabled";
+ << "Dependency '" << GetName() << "' passed: Notifications are not disabled";
return true;
}
Log(LogNotice, "Dependency")
- << "Dependency '" << GetName() << "' failed. Parent "
- << (parentService ? "service" : "host") << " '" << parent->GetName() << "' is "
- << (parentService ? Service::StateToString(parentService->GetState()) : Host::StateToString(parentHost->GetState()));
+ << "Dependency '" << GetName() << "' failed. Parent "
+ << (parentService ? "service" : "host") << " '" << parent->GetName() << "' is "
+ << (parentService ? Service::StateToString(parentService->GetState()) : Host::StateToString(parentHost->GetState()));
return false;
}
*/
if (!checkable->IsStateOK(checkable->GetStateRaw())) {
Log(LogNotice, "Downtime")
- << "Checkable '" << checkable->GetName() << "' already in a NOT-OK state."
- << " Triggering downtime now.";
+ << "Checkable '" << checkable->GetName() << "' already in a NOT-OK state."
+ << " Triggering downtime now.";
TriggerDowntime();
}
}
}
String Downtime::AddDowntime(const Checkable::Ptr& checkable, const String& author,
- const String& comment, double startTime, double endTime, bool fixed,
- const String& triggeredBy, double duration,
- const String& scheduledDowntime, const String& scheduledBy,
- const String& id, const MessageOrigin::Ptr& origin)
+ const String& comment, double startTime, double endTime, bool fixed,
+ const String& triggeredBy, double duration,
+ const String& scheduledDowntime, const String& scheduledBy,
+ const String& id, const MessageOrigin::Ptr& origin)
{
String fullName;
BOOST_THROW_EXCEPTION(std::runtime_error("Could not create downtime object."));
Log(LogNotice, "Downtime")
- << "Added downtime '" << downtime->GetName()
- << "' between '" << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", startTime)
- << "' and '" << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime) << "'.";
+ << "Added downtime '" << downtime->GetName()
+ << "' between '" << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", startTime)
+ << "' and '" << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime) << "'.";
return fullName;
}
if (!config_owner.IsEmpty() && !expired) {
Log(LogWarning, "Downtime")
- << "Cannot remove downtime '" << downtime->GetName() << "'. It is owned by scheduled downtime object '" << config_owner << "'";
+ << "Cannot remove downtime '" << downtime->GetName() << "'. It is owned by scheduled downtime object '" << config_owner << "'";
return;
}
downtime->SetWasCancelled(cancelled);
Log(LogNotice, "Downtime")
- << "Removed downtime '" << downtime->GetName() << "' from object '" << downtime->GetCheckable()->GetName() << "'.";
+ << "Removed downtime '" << downtime->GetName() << "' from object '" << downtime->GetCheckable()->GetName() << "'.";
Array::Ptr errors = new Array();
/* Start fixed downtimes. Flexible downtimes will be triggered on-demand. */
for (const Downtime::Ptr& downtime : ConfigType::GetObjectsByType<Downtime>()) {
if (downtime->IsActive() &&
- downtime->CanBeTriggered() &&
- downtime->GetFixed()) {
+ downtime->CanBeTriggered() &&
+ downtime->GetFixed()) {
/* Send notifications. */
OnDowntimeStarted(downtime);
static int GetNextDowntimeID(void);
static String AddDowntime(const intrusive_ptr<Checkable>& checkable, const String& author,
- const String& comment, double startTime, double endTime, bool fixed,
- const String& triggeredBy, double duration, const String& scheduledDowntime = String(),
- const String& scheduledBy = String(), const String& id = String(),
- const MessageOrigin::Ptr& origin = nullptr);
+ const String& comment, double startTime, double endTime, bool fixed,
+ const String& triggeredBy, double duration, const String& scheduledDowntime = String(),
+ const String& scheduledBy = String(), const String& id = String(),
+ const MessageOrigin::Ptr& origin = nullptr);
static void RemoveDowntime(const String& id, bool cancelled, bool expired = false, const MessageOrigin::Ptr& origin = nullptr);
REGISTER_TYPE(EventCommand);
void EventCommand::Execute(const Checkable::Ptr& checkable,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
GetExecute()->Invoke({
- checkable,
- resolvedMacros,
- useResolvedMacros
+ checkable,
+ resolvedMacros,
+ useResolvedMacros
});
}
DECLARE_OBJECTNAME(EventCommand);
virtual void Execute(const Checkable::Ptr& checkable,
- const Dictionary::Ptr& resolvedMacros = nullptr,
- bool useResolvedMacros = false);
+ const Dictionary::Ptr& resolvedMacros = nullptr,
+ bool useResolvedMacros = false);
};
}
result->SetActive(false);
Log(LogNotice, "ExternalCommandProcessor")
- << "Processing passive check result for host '" << arguments[0] << "'";
+ << "Processing passive check result for host '" << arguments[0] << "'";
host->ProcessCheckResult(result);
}
result->SetActive(false);
Log(LogNotice, "ExternalCommandProcessor")
- << "Processing passive check result for service '" << arguments[1] << "'";
+ << "Processing passive check result for service '" << arguments[1] << "'";
service->ProcessCheckResult(result);
}
if (planned_check > host->GetNextCheck()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Ignoring reschedule request for host '"
- << arguments[0] << "' (next check is already sooner than requested check time)";
+ << "Ignoring reschedule request for host '"
+ << arguments[0] << "' (next check is already sooner than requested check time)";
return;
}
Log(LogNotice, "ExternalCommandProcessor")
- << "Rescheduling next check for host '" << arguments[0] << "'";
+ << "Rescheduling next check for host '" << arguments[0] << "'";
if (planned_check < Utility::GetTime())
planned_check = Utility::GetTime();
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot reschedule forced host check for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Rescheduling next check for host '" << arguments[0] << "'";
+ << "Rescheduling next check for host '" << arguments[0] << "'";
host->SetForceNextCheck(true);
host->SetNextCheck(Convert::ToDouble(arguments[1]));
if (planned_check > service->GetNextCheck()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Ignoring reschedule request for service '"
- << arguments[1] << "' (next check is already sooner than requested check time)";
+ << "Ignoring reschedule request for service '"
+ << arguments[1] << "' (next check is already sooner than requested check time)";
return;
}
Log(LogNotice, "ExternalCommandProcessor")
- << "Rescheduling next check for service '" << arguments[1] << "'";
+ << "Rescheduling next check for service '" << arguments[1] << "'";
if (planned_check < Utility::GetTime())
planned_check = Utility::GetTime();
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot reschedule forced service check for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Rescheduling next check for service '" << arguments[1] << "'";
+ << "Rescheduling next check for service '" << arguments[1] << "'";
service->SetForceNextCheck(true);
service->SetNextCheck(Convert::ToDouble(arguments[2]));
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host checks for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling active checks for host '" << arguments[0] << "'";
+ << "Enabling active checks for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_active_checks", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host check non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling active checks for host '" << arguments[0] << "'";
+ << "Disabling active checks for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_active_checks", false);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable service check for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling active checks for service '" << arguments[1] << "'";
+ << "Enabling active checks for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_active_checks", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable service check for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling active checks for service '" << arguments[1] << "'";
+ << "Disabling active checks for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_active_checks", false);
}
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Rescheduling next check for service '" << service->GetName() << "'";
+ << "Rescheduling next check for service '" << service->GetName() << "'";
service->SetNextCheck(planned_check);
service->SetForceNextCheck(true);
for (const Service::Ptr& service : host->GetServices()) {
if (planned_check > service->GetNextCheck()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Ignoring reschedule request for service '"
- << service->GetName() << "' (next check is already sooner than requested check time)";
+ << "Ignoring reschedule request for service '"
+ << service->GetName() << "' (next check is already sooner than requested check time)";
continue;
}
Log(LogNotice, "ExternalCommandProcessor")
- << "Rescheduling next check for service '" << service->GetName() << "'";
+ << "Rescheduling next check for service '" << service->GetName() << "'";
service->SetNextCheck(planned_check);
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling active checks for service '" << service->GetName() << "'";
+ << "Enabling active checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_active_checks", true);
}
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling active checks for service '" << service->GetName() << "'";
+ << "Disabling active checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_active_checks", false);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("The service '" + arguments[1] + "' is OK."));
Log(LogNotice, "ExternalCommandProcessor")
- << "Setting acknowledgement for service '" << service->GetName() << "'" << (notify ? "" : ". Disabled notification");
+ << "Setting acknowledgement for service '" << service->GetName() << "'" << (notify ? "" : ". Disabled notification");
Comment::AddComment(service, CommentAcknowledgement, arguments[5], arguments[6], persistent, 0);
service->AcknowledgeProblem(arguments[5], arguments[6], sticky ? AcknowledgementSticky : AcknowledgementNormal, notify, persistent);
BOOST_THROW_EXCEPTION(std::invalid_argument("Acknowledgement expire time must be in the future for service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Setting timed acknowledgement for service '" << service->GetName() << "'" << (notify ? "" : ". Disabled notification");
+ << "Setting timed acknowledgement for service '" << service->GetName() << "'" << (notify ? "" : ". Disabled notification");
Comment::AddComment(service, CommentAcknowledgement, arguments[6], arguments[7], persistent, timestamp);
service->AcknowledgeProblem(arguments[6], arguments[7], sticky ? AcknowledgementSticky : AcknowledgementNormal, notify, persistent, timestamp);
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot remove service acknowledgement for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing acknowledgement for service '" << service->GetName() << "'";
+ << "Removing acknowledgement for service '" << service->GetName() << "'";
{
ObjectLock olock(service);
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot acknowledge host problem for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Setting acknowledgement for host '" << host->GetName() << "'" << (notify ? "" : ". Disabled notification");
+ << "Setting acknowledgement for host '" << host->GetName() << "'" << (notify ? "" : ". Disabled notification");
if (host->GetState() == HostUp)
BOOST_THROW_EXCEPTION(std::invalid_argument("The host '" + arguments[0] + "' is OK."));
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot acknowledge host problem with expire time for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Setting timed acknowledgement for host '" << host->GetName() << "'" << (notify ? "" : ". Disabled notification");
+ << "Setting timed acknowledgement for host '" << host->GetName() << "'" << (notify ? "" : ". Disabled notification");
if (host->GetState() == HostUp)
BOOST_THROW_EXCEPTION(std::invalid_argument("The host '" + arguments[0] + "' is OK."));
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot remove acknowledgement for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing acknowledgement for host '" << host->GetName() << "'";
+ << "Removing acknowledgement for host '" << host->GetName() << "'";
{
ObjectLock olock(host);
for (const Host::Ptr& host : hg->GetMembers()) {
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling active checks for service '" << service->GetName() << "'";
+ << "Enabling active checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_active_checks", true);
}
for (const Host::Ptr& host : hg->GetMembers()) {
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling active checks for service '" << service->GetName() << "'";
+ << "Disabling active checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_active_checks", false);
}
for (const Service::Ptr& service : sg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling active checks for service '" << service->GetName() << "'";
+ << "Enabling active checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_active_checks", true);
}
for (const Service::Ptr& service : sg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling active checks for service '" << service->GetName() << "'";
+ << "Disabling active checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_active_checks", false);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable passive host checks for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling passive checks for host '" << arguments[0] << "'";
+ << "Enabling passive checks for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_passive_checks", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable passive host checks for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling passive checks for host '" << arguments[0] << "'";
+ << "Disabling passive checks for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_passive_checks", false);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable service checks for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling passive checks for service '" << arguments[1] << "'";
+ << "Enabling passive checks for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_passive_checks", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable service checks for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling passive checks for service '" << arguments[1] << "'";
+ << "Disabling passive checks for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_passive_checks", false);
}
for (const Service::Ptr& service : sg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling passive checks for service '" << service->GetName() << "'";
+ << "Enabling passive checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_passive_checks", true);
}
for (const Service::Ptr& service : sg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling passive checks for service '" << service->GetName() << "'";
+ << "Disabling passive checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_passive_checks", false);
}
for (const Host::Ptr& host : hg->GetMembers()) {
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling passive checks for service '" << service->GetName() << "'";
+ << "Enabling passive checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_passive_checks", true);
}
for (const Host::Ptr& host : hg->GetMembers()) {
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling passive checks for service '" << service->GetName() << "'";
+ << "Disabling passive checks for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_passive_checks", false);
}
try {
Log(LogNotice, "compat")
- << "Executing external command: " << line;
+ << "Executing external command: " << line;
ExecuteFromFile(line, file_queue);
} catch (const std::exception& ex) {
Log(LogWarning, "ExternalCommandProcessor")
- << "External command failed: " << DiagnosticInformation(ex);
+ << "External command failed: " << DiagnosticInformation(ex);
}
}
triggeredBy = Downtime::GetDowntimeIDFromLegacyID(triggeredByLegacy);
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for service " << service->GetName();
+ << "Creating downtime for service " << service->GetName();
(void) Downtime::AddDowntime(service, arguments[7], arguments[8],
- Convert::ToDouble(arguments[2]), Convert::ToDouble(arguments[3]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[6]));
+ Convert::ToDouble(arguments[2]), Convert::ToDouble(arguments[3]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[6]));
}
void ExternalCommandProcessor::DelSvcDowntime(double, const std::vector<String>& arguments)
{
int id = Convert::ToLong(arguments[0]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing downtime ID " << arguments[0];
+ << "Removing downtime ID " << arguments[0];
String rid = Downtime::GetDowntimeIDFromLegacyID(id);
Downtime::RemoveDowntime(rid, true);
}
triggeredBy = Downtime::GetDowntimeIDFromLegacyID(triggeredByLegacy);
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for host " << host->GetName();
+ << "Creating downtime for host " << host->GetName();
(void) Downtime::AddDowntime(host, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
}
void ExternalCommandProcessor::ScheduleAndPropagateHostDowntime(double, const std::vector<String>& arguments)
triggeredBy = Downtime::GetDowntimeIDFromLegacyID(triggeredByLegacy);
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for host " << host->GetName();
+ << "Creating downtime for host " << host->GetName();
(void) Downtime::AddDowntime(host, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
/* Schedule downtime for all child hosts */
for (const Checkable::Ptr& child : host->GetAllChildren()) {
continue;
(void) Downtime::AddDowntime(child, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
}
}
triggeredBy = Downtime::GetDowntimeIDFromLegacyID(triggeredByLegacy);
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for host " << host->GetName();
+ << "Creating downtime for host " << host->GetName();
String parentDowntime = Downtime::AddDowntime(host, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
/* Schedule downtime for all child hosts and explicitely trigger them through the parent host's downtime */
for (const Checkable::Ptr& child : host->GetAllChildren()) {
continue;
(void) Downtime::AddDowntime(child, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), parentDowntime, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), parentDowntime, Convert::ToDouble(arguments[5]));
}
}
{
int id = Convert::ToLong(arguments[0]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing downtime ID " << arguments[0];
+ << "Removing downtime ID " << arguments[0];
String rid = Downtime::GetDowntimeIDFromLegacyID(id);
Downtime::RemoveDowntime(rid, true);
}
if (arguments.size() > 5)
Log(LogWarning, "ExternalCommandProcessor")
- << ("Ignoring additional parameters for host '" + arguments[0] + "' downtime deletion.");
+ << ("Ignoring additional parameters for host '" + arguments[0] + "' downtime deletion.");
for (const Downtime::Ptr& downtime : host->GetDowntimes()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing downtime '" << downtime->GetName() << "'.";
+ << "Removing downtime '" << downtime->GetName() << "'.";
Downtime::RemoveDowntime(downtime->GetName(), true);
}
continue;
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing downtime '" << downtime->GetName() << "'.";
+ << "Removing downtime '" << downtime->GetName() << "'.";
Downtime::RemoveDowntime(downtime->GetName(), true);
}
triggeredBy = Downtime::GetDowntimeIDFromLegacyID(triggeredByLegacy);
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for host " << host->GetName();
+ << "Creating downtime for host " << host->GetName();
(void) Downtime::AddDowntime(host, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for service " << service->GetName();
+ << "Creating downtime for service " << service->GetName();
(void) Downtime::AddDowntime(service, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
}
}
for (const Host::Ptr& host : hg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for host " << host->GetName();
+ << "Creating downtime for host " << host->GetName();
(void) Downtime::AddDowntime(host, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
}
}
for (const Service::Ptr& service : services) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for service " << service->GetName();
+ << "Creating downtime for service " << service->GetName();
(void) Downtime::AddDowntime(service, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
}
}
for (const Host::Ptr& host : hosts) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for host " << host->GetName();
+ << "Creating downtime for host " << host->GetName();
(void) Downtime::AddDowntime(host, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
}
}
for (const Service::Ptr& service : sg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating downtime for service " << service->GetName();
+ << "Creating downtime for service " << service->GetName();
(void) Downtime::AddDowntime(service, arguments[6], arguments[7],
- Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
- Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
+ Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
+ Convert::ToBool(is_fixed), triggeredBy, Convert::ToDouble(arguments[5]));
}
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Author and comment must not be empty"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating comment for host " << host->GetName();
+ << "Creating comment for host " << host->GetName();
(void) Comment::AddComment(host, CommentUser, arguments[2], arguments[3], false, 0);
}
{
int id = Convert::ToLong(arguments[0]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing comment ID " << arguments[0];
+ << "Removing comment ID " << arguments[0];
String rid = Comment::GetCommentIDFromLegacyID(id);
Comment::RemoveComment(rid);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Author and comment must not be empty"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Creating comment for service " << service->GetName();
+ << "Creating comment for service " << service->GetName();
(void) Comment::AddComment(service, CommentUser, arguments[3], arguments[4], false, 0);
}
{
int id = Convert::ToLong(arguments[0]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing comment ID " << arguments[0];
+ << "Removing comment ID " << arguments[0];
String rid = Comment::GetCommentIDFromLegacyID(id);
Comment::RemoveComment(rid);
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delete all host comments for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing all comments for host " << host->GetName();
+ << "Removing all comments for host " << host->GetName();
host->RemoveAllComments();
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delete all service comments for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Removing all comments for service " << service->GetName();
+ << "Removing all comments for service " << service->GetName();
service->RemoveAllComments();
}
int options = Convert::ToLong(arguments[1]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Sending custom notification for host " << host->GetName();
+ << "Sending custom notification for host " << host->GetName();
if (options & 2) {
host->SetForceNextNotification(true);
}
Checkable::OnNotificationsRequested(host, NotificationCustom,
- host->GetLastCheckResult(), arguments[2], arguments[3], nullptr);
+ host->GetLastCheckResult(), arguments[2], arguments[3], nullptr);
}
void ExternalCommandProcessor::SendCustomSvcNotification(double, const std::vector<String>& arguments)
int options = Convert::ToLong(arguments[2]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Sending custom notification for service " << service->GetName();
+ << "Sending custom notification for service " << service->GetName();
if (options & 2) {
service->SetForceNextNotification(true);
}
Service::OnNotificationsRequested(service, NotificationCustom,
- service->GetLastCheckResult(), arguments[3], arguments[4], nullptr);
+ service->GetLastCheckResult(), arguments[3], arguments[4], nullptr);
}
void ExternalCommandProcessor::DelayHostNotification(double, const std::vector<String>& arguments)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delay host notification for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Delaying notifications for host '" << host->GetName() << "'";
+ << "Delaying notifications for host '" << host->GetName() << "'";
for (const Notification::Ptr& notification : host->GetNotifications()) {
notification->SetNextNotification(Convert::ToDouble(arguments[1]));
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delay service notification for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Delaying notifications for service " << service->GetName();
+ << "Delaying notifications for service " << service->GetName();
for (const Notification::Ptr& notification : service->GetNotifications()) {
notification->SetNextNotification(Convert::ToDouble(arguments[2]));
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host notifications for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling notifications for host '" << arguments[0] << "'";
+ << "Enabling notifications for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_notifications", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host notifications for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling notifications for host '" << arguments[0] << "'";
+ << "Disabling notifications for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_notifications", false);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable service notifications for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling notifications for service '" << arguments[1] << "'";
+ << "Enabling notifications for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_notifications", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable service notifications for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling notifications for service '" << arguments[1] << "'";
+ << "Disabling notifications for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_notifications", false);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable notifications for all services for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling notifications for all services on host '" << arguments[0] << "'";
+ << "Enabling notifications for all services on host '" << arguments[0] << "'";
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling notifications for service '" << service->GetName() << "'";
+ << "Enabling notifications for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_notifications", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable notifications for all services for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling notifications for all services on host '" << arguments[0] << "'";
+ << "Disabling notifications for all services on host '" << arguments[0] << "'";
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling notifications for service '" << service->GetName() << "'";
+ << "Disabling notifications for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_notifications", false);
}
for (const Host::Ptr& host : hg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling active checks for host '" << host->GetName() << "'";
+ << "Disabling active checks for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_active_checks", false);
}
for (const Host::Ptr& host : hg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling passive checks for host '" << host->GetName() << "'";
+ << "Disabling passive checks for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_passive_checks", false);
}
Host::Ptr host = service->GetHost();
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling active checks for host '" << host->GetName() << "'";
+ << "Disabling active checks for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_active_checks", false);
}
Host::Ptr host = service->GetHost();
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling passive checks for host '" << host->GetName() << "'";
+ << "Disabling passive checks for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_passive_checks", false);
}
for (const Host::Ptr& host : hg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling active checks for host '" << host->GetName() << "'";
+ << "Enabling active checks for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_active_checks", true);
}
for (const Host::Ptr& host : hg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling passive checks for host '" << host->GetName() << "'";
+ << "Enabling passive checks for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_passive_checks", true);
}
Host::Ptr host = service->GetHost();
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling active checks for host '" << host->GetName() << "'";
+ << "Enabling active checks for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_active_checks", true);
}
Host::Ptr host = service->GetHost();
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling passive checks for host '" << host->GetName() << "'";
+ << "Enabling passive checks for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_passive_checks", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host flapping for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling flapping detection for host '" << arguments[0] << "'";
+ << "Enabling flapping detection for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_flapping", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host flapping for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling flapping detection for host '" << arguments[0] << "'";
+ << "Disabling flapping detection for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_flapping", false);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable service flapping for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling flapping detection for service '" << arguments[1] << "'";
+ << "Enabling flapping detection for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_flapping", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable service flapping for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling flapping detection for service '" << arguments[1] << "'";
+ << "Disabling flapping detection for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_flapping", false);
}
double interval = Convert::ToDouble(arguments[2]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Updating check interval for service '" << arguments[1] << "'";
+ << "Updating check interval for service '" << arguments[1] << "'";
service->ModifyAttribute("check_interval", interval * 60);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update check interval for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Updating check interval for host '" << arguments[0] << "'";
+ << "Updating check interval for host '" << arguments[0] << "'";
double interval = Convert::ToDouble(arguments[1]);
double interval = Convert::ToDouble(arguments[2]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Updating retry interval for service '" << arguments[1] << "'";
+ << "Updating retry interval for service '" << arguments[1] << "'";
service->ModifyAttribute("retry_interval", interval * 60);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update retry interval for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Updating retry interval for host '" << arguments[0] << "'";
+ << "Updating retry interval for host '" << arguments[0] << "'";
double interval = Convert::ToDouble(arguments[1]);
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable event handler for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling event handler for host '" << arguments[0] << "'";
+ << "Enabling event handler for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_event_handler", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable event handler for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling event handler for host '" << arguments[0] << "'";
+ << "Disabling event handler for host '" << arguments[0] << "'";
host->ModifyAttribute("enable_event_handler", false);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable event handler for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling event handler for service '" << arguments[1] << "'";
+ << "Enabling event handler for service '" << arguments[1] << "'";
service->ModifyAttribute("enable_event_handler", true);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable event handler for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling event handler for service '" << arguments[1] + "'";
+ << "Disabling event handler for service '" << arguments[1] + "'";
service->ModifyAttribute("enable_event_handler", false);
}
if (arguments[1].IsEmpty()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Unsetting event handler for host '" << arguments[0] << "'";
+ << "Unsetting event handler for host '" << arguments[0] << "'";
host->ModifyAttribute("event_command", "");
} else {
BOOST_THROW_EXCEPTION(std::invalid_argument("Event command '" + arguments[1] + "' does not exist."));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing event handler for host '" << arguments[0] << "' to '" << arguments[1] << "'";
+ << "Changing event handler for host '" << arguments[0] << "' to '" << arguments[1] << "'";
host->ModifyAttribute("event_command", command->GetName());
}
if (arguments[2].IsEmpty()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Unsetting event handler for service '" << arguments[1] << "'";
+ << "Unsetting event handler for service '" << arguments[1] << "'";
service->ModifyAttribute("event_command", "");
} else {
BOOST_THROW_EXCEPTION(std::invalid_argument("Event command '" + arguments[2] + "' does not exist."));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing event handler for service '" << arguments[1] << "' to '" << arguments[2] << "'";
+ << "Changing event handler for service '" << arguments[1] << "' to '" << arguments[2] << "'";
service->ModifyAttribute("event_command", command->GetName());
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Check command '" + arguments[1] + "' does not exist."));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing check command for host '" << arguments[0] << "' to '" << arguments[1] << "'";
+ << "Changing check command for host '" << arguments[0] << "' to '" << arguments[1] << "'";
host->ModifyAttribute("check_command", command->GetName());
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Check command '" + arguments[2] + "' does not exist."));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing check command for service '" << arguments[1] << "' to '" << arguments[2] << "'";
+ << "Changing check command for service '" << arguments[1] << "' to '" << arguments[2] << "'";
service->ModifyAttribute("check_command", command->GetName());
}
int attempts = Convert::ToLong(arguments[1]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing max check attempts for host '" << arguments[0] << "' to '" << arguments[1] << "'";
+ << "Changing max check attempts for host '" << arguments[0] << "' to '" << arguments[1] << "'";
host->ModifyAttribute("max_check_attempts", attempts);
}
int attempts = Convert::ToLong(arguments[2]);
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing max check attempts for service '" << arguments[1] << "' to '" << arguments[2] << "'";
+ << "Changing max check attempts for service '" << arguments[1] << "' to '" << arguments[2] << "'";
service->ModifyAttribute("max_check_attempts", attempts);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Time period '" + arguments[1] + "' does not exist."));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing check period for host '" << arguments[0] << "' to '" << arguments[1] << "'";
+ << "Changing check period for host '" << arguments[0] << "' to '" << arguments[1] << "'";
host->ModifyAttribute("check_period", tp->GetName());
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Time period '" + arguments[2] + "' does not exist."));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing check period for service '" << arguments[1] << "' to '" << arguments[2] << "'";
+ << "Changing check period for service '" << arguments[1] << "' to '" << arguments[2] << "'";
service->ModifyAttribute("check_period", tp->GetName());
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change custom var for non-existent host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing custom var '" << arguments[1] << "' for host '" << arguments[0] << "' to value '" << arguments[2] << "'";
+ << "Changing custom var '" << arguments[1] << "' for host '" << arguments[0] << "' to value '" << arguments[2] << "'";
host->ModifyAttribute("vars." + arguments[1], arguments[2]);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change custom var for non-existent service '" + arguments[1] + "' on host '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing custom var '" << arguments[2] << "' for service '" << arguments[1] << "' on host '"
- << arguments[0] << "' to value '" << arguments[3] << "'";
+ << "Changing custom var '" << arguments[2] << "' for service '" << arguments[1] << "' on host '"
+ << arguments[0] << "' to value '" << arguments[3] << "'";
service->ModifyAttribute("vars." + arguments[2], arguments[3]);
}
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change custom var for non-existent user '" + arguments[0] + "'"));
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing custom var '" << arguments[1] << "' for user '" << arguments[0] << "' to value '" << arguments[2] << "'";
+ << "Changing custom var '" << arguments[1] << "' for user '" << arguments[0] << "' to value '" << arguments[2] << "'";
user->ModifyAttribute("vars." + arguments[1], arguments[2]);
}
void ExternalCommandProcessor::ChangeCustomCommandVarInternal(const Command::Ptr& command, const String& name, const Value& value)
{
Log(LogNotice, "ExternalCommandProcessor")
- << "Changing custom var '" << name << "' for command '" << command->GetName() << "' to value '" << value << "'";
+ << "Changing custom var '" << name << "' for command '" << command->GetName() << "' to value '" << value << "'";
command->ModifyAttribute("vars." + name, value);
}
for (const Host::Ptr& host : hg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling notifications for host '" << host->GetName() << "'";
+ << "Enabling notifications for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_notifications", true);
}
for (const Host::Ptr& host : hg->GetMembers()) {
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling notifications for service '" << service->GetName() << "'";
+ << "Enabling notifications for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_notifications", true);
}
for (const Host::Ptr& host : hg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling notifications for host '" << host->GetName() << "'";
+ << "Disabling notifications for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_notifications", false);
}
for (const Host::Ptr& host : hg->GetMembers()) {
for (const Service::Ptr& service : host->GetServices()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling notifications for service '" << service->GetName() << "'";
+ << "Disabling notifications for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_notifications", false);
}
Host::Ptr host = service->GetHost();
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling notifications for host '" << host->GetName() << "'";
+ << "Enabling notifications for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_notifications", true);
}
for (const Service::Ptr& service : sg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Enabling notifications for service '" << service->GetName() << "'";
+ << "Enabling notifications for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_notifications", true);
}
Host::Ptr host = service->GetHost();
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling notifications for host '" << host->GetName() << "'";
+ << "Disabling notifications for host '" << host->GetName() << "'";
host->ModifyAttribute("enable_notifications", false);
}
for (const Service::Ptr& service : sg->GetMembers()) {
Log(LogNotice, "ExternalCommandProcessor")
- << "Disabling notifications for service '" << service->GetName() << "'";
+ << "Disabling notifications for service '" << service->GetName() << "'";
service->ModifyAttribute("enable_notifications", false);
}
*result = Utility::GetTime() - GetLastStateChange();
return true;
} else if (macro == "num_services" || macro == "num_services_ok" || macro == "num_services_warning"
- || macro == "num_services_unknown" || macro == "num_services_critical") {
+ || macro == "num_services_unknown" || macro == "num_services_critical") {
int filter = -1;
int count = 0;
return false;
Log(LogDebug, "HostGroup")
- << "Assigning membership for group '" << group_name << "' to host '" << host->GetName() << "'";
+ << "Assigning membership for group '" << group_name << "' to host '" << host->GetName() << "'";
Array::Ptr groups = host->GetGroups();
groups->Add(group_name);
if (add && rstack > 20) {
Log(LogWarning, "HostGroup")
- << "Too many nested groups for group '" << GetName() << "': Host '"
- << host->GetName() << "' membership assignment failed.";
+ << "Too many nested groups for group '" << GetName() << "': Host '"
+ << host->GetName() << "' membership assignment failed.";
return false;
}
if (rename(tempFilename.CStr(), path.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempFilename));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempFilename));
}
}
ParseTimeRange(daydef, &begin, &end, &stride, reference);
Log(LogDebug, "LegacyTimePeriod")
- << "ParseTimeRange: '" << daydef << "' => " << mktime(&begin)
- << " -> " << mktime(&end) << ", stride: " << stride;
+ << "ParseTimeRange: '" << daydef << "' => " << mktime(&begin)
+ << " -> " << mktime(&end) << ", stride: " << stride;
return IsInTimeRange(&begin, &end, stride, reference);
}
end->tm_hour = Convert::ToLong(hd2[0]);
if (begin->tm_hour * 3600 + begin->tm_min * 60 + begin->tm_sec >=
- end->tm_hour * 3600 + end->tm_min * 60 + end->tm_sec)
+ end->tm_hour * 3600 + end->tm_min * 60 + end->tm_sec)
BOOST_THROW_EXCEPTION(std::invalid_argument("Time period segment ends before it begins"));
}
#ifdef I2_DEBUG
Log(LogDebug, "LegacyTimePeriod")
- << "Checking reference time " << refts;
+ << "Checking reference time " << refts;
#endif /* I2_DEBUG */
ObjectLock olock(ranges);
if (!IsInDayDefinition(kv.first, &reference)) {
#ifdef I2_DEBUG
Log(LogDebug, "LegacyTimePeriod")
- << "Not in day definition '" << kv.first << "'.";
+ << "Not in day definition '" << kv.first << "'.";
#endif /* I2_DEBUG */
continue;
}
#ifdef I2_DEBUG
Log(LogDebug, "LegacyTimePeriod")
- << "In day definition '" << kv.first << "'.";
+ << "In day definition '" << kv.first << "'.";
#endif /* I2_DEBUG */
ProcessTimeRanges(kv.second, &reference, segments);
}
Log(LogDebug, "LegacyTimePeriod")
- << "Legacy timeperiod update returned " << segments->GetLength() << " segments.";
+ << "Legacy timeperiod update returned " << segments->GetLength() << " segments.";
return segments;
}
using namespace icinga;
Value MacroProcessor::ResolveMacros(const Value& str, const ResolverList& resolvers,
- const CheckResult::Ptr& cr, String *missingMacro,
- const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
- bool useResolvedMacros, int recursionLevel)
+ const CheckResult::Ptr& cr, String *missingMacro,
+ const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
+ bool useResolvedMacros, int recursionLevel)
{
Value result;
if (str.IsScalar()) {
result = InternalResolveMacros(str, resolvers, cr, missingMacro, escapeFn,
- resolvedMacros, useResolvedMacros, recursionLevel + 1);
+ resolvedMacros, useResolvedMacros, recursionLevel + 1);
} else if (str.IsObjectType<Array>()) {
Array::Ptr resultArr = new Array();
Array::Ptr arr = str;
for (const Value& arg : arr) {
/* Note: don't escape macros here. */
Value value = InternalResolveMacros(arg, resolvers, cr, missingMacro,
- EscapeCallback(), resolvedMacros, useResolvedMacros, recursionLevel + 1);
+ EscapeCallback(), resolvedMacros, useResolvedMacros, recursionLevel + 1);
if (value.IsObjectType<Array>())
resultArr->Add(Utility::Join(value, ';'));
for (const Dictionary::Pair& kv : dict) {
/* Note: don't escape macros here. */
resultDict->Set(kv.first, InternalResolveMacros(kv.second, resolvers, cr, missingMacro,
- EscapeCallback(), resolvedMacros, useResolvedMacros, recursionLevel + 1));
+ EscapeCallback(), resolvedMacros, useResolvedMacros, recursionLevel + 1));
}
result = resultDict;
}
bool MacroProcessor::ResolveMacro(const String& macro, const ResolverList& resolvers,
- const CheckResult::Ptr& cr, Value *result, bool *recursive_macro)
+ const CheckResult::Ptr& cr, Value *result, bool *recursive_macro)
{
CONTEXT("Resolving macro '" + macro + "'");
if (valid) {
if (tokens[0] == "vars" ||
- tokens[0] == "action_url" ||
- tokens[0] == "notes_url" ||
- tokens[0] == "notes")
+ tokens[0] == "action_url" ||
+ tokens[0] == "notes_url" ||
+ tokens[0] == "notes")
*recursive_macro = true;
*result = ref;
}
Value MacroProcessor::EvaluateFunction(const Function::Ptr& func, const ResolverList& resolvers,
- const CheckResult::Ptr& cr, const MacroProcessor::EscapeCallback& escapeFn,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros, int recursionLevel)
+ const CheckResult::Ptr& cr, const MacroProcessor::EscapeCallback& escapeFn,
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros, int recursionLevel)
{
Dictionary::Ptr resolvers_this = new Dictionary();
String missingMacro;
return MacroProcessor::InternalResolveMacros(args[0], resolvers, cr, &missingMacro, MacroProcessor::EscapeCallback(),
- resolvedMacros, useResolvedMacros, recursionLevel);
+ resolvedMacros, useResolvedMacros, recursionLevel);
};
resolvers_this->Set("macro", new Function("macro (temporary)", internalResolveMacrosShim, { "str" }));
BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments for function"));
return MacroProcessor::ResolveArguments(args[0], args[1], resolvers, cr,
- resolvedMacros, useResolvedMacros, recursionLevel + 1);
+ resolvedMacros, useResolvedMacros, recursionLevel + 1);
};
resolvers_this->Set("resolve_arguments", new Function("resolve_arguments (temporary)", internalResolveArgumentsShim, { "command", "args" }));
}
Value MacroProcessor::InternalResolveMacros(const String& str, const ResolverList& resolvers,
- const CheckResult::Ptr& cr, String *missingMacro,
- const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
- bool useResolvedMacros, int recursionLevel)
+ const CheckResult::Ptr& cr, String *missingMacro,
+ const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
+ bool useResolvedMacros, int recursionLevel)
{
CONTEXT("Resolving macros for string '" + str + "'");
if (resolved_macro.IsObjectType<Function>()) {
resolved_macro = EvaluateFunction(resolved_macro, resolvers, cr, escapeFn,
- resolvedMacros, useResolvedMacros, recursionLevel + 1);
+ resolvedMacros, useResolvedMacros, recursionLevel + 1);
}
if (!found) {
if (!missingMacro)
Log(LogWarning, "MacroProcessor")
- << "Macro '" << name << "' is not defined.";
+ << "Macro '" << name << "' is not defined.";
else
*missingMacro = name;
}
}
void MacroProcessor::AddArgumentHelper(const Array::Ptr& args, const String& key, const String& value,
- bool add_key, bool add_value)
+ bool add_key, bool add_value)
{
if (add_key)
args->Add(key);
};
Value MacroProcessor::ResolveArguments(const Value& command, const Dictionary::Ptr& arguments,
- const MacroProcessor::ResolverList& resolvers, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros, int recursionLevel)
+ const MacroProcessor::ResolverList& resolvers, const CheckResult::Ptr& cr,
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros, int recursionLevel)
{
Value resolvedCommand;
if (!arguments || command.IsObjectType<Array>() || command.IsObjectType<Function>())
resolvedCommand = MacroProcessor::ResolveMacros(command, resolvers, cr, nullptr,
- EscapeMacroShellArg, resolvedMacros, useResolvedMacros, recursionLevel + 1);
+ EscapeMacroShellArg, resolvedMacros, useResolvedMacros, recursionLevel + 1);
else {
Array::Ptr arr = new Array();
arr->Add(command);
if (!set_if.IsEmpty()) {
String missingMacro;
Value set_if_resolved = MacroProcessor::ResolveMacros(set_if, resolvers,
- cr, &missingMacro, MacroProcessor::EscapeCallback(), resolvedMacros,
- useResolvedMacros, recursionLevel + 1);
+ cr, &missingMacro, MacroProcessor::EscapeCallback(), resolvedMacros,
+ useResolvedMacros, recursionLevel + 1);
if (!missingMacro.IsEmpty())
continue;
} catch (const std::exception& ex) {
/* tried to convert a string */
Log(LogWarning, "PluginUtility")
- << "Error evaluating set_if value '" << set_if_resolved
- << "' used in argument '" << arg.Key << "': " << ex.what();
+ << "Error evaluating set_if value '" << set_if_resolved
+ << "' used in argument '" << arg.Key << "': " << ex.what();
continue;
}
}
String missingMacro;
arg.AValue = MacroProcessor::ResolveMacros(argval, resolvers,
- cr, &missingMacro, MacroProcessor::EscapeCallback(), resolvedMacros,
- useResolvedMacros, recursionLevel + 1);
+ cr, &missingMacro, MacroProcessor::EscapeCallback(), resolvedMacros,
+ useResolvedMacros, recursionLevel + 1);
if (!missingMacro.IsEmpty()) {
if (required) {
BOOST_THROW_EXCEPTION(ScriptError("Non-optional macro '" + missingMacro + "' used in argument '" +
- arg.Key + "' is missing."));
+ arg.Key + "' is missing."));
}
continue;
if (arg.AValue.IsObjectType<Dictionary>()) {
Log(LogWarning, "PluginUtility")
- << "Tried to use dictionary in argument '" << arg.Key << "'.";
+ << "Tried to use dictionary in argument '" << arg.Key << "'.";
continue;
} else if (arg.AValue.IsObjectType<Array>()) {
bool first = true;
typedef std::vector<ResolverSpec> ResolverList;
static Value ResolveMacros(const Value& str, const ResolverList& resolvers,
- const CheckResult::Ptr& cr = nullptr, String *missingMacro = nullptr,
- const EscapeCallback& escapeFn = EscapeCallback(),
- const Dictionary::Ptr& resolvedMacros = nullptr,
- bool useResolvedMacros = false, int recursionLevel = 0);
+ const CheckResult::Ptr& cr = nullptr, String *missingMacro = nullptr,
+ const EscapeCallback& escapeFn = EscapeCallback(),
+ const Dictionary::Ptr& resolvedMacros = nullptr,
+ bool useResolvedMacros = false, int recursionLevel = 0);
static Value ResolveArguments(const Value& command, const Dictionary::Ptr& arguments,
- const MacroProcessor::ResolverList& resolvers, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros, int recursionLevel = 0);
+ const MacroProcessor::ResolverList& resolvers, const CheckResult::Ptr& cr,
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros, int recursionLevel = 0);
static bool ValidateMacroString(const String& macro);
static void ValidateCustomVars(const ConfigObject::Ptr& object, const Dictionary::Ptr& value);
static bool ResolveMacro(const String& macro, const ResolverList& resolvers,
const CheckResult::Ptr& cr, Value *result, bool *recursive_macro);
static Value InternalResolveMacros(const String& str,
- const ResolverList& resolvers, const CheckResult::Ptr& cr,
- String *missingMacro, const EscapeCallback& escapeFn,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros,
- int recursionLevel = 0);
+ const ResolverList& resolvers, const CheckResult::Ptr& cr,
+ String *missingMacro, const EscapeCallback& escapeFn,
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros,
+ int recursionLevel = 0);
static Value EvaluateFunction(const Function::Ptr& func, const ResolverList& resolvers,
- const CheckResult::Ptr& cr, const MacroProcessor::EscapeCallback& escapeFn,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros, int recursionLevel);
+ const CheckResult::Ptr& cr, const MacroProcessor::EscapeCallback& escapeFn,
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros, int recursionLevel);
static void AddArgumentHelper(const Array::Ptr& args, const String& key, const String& value,
- bool add_key, bool add_value);
+ bool add_key, bool add_value);
static Value EscapeMacroShellArg(const Value& value);
};
#ifdef _DEBUG
Log(LogDebug, "Notification")
- << "Applying notification '" << name << "' to object '" << checkable->GetName() << "' for rule " << di;
+ << "Applying notification '" << name << "' to object '" << checkable->GetName() << "' for rule " << di;
#endif /* _DEBUG */
ConfigItemBuilder::Ptr builder = new ConfigItemBuilder(di);
void Notification::BeginExecuteNotification(NotificationType type, const CheckResult::Ptr& cr, bool force, bool reminder, const String& author, const String& text)
{
Log(LogNotice, "Notification")
- << "Attempting to send " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName() << "'.";
+ << "Attempting to send " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName() << "'.";
Checkable::Ptr checkable = GetCheckable();
if (tp && !tp->IsInside(Utility::GetTime())) {
Log(LogNotice, "Notification")
- << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName()
- << "': not in timeperiod '" << tp->GetName() << "'";
+ << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName()
+ << "': not in timeperiod '" << tp->GetName() << "'";
return;
}
if (timesBegin != Empty && timesBegin >= 0 && now < checkable->GetLastHardStateChange() + timesBegin) {
Log(LogNotice, "Notification")
- << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName()
- << "': before specified begin time (" << Utility::FormatDuration(timesBegin) << ")";
+ << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName()
+ << "': before specified begin time (" << Utility::FormatDuration(timesBegin) << ")";
/* we need to adjust the next notification time
* to now + begin delaying the first notification
if (timesEnd != Empty && timesEnd >= 0 && now > checkable->GetLastHardStateChange() + timesEnd) {
Log(LogNotice, "Notification")
- << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName()
- << "': after specified end time (" << Utility::FormatDuration(timesEnd) << ")";
+ << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName()
+ << "': after specified end time (" << Utility::FormatDuration(timesEnd) << ")";
return;
}
}
unsigned long ftype = type;
Log(LogDebug, "Notification")
- << "Type '" << NotificationTypeToStringInternal(type)
- << "', TypeFilter: " << NotificationFilterToString(GetTypeFilter(), GetTypeFilterMap())
- << " (FType=" << ftype << ", TypeFilter=" << GetTypeFilter() << ")";
+ << "Type '" << NotificationTypeToStringInternal(type)
+ << "', TypeFilter: " << NotificationFilterToString(GetTypeFilter(), GetTypeFilterMap())
+ << " (FType=" << ftype << ", TypeFilter=" << GetTypeFilter() << ")";
if (!(ftype & GetTypeFilter())) {
Log(LogNotice, "Notification")
- << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName() << "': type '"
- << NotificationTypeToStringInternal(type) << "' does not match type filter: "
- << NotificationFilterToString(GetTypeFilter(), GetTypeFilterMap()) << ".";
+ << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName() << "': type '"
+ << NotificationTypeToStringInternal(type) << "' does not match type filter: "
+ << NotificationFilterToString(GetTypeFilter(), GetTypeFilterMap()) << ".";
return;
}
}
Log(LogDebug, "Notification")
- << "State '" << stateStr << "', StateFilter: " << NotificationFilterToString(GetStateFilter(), GetStateFilterMap())
- << " (FState=" << fstate << ", StateFilter=" << GetStateFilter() << ")";
+ << "State '" << stateStr << "', StateFilter: " << NotificationFilterToString(GetStateFilter(), GetStateFilterMap())
+ << " (FState=" << fstate << ", StateFilter=" << GetStateFilter() << ")";
if (!(fstate & GetStateFilter())) {
Log(LogNotice, "Notification")
- << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName() << "': state '" << stateStr
- << "' does not match state filter: " << NotificationFilterToString(GetStateFilter(), GetStateFilterMap()) << ".";
+ << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '" << GetName() << "': state '" << stateStr
+ << "' does not match state filter: " << NotificationFilterToString(GetStateFilter(), GetStateFilterMap()) << ".";
return;
}
}
} else {
Log(LogNotice, "Notification")
- << "Not checking " << (reminder ? "reminder " : " ") << "notification filters for notification object '" << GetName() << "': Notification was forced.";
+ << "Not checking " << (reminder ? "reminder " : " ") << "notification filters for notification object '" << GetName() << "': Notification was forced.";
}
{
if (!user->GetEnableNotifications()) {
Log(LogNotice, "Notification")
- << "Disabled notifications for user '" << userName << "'. Not sending notification.";
+ << "Disabled notifications for user '" << userName << "'. Not sending notification.";
continue;
}
if (!CheckNotificationUserFilters(type, user, force, reminder)) {
Log(LogNotice, "Notification")
- << "Notification filters for user '" << userName << "' not matched. Not sending notification.";
+ << "Notification filters for user '" << userName << "' not matched. Not sending notification.";
continue;
}
if (type == NotificationRecovery) {
if (!notifiedProblemUsers->Contains(userName)) {
Log(LogNotice, "Notification")
- << "We did not notify user '" << userName << "' for a problem before. Not sending recovery notification.";
+ << "We did not notify user '" << userName << "' for a problem before. Not sending recovery notification.";
continue;
}
}
Log(LogInformation, "Notification")
- << "Sending " << (reminder ? "reminder " : "") << "'" << NotificationTypeToStringInternal(type) << "' notification '"
- << GetName() << "' for user '" << userName << "'";
+ << "Sending " << (reminder ? "reminder " : "") << "'" << NotificationTypeToStringInternal(type) << "' notification '"
+ << GetName() << "' for user '" << userName << "'";
Utility::QueueAsyncCallback(std::bind(&Notification::ExecuteNotificationHelper, this, type, user, cr, force, author, text));
if (tp && !tp->IsInside(Utility::GetTime())) {
Log(LogNotice, "Notification")
- << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '"
- << GetName() << " and user '" << user->GetName()
- << "': user period not in timeperiod '" << tp->GetName() << "'";
+ << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '"
+ << GetName() << " and user '" << user->GetName()
+ << "': user period not in timeperiod '" << tp->GetName() << "'";
return false;
}
unsigned long ftype = type;
Log(LogDebug, "Notification")
- << "User notification, Type '" << NotificationTypeToStringInternal(type)
- << "', TypeFilter: " << NotificationFilterToString(user->GetTypeFilter(), GetTypeFilterMap())
- << " (FType=" << ftype << ", TypeFilter=" << GetTypeFilter() << ")";
+ << "User notification, Type '" << NotificationTypeToStringInternal(type)
+ << "', TypeFilter: " << NotificationFilterToString(user->GetTypeFilter(), GetTypeFilterMap())
+ << " (FType=" << ftype << ", TypeFilter=" << GetTypeFilter() << ")";
if (!(ftype & user->GetTypeFilter())) {
Log(LogNotice, "Notification")
- << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '"
- << GetName() << " and user '" << user->GetName() << "': type '"
- << NotificationTypeToStringInternal(type) << "' does not match type filter: "
- << NotificationFilterToString(user->GetTypeFilter(), GetTypeFilterMap()) << ".";
+ << "Not sending " << (reminder ? "reminder " : " ") << "notifications for notification object '"
+ << GetName() << " and user '" << user->GetName() << "': type '"
+ << NotificationTypeToStringInternal(type) << "' does not match type filter: "
+ << NotificationFilterToString(user->GetTypeFilter(), GetTypeFilterMap()) << ".";
return false;
}
}
Log(LogDebug, "Notification")
- << "User notification, State '" << stateStr << "', StateFilter: "
- << NotificationFilterToString(user->GetStateFilter(), GetStateFilterMap())
- << " (FState=" << fstate << ", StateFilter=" << user->GetStateFilter() << ")";
+ << "User notification, State '" << stateStr << "', StateFilter: "
+ << NotificationFilterToString(user->GetStateFilter(), GetStateFilterMap())
+ << " (FState=" << fstate << ", StateFilter=" << user->GetStateFilter() << ")";
if (!(fstate & user->GetStateFilter())) {
Log(LogNotice, "Notification")
- << "Not " << (reminder ? "reminder " : " ") << "sending notifications for notification object '"
- << GetName() << " and user '" << user->GetName() << "': state '" << stateStr
- << "' does not match state filter: " << NotificationFilterToString(user->GetStateFilter(), GetStateFilterMap()) << ".";
+ << "Not " << (reminder ? "reminder " : " ") << "sending notifications for notification object '"
+ << GetName() << " and user '" << user->GetName() << "': state '" << stateStr
+ << "' does not match state filter: " << NotificationFilterToString(user->GetStateFilter(), GetStateFilterMap()) << ".";
return false;
}
}
} else {
Log(LogNotice, "Notification")
- << "Not checking " << (reminder ? "reminder " : " ") << "notification filters for notification object '"
- << GetName() << "' and user '" << user->GetName() << "': Notification was forced.";
+ << "Not checking " << (reminder ? "reminder " : " ") << "notification filters for notification object '"
+ << GetName() << "' and user '" << user->GetName() << "': Notification was forced.";
}
return true;
if (!command) {
Log(LogDebug, "Notification")
- << "No command found for notification '" << GetName() << "'. Skipping execution.";
+ << "No command found for notification '" << GetName() << "'. Skipping execution.";
return;
}
Service::OnNotificationSentToUser(this, GetCheckable(), user, type, cr, author, text, command->GetName(), nullptr);
Log(LogInformation, "Notification")
- << "Completed sending '" << NotificationTypeToStringInternal(type)
- << "' notification '" << GetName()
- << "' for checkable '" << GetCheckable()->GetName()
- << "' and user '" << user->GetName() << "'.";
+ << "Completed sending '" << NotificationTypeToStringInternal(type)
+ << "' notification '" << GetName()
+ << "' for checkable '" << GetCheckable()->GetName()
+ << "' and user '" << user->GetName() << "'.";
} catch (const std::exception& ex) {
Log(LogWarning, "Notification")
- << "Exception occured during notification for checkable '"
- << GetCheckable()->GetName() << "': " << DiagnosticInformation(ex);
+ << "Exception occured during notification for checkable '"
+ << GetCheckable()->GetName() << "': " << DiagnosticInformation(ex);
}
}
int filter = FilterArrayToInt(value, GetTypeFilterMap(), 0);
if (filter == -1 || (filter & ~(NotificationDowntimeStart | NotificationDowntimeEnd | NotificationDowntimeRemoved |
- NotificationCustom | NotificationAcknowledgement | NotificationProblem | NotificationRecovery |
- NotificationFlappingStart | NotificationFlappingEnd)) != 0)
+ NotificationCustom | NotificationAcknowledgement | NotificationProblem | NotificationRecovery |
+ NotificationFlappingStart | NotificationFlappingEnd)) != 0)
BOOST_THROW_EXCEPTION(ValidationError(this, { "types" }, "Type filter is invalid."));
}
void ResetNotificationNumber(void);
void BeginExecuteNotification(NotificationType type, const CheckResult::Ptr& cr, bool force,
- bool reminder = false, const String& author = "", const String& text = "");
+ bool reminder = false, const String& author = "", const String& text = "");
Endpoint::Ptr GetCommandEndpoint(void) const;
REGISTER_TYPE(NotificationCommand);
Dictionary::Ptr NotificationCommand::Execute(const Notification::Ptr& notification,
- const User::Ptr& user, const CheckResult::Ptr& cr, const NotificationType& type,
- const String& author, const String& comment, const Dictionary::Ptr& resolvedMacros,
- bool useResolvedMacros)
+ const User::Ptr& user, const CheckResult::Ptr& cr, const NotificationType& type,
+ const String& author, const String& comment, const Dictionary::Ptr& resolvedMacros,
+ bool useResolvedMacros)
{
return GetExecute()->Invoke({
- notification,
- user,
- cr,
- type,
- author,
- comment,
- resolvedMacros,
- useResolvedMacros,
+ notification,
+ user,
+ cr,
+ type,
+ author,
+ comment,
+ resolvedMacros,
+ useResolvedMacros,
});
}
virtual Dictionary::Ptr Execute(const intrusive_ptr<Notification>& notification,
const User::Ptr& user, const CheckResult::Ptr& cr, const NotificationType& type,
- const String& author, const String& comment,
- const Dictionary::Ptr& resolvedMacros = nullptr,
- bool useResolvedMacros = false);
+ const String& author, const String& comment,
+ const Dictionary::Ptr& resolvedMacros = nullptr,
+ bool useResolvedMacros = false);
};
}
using namespace icinga;
void PluginUtility::ExecuteCommand(const Command::Ptr& commandObj, const Checkable::Ptr& checkable,
- const CheckResult::Ptr& cr, const MacroProcessor::ResolverList& macroResolvers,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros,
- const std::function<void(const Value& commandLine, const ProcessResult&)>& callback)
+ const CheckResult::Ptr& cr, const MacroProcessor::ResolverList& macroResolvers,
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros,
+ const std::function<void(const Value& commandLine, const ProcessResult&)>& callback)
{
Value raw_command = commandObj->GetCommandLine();
Dictionary::Ptr raw_arguments = commandObj->GetArguments();
try {
command = MacroProcessor::ResolveArguments(raw_command, raw_arguments,
- macroResolvers, cr, resolvedMacros, useResolvedMacros);
+ macroResolvers, cr, resolvedMacros, useResolvedMacros);
} catch (const std::exception& ex) {
String message = DiagnosticInformation(ex);
String name = kv.second;
Value value = MacroProcessor::ResolveMacros(name, macroResolvers, cr,
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros,
- useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros,
+ useResolvedMacros);
if (value.IsObjectType<Array>())
value = Utility::Join(value, ';');
{
public:
static void ExecuteCommand(const Command::Ptr& commandObj, const Checkable::Ptr& checkable,
- const CheckResult::Ptr& cr, const MacroProcessor::ResolverList& macroResolvers,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros,
- const std::function<void(const Value& commandLine, const ProcessResult&)>& callback = std::function<void(const Value& commandLine, const ProcessResult&)>());
+ const CheckResult::Ptr& cr, const MacroProcessor::ResolverList& macroResolvers,
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros,
+ const std::function<void(const Value& commandLine, const ProcessResult&)>& callback = std::function<void(const Value& commandLine, const ProcessResult&)>());
static ServiceState ExitStatusToState(int exitStatus);
static std::pair<String, String> ParseCheckOutput(const String& output);
tm reference = Utility::LocalTime(refts);
Log(LogDebug, "ScheduledDowntime")
- << "Finding next scheduled downtime segment for time " << refts;
+ << "Finding next scheduled downtime segment for time " << refts;
Dictionary::Ptr ranges = GetRanges();
ObjectLock olock(ranges);
for (const Dictionary::Pair& kv : ranges) {
Log(LogDebug, "ScheduledDowntime")
- << "Evaluating segment: " << kv.first << ": " << kv.second << " at ";
+ << "Evaluating segment: " << kv.first << ": " << kv.second << " at ";
Dictionary::Ptr segment = LegacyTimePeriod::FindNextSegment(kv.first, kv.second, &reference);
continue;
Log(LogDebug, "ScheduledDowntime")
- << "Considering segment: " << Utility::FormatDateTime("%c", segment->Get("begin")) << " -> " << Utility::FormatDateTime("%c", segment->Get("end"));
+ << "Considering segment: " << Utility::FormatDateTime("%c", segment->Get("begin")) << " -> " << Utility::FormatDateTime("%c", segment->Get("end"));
double begin = segment->Get("begin");
{
for (const Downtime::Ptr& downtime : GetCheckable()->GetDowntimes()) {
if (downtime->GetScheduledBy() != GetName() ||
- downtime->GetStartTime() < Utility::GetTime())
+ downtime->GetStartTime() < Utility::GetTime())
continue;
/* We've found a downtime that is owned by us and that hasn't started yet - we're done. */
}
Downtime::AddDowntime(GetCheckable(), GetAuthor(), GetComment(),
- segment.first, segment.second,
- GetFixed(), String(), GetDuration(), GetName(), GetName());
+ segment.first, segment.second,
+ GetFixed(), String(), GetDuration(), GetName(), GetName());
}
void ScheduledDowntime::ValidateRanges(const Dictionary::Ptr& value, const ValidationUtils& utils)
#ifdef _DEBUG
Log(LogDebug, "Service")
- << "Applying service '" << name << "' to host '" << host->GetName() << "' for rule " << di;
+ << "Applying service '" << name << "' to host '" << host->GetName() << "' for rule " << di;
#endif /* _DEBUG */
ConfigItemBuilder::Ptr builder = new ConfigItemBuilder(di);
return false;
Log(LogDebug, "ServiceGroup")
- << "Assigning membership for group '" << group_name << "' to service '" << service->GetName() << "'";
+ << "Assigning membership for group '" << group_name << "' to service '" << service->GetName() << "'";
Array::Ptr groups = service->GetGroups();
groups->Add(group_name);
if (add && rstack > 20) {
Log(LogWarning, "ServiceGroup")
- << "Too many nested groups for group '" << GetName() << "': Service '"
- << service->GetName() << "' membership assignment failed.";
+ << "Too many nested groups for group '" << GetName() << "': Service '"
+ << service->GetName() << "' membership assignment failed.";
return false;
}
ASSERT(OwnsLock());
Log(LogDebug, "TimePeriod")
- << "Adding segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '"
- << Utility::FormatDateTime("%c", end) << "' to TimePeriod '" << GetName() << "'";
+ << "Adding segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '"
+ << Utility::FormatDateTime("%c", end) << "' to TimePeriod '" << GetName() << "'";
if (GetValidBegin().IsEmpty() || begin < GetValidBegin())
SetValidBegin(begin);
ASSERT(OwnsLock());
Log(LogDebug, "TimePeriod")
- << "Removing segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '"
- << Utility::FormatDateTime("%c", end) << "' from TimePeriod '" << GetName() << "'";
+ << "Removing segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '"
+ << Utility::FormatDateTime("%c", end) << "' from TimePeriod '" << GetName() << "'";
if (GetValidBegin().IsEmpty() || begin < GetValidBegin())
SetValidBegin(begin);
ASSERT(OwnsLock());
Log(LogDebug, "TimePeriod")
- << "Purging segments older than '" << Utility::FormatDateTime("%c", end)
- << "' from TimePeriod '" << GetName() << "'";
+ << "Purging segments older than '" << Utility::FormatDateTime("%c", end)
+ << "' from TimePeriod '" << GetName() << "'";
if (GetValidBegin().IsEmpty() || end < GetValidBegin())
return;
void TimePeriod::Merge(const TimePeriod::Ptr& timeperiod, bool include)
{
Log(LogDebug, "TimePeriod")
- << "Merge TimePeriod '" << GetName() << "' with '" << timeperiod->GetName() << "' "
- << "Method: " << (include ? "include" : "exclude");
+ << "Merge TimePeriod '" << GetName() << "' with '" << timeperiod->GetName() << "' "
+ << "Method: " << (include ? "include" : "exclude");
Array::Ptr segments = timeperiod->GetSegments();
Array::Ptr segments = GetSegments();
Log(LogDebug, "TimePeriod")
- << "Dumping TimePeriod '" << GetName() << "'";
+ << "Dumping TimePeriod '" << GetName() << "'";
Log(LogDebug, "TimePeriod")
- << "Valid from '" << Utility::FormatDateTime("%c", GetValidBegin())
- << "' until '" << Utility::FormatDateTime("%c", GetValidEnd());
+ << "Valid from '" << Utility::FormatDateTime("%c", GetValidBegin())
+ << "' until '" << Utility::FormatDateTime("%c", GetValidEnd());
if (segments) {
ObjectLock dlock(segments);
for (const Dictionary::Ptr& segment : segments) {
Log(LogDebug, "TimePeriod")
- << "Segment: " << Utility::FormatDateTime("%c", segment->Get("begin")) << " <-> "
- << Utility::FormatDateTime("%c", segment->Get("end"));
+ << "Segment: " << Utility::FormatDateTime("%c", segment->Get("begin")) << " <-> "
+ << Utility::FormatDateTime("%c", segment->Get("end"));
}
}
int filter = FilterArrayToInt(value, Notification::GetTypeFilterMap(), 0);
if (filter == -1 || (filter & ~(NotificationDowntimeStart | NotificationDowntimeEnd | NotificationDowntimeRemoved |
- NotificationCustom | NotificationAcknowledgement | NotificationProblem | NotificationRecovery |
- NotificationFlappingStart | NotificationFlappingEnd)) != 0)
+ NotificationCustom | NotificationAcknowledgement | NotificationProblem | NotificationRecovery |
+ NotificationFlappingStart | NotificationFlappingEnd)) != 0)
BOOST_THROW_EXCEPTION(ValidationError(this, { "types" }, "Type filter is invalid."));
}
return false;
Log(LogDebug, "UserGroup")
- << "Assigning membership for group '" << group_name << "' to user '" << user->GetName() << "'";
+ << "Assigning membership for group '" << group_name << "' to user '" << user->GetName() << "'";
Array::Ptr groups = user->GetGroups();
groups->Add(group_name);
if (add && rstack > 20) {
Log(LogWarning, "UserGroup")
- << "Too many nested groups for group '" << GetName() << "': User '"
- << user->GetName() << "' membership assignment failed.";
+ << "Too many nested groups for group '" << GetName() << "': User '"
+ << user->GetName() << "' membership assignment failed.";
return false;
}
ret = boost::regex_search(operand.GetData(), what, expr);
} catch (boost::exception&) {
Log(LogWarning, "AttributeFilter")
- << "Regex '" << m_Operand << " " << m_Operator << " " << value << "' error.";
+ << "Regex '" << m_Operand << " " << m_Operator << " " << value << "' error.";
ret = false;
}
ret = boost::iequals(operand, m_Operand.GetData());
} catch (boost::exception&) {
Log(LogWarning, "AttributeFilter")
- << "Case-insensitive equality '" << m_Operand << " " << m_Operator << " " << value << "' error.";
+ << "Case-insensitive equality '" << m_Operand << " " << m_Operator << " " << value << "' error.";
ret = false;
}
ret = boost::regex_search(operand.GetData(), what, expr);
} catch (boost::exception&) {
Log(LogWarning, "AttributeFilter")
- << "Regex '" << m_Operand << " " << m_Operator << " " << value << "' error.";
+ << "Regex '" << m_Operand << " " << m_Operator << " " << value << "' error.";
ret = false;
}
using namespace icinga;
AvgAggregator::AvgAggregator(const String& attr)
- : m_AvgAttr(attr)
+ : m_AvgAttr(attr)
{ }
AvgAggregatorState *AvgAggregator::EnsureState(AggregatorState **state)
struct AvgAggregatorState : public AggregatorState
{
AvgAggregatorState(void)
- : Avg(0), AvgCount(0)
+ : Avg(0), AvgCount(0)
{ }
double Avg;
}
void CommandsTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&CommandsTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "line", Column(&CommandsTable::LineAccessor, objectAccessor));
CommandsTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
}
void CommentsTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "author", Column(&CommentsTable::AuthorAccessor, objectAccessor));
table->AddColumn(prefix + "comment", Column(&CommentsTable::CommentAccessor, objectAccessor));
CommentsTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
}
void ContactGroupsTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&ContactGroupsTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "alias", Column(&ContactGroupsTable::AliasAccessor, objectAccessor));
ContactGroupsTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
ContactsTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
struct CountAggregatorState : public AggregatorState
{
CountAggregatorState(void)
- : Count(0)
+ : Count(0)
{ }
int Count;
}
void DowntimesTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "author", Column(&DowntimesTable::AuthorAccessor, objectAccessor));
table->AddColumn(prefix + "comment", Column(&DowntimesTable::CommentAccessor, objectAccessor));
DowntimesTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
}
void EndpointsTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&EndpointsTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "identity", Column(&EndpointsTable::IdentityAccessor, objectAccessor));
EndpointsTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
}
void HostGroupsTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&HostGroupsTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "alias", Column(&HostGroupsTable::AliasAccessor, objectAccessor));
HostGroupsTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
using namespace icinga;
HostsTable::HostsTable(LivestatusGroupByType type)
- :Table(type)
+ :Table(type)
{
AddColumns(this);
}
void HostsTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&HostsTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "host_name", Column(&HostsTable::NameAccessor, objectAccessor)); //ugly compatibility hack
if (table->GetGroupByType() == LivestatusGroupByHostGroup) {
/* _1 = row, _2 = groupByType, _3 = groupByObject */
Log(LogDebug, "Livestatus")
- << "Processing hosts group by hostgroup table.";
+ << "Processing hosts group by hostgroup table.";
HostGroupsTable::AddColumns(table, "hostgroup_", std::bind(&HostsTable::HostGroupAccessor, _1, _2, _3));
}
}
return Empty;
MacroProcessor::ResolverList resolvers {
- { "host", host },
- { "icinga", IcingaApplication::GetInstance() }
+ { "host", host },
+ { "icinga", IcingaApplication::GetInstance() }
};
return MacroProcessor::ResolveMacros(host->GetNotes(), resolvers);
return Empty;
MacroProcessor::ResolverList resolvers {
- { "host", host },
- { "icinga", IcingaApplication::GetInstance() }
+ { "host", host },
+ { "icinga", IcingaApplication::GetInstance() }
};
return MacroProcessor::ResolveMacros(host->GetNotesUrl(), resolvers);
return Empty;
MacroProcessor::ResolverList resolvers {
- { "host", host },
- { "icinga", IcingaApplication::GetInstance() }
+ { "host", host },
+ { "icinga", IcingaApplication::GetInstance() }
};
return MacroProcessor::ResolveMacros(host->GetActionUrl(), resolvers);
return Empty;
MacroProcessor::ResolverList resolvers {
- { "host", host },
- { "icinga", IcingaApplication::GetInstance() }
+ { "host", host },
+ { "icinga", IcingaApplication::GetInstance() }
};
return MacroProcessor::ResolveMacros(host->GetIconImage(), resolvers);
HostsTable(LivestatusGroupByType type = LivestatusGroupByNone);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
using namespace icinga;
InvAvgAggregator::InvAvgAggregator(const String& attr)
- : m_InvAvgAttr(attr)
+ : m_InvAvgAttr(attr)
{ }
InvAvgAggregatorState *InvAvgAggregator::EnsureState(AggregatorState **state)
struct InvAvgAggregatorState : public AggregatorState
{
InvAvgAggregatorState(void)
- : InvAvg(0), InvAvgCount(0)
+ : InvAvg(0), InvAvgCount(0)
{ }
double InvAvg;
using namespace icinga;
InvSumAggregator::InvSumAggregator(const String& attr)
- : m_InvSumAttr(attr)
+ : m_InvSumAttr(attr)
{ }
InvSumAggregatorState *InvSumAggregator::EnsureState(AggregatorState **state)
struct I2_LIVESTATUS_API InvSumAggregatorState : public AggregatorState
{
InvSumAggregatorState(void)
- : InvSum(0)
+ : InvSum(0)
{ }
double InvSum;
ObjectImpl<LivestatusListener>::Start(runtimeCreated);
Log(LogInformation, "LivestatusListener")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
if (GetSocketType() == "tcp") {
TcpSocket::Ptr socket = new TcpSocket();
socket->Bind(GetBindHost(), GetBindPort(), AF_UNSPEC);
} catch (std::exception&) {
Log(LogCritical, "LivestatusListener")
- << "Cannot bind TCP socket on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
+ << "Cannot bind TCP socket on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
return;
}
m_Thread = std::thread(std::bind(&LivestatusListener::ServerThreadProc, this));
Log(LogInformation, "LivestatusListener")
- << "Created TCP socket listening on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
+ << "Created TCP socket listening on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
}
else if (GetSocketType() == "unix") {
#ifndef _WIN32
socket->Bind(GetSocketPath());
} catch (std::exception&) {
Log(LogCritical, "LivestatusListener")
- << "Cannot bind UNIX socket to '" << GetSocketPath() << "'.";
+ << "Cannot bind UNIX socket to '" << GetSocketPath() << "'.";
return;
}
if (chmod(GetSocketPath().CStr(), mode) < 0) {
Log(LogCritical, "LivestatusListener")
- << "chmod() on unix socket '" << GetSocketPath() << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
+ << "chmod() on unix socket '" << GetSocketPath() << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
return;
}
m_Thread = std::thread(std::bind(&LivestatusListener::ServerThreadProc, this));
Log(LogInformation, "LivestatusListener")
- << "Created UNIX socket in '" << GetSocketPath() << "'.";
+ << "Created UNIX socket in '" << GetSocketPath() << "'.";
#else
/* no UNIX sockets on windows */
Log(LogCritical, "LivestatusListener", "Unix sockets are not supported on Windows.");
ObjectImpl<LivestatusListener>::Stop(runtimeRemoved);
Log(LogInformation, "LivestatusListener")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
m_Listener->Close();
stream.close();
Log(LogDebug, "LivestatusLogUtility")
- << "Indexing log file: '" << path << "' with timestamp start: '" << ts_start << "'.";
+ << "Indexing log file: '" << path << "' with timestamp start: '" << ts_start << "'.";
index[ts_start] = path;
}
void LivestatusLogUtility::CreateLogCache(std::map<time_t, String> index, HistoryTable *table,
- time_t from, time_t until, const AddRowFunction& addRowFn)
+ time_t from, time_t until, const AddRowFunction& addRowFn)
{
ASSERT(table);
/* no attributes available - invalid log line */
if (!log_entry_attrs) {
Log(LogDebug, "LivestatusLogUtility")
- << "Skipping invalid log line: '" << line << "'.";
+ << "Skipping invalid log line: '" << line << "'.";
continue;
}
unsigned long time = atoi(text.SubStr(1, 11).CStr());
Log(LogDebug, "LivestatusLogUtility")
- << "Processing log line: '" << text << "'.";
+ << "Processing log line: '" << text << "'.";
bag->Set("time", time);
size_t colon = text.FindFirstOf(':');
bag->Set("message", text); /* used as 'message' in log table, and 'log_output' in statehist table */
if (type.Contains("INITIAL HOST STATE") ||
- type.Contains("CURRENT HOST STATE") ||
- type.Contains("HOST ALERT")) {
+ type.Contains("CURRENT HOST STATE") ||
+ type.Contains("HOST ALERT")) {
if (tokens.size() < 5)
return bag;
}
return bag;
- } else if (type.Contains("HOST DOWNTIME ALERT") ||
- type.Contains("HOST FLAPPING ALERT")) {
+ } else if (type.Contains("HOST DOWNTIME ALERT") || type.Contains("HOST FLAPPING ALERT")) {
if (tokens.size() < 3)
return bag;
return bag;
} else if (type.Contains("INITIAL SERVICE STATE") ||
- type.Contains("CURRENT SERVICE STATE") ||
- type.Contains("SERVICE ALERT")) {
+ type.Contains("CURRENT SERVICE STATE") ||
+ type.Contains("SERVICE ALERT")) {
if (tokens.size() < 6)
return bag;
return bag;
} else if (type.Contains("SERVICE DOWNTIME ALERT") ||
- type.Contains("SERVICE FLAPPING ALERT")) {
+ type.Contains("SERVICE FLAPPING ALERT")) {
if (tokens.size() < 4)
return bag;
}
/* program */
else if (type.Contains("restarting...") ||
- type.Contains("shutting down...") ||
- type.Contains("Bailing out") ||
- type.Contains("active mode...") ||
- type.Contains("standby mode...")) {
+ type.Contains("shutting down...") ||
+ type.Contains("Bailing out") ||
+ type.Contains("active mode...") ||
+ type.Contains("standby mode...")) {
bag->Set("class", LogEntryClassProgram);
return bag;
{
enum LogEntryType {
- LogEntryTypeHostAlert,
- LogEntryTypeHostDowntimeAlert,
- LogEntryTypeHostFlapping,
- LogEntryTypeHostNotification,
- LogEntryTypeHostInitialState,
- LogEntryTypeHostCurrentState,
- LogEntryTypeServiceAlert,
- LogEntryTypeServiceDowntimeAlert,
- LogEntryTypeServiceFlapping,
- LogEntryTypeServiceNotification,
- LogEntryTypeServiceInitialState,
- LogEntryTypeServiceCurrentState,
- LogEntryTypeTimeperiodTransition,
- LogEntryTypeVersion,
- LogEntryTypeInitialStates,
- LogEntryTypeProgramStarting
+ LogEntryTypeHostAlert,
+ LogEntryTypeHostDowntimeAlert,
+ LogEntryTypeHostFlapping,
+ LogEntryTypeHostNotification,
+ LogEntryTypeHostInitialState,
+ LogEntryTypeHostCurrentState,
+ LogEntryTypeServiceAlert,
+ LogEntryTypeServiceDowntimeAlert,
+ LogEntryTypeServiceFlapping,
+ LogEntryTypeServiceNotification,
+ LogEntryTypeServiceInitialState,
+ LogEntryTypeServiceCurrentState,
+ LogEntryTypeTimeperiodTransition,
+ LogEntryTypeVersion,
+ LogEntryTypeInitialStates,
+ LogEntryTypeProgramStarting
};
enum LogEntryClass {
- LogEntryClassInfo = 0,
- LogEntryClassAlert = 1,
- LogEntryClassProgram = 2,
- LogEntryClassNotification = 3,
- LogEntryClassPassive = 4,
- LogEntryClassCommand = 5,
- LogEntryClassState = 6,
- LogEntryClassText = 7
+ LogEntryClassInfo = 0,
+ LogEntryClassAlert = 1,
+ LogEntryClassProgram = 2,
+ LogEntryClassNotification = 3,
+ LogEntryClassPassive = 4,
+ LogEntryClassCommand = 5,
+ LogEntryClassState = 6,
+ LogEntryClassText = 7
};
/**
LivestatusQuery::LivestatusQuery(const std::vector<String>& lines, const String& compat_log_path)
: m_KeepAlive(false), m_OutputFormat("csv"), m_ColumnHeaders(true), m_Limit(-1), m_ErrorCode(0),
- m_LogTimeFrom(0), m_LogTimeUntil(static_cast<long>(Utility::GetTime()))
+ m_LogTimeFrom(0), m_LogTimeUntil(static_cast<long>(Utility::GetTime()))
{
if (lines.size() == 0) {
m_Verb = "ERROR";
if (header == "Or" || header == "StatsOr") {
filter = new OrFilter();
Log(LogDebug, "LivestatusQuery")
- << "Add OR filter for " << params << " column(s). " << deq.size() << " filters available.";
+ << "Add OR filter for " << params << " column(s). " << deq.size() << " filters available.";
} else {
filter = new AndFilter();
Log(LogDebug, "LivestatusQuery")
- << "Add AND filter for " << params << " column(s). " << deq.size() << " filters available.";
+ << "Add AND filter for " << params << " column(s). " << deq.size() << " filters available.";
}
if (num > deq.size()) {
while (num > 0 && num--) {
filter->AddSubFilter(deq.back());
Log(LogDebug, "LivestatusQuery")
- << "Add " << num << " filter.";
+ << "Add " << num << " filter.";
deq.pop_back();
if (&deq == &stats)
aggregators.pop_back();
}
Log(LogDebug, "LivestatusQuery")
- << "Parsed filter with attr: '" << attr << "' op: '" << op << "' val: '" << val << "'.";
+ << "Parsed filter with attr: '" << attr << "' op: '" << op << "' val: '" << val << "'.";
return filter;
}
void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream)
{
Log(LogNotice, "LivestatusQuery")
- << "Table: " << m_Table;
+ << "Table: " << m_Table;
Table::Ptr table = Table::GetByName(m_Table, m_CompatLogPath, m_LogTimeFrom, m_LogTimeUntil);
}
Log(LogNotice, "LivestatusQuery")
- << "Executing command: " << m_Command;
+ << "Executing command: " << m_Command;
ExternalCommandProcessor::Execute(m_Command);
SendResponse(stream, LivestatusErrorOK, "");
}
void LivestatusQuery::ExecuteErrorHelper(const Stream::Ptr& stream)
{
Log(LogDebug, "LivestatusQuery")
- << "ERROR: Code: '" << m_ErrorCode << "' Message: '" << m_ErrorMessage << "'.";
+ << "ERROR: Code: '" << m_ErrorCode << "' Message: '" << m_ErrorMessage << "'.";
SendResponse(stream, m_ErrorCode, m_ErrorMessage);
}
{
try {
Log(LogNotice, "LivestatusQuery")
- << "Executing livestatus query: " << m_Verb;
+ << "Executing livestatus query: " << m_Verb;
if (m_Verb == "GET")
ExecuteGetHelper(stream);
}
void LogTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "time", Column(&LogTable::TimeAccessor, objectAccessor));
table->AddColumn(prefix + "lineno", Column(&LogTable::LinenoAccessor, objectAccessor));
void LogTable::FetchRows(const AddRowFunction& addRowFn)
{
Log(LogDebug, "LogTable")
- << "Pre-selecting log file from " << m_TimeFrom << " until " << m_TimeUntil;
+ << "Pre-selecting log file from " << m_TimeFrom << " until " << m_TimeUntil;
/* create log file index */
LivestatusLogUtility::CreateLogIndex(m_CompatLogPath, m_LogFileIndex);
LogTable(const String& compat_log_path, time_t from, time_t until);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
using namespace icinga;
MaxAggregator::MaxAggregator(const String& attr)
- : m_MaxAttr(attr)
+ : m_MaxAttr(attr)
{ }
MaxAggregatorState *MaxAggregator::EnsureState(AggregatorState **state)
struct I2_LIVESTATUS_API MaxAggregatorState : public AggregatorState
{
MaxAggregatorState(void)
- : Max(0)
+ : Max(0)
{ }
double Max;
using namespace icinga;
MinAggregator::MinAggregator(const String& attr)
- : m_MinAttr(attr)
+ : m_MinAttr(attr)
{ }
MinAggregatorState *MinAggregator::EnsureState(AggregatorState **state)
struct I2_LIVESTATUS_API MinAggregatorState : public AggregatorState
{
MinAggregatorState(void)
- : Min(DBL_MAX)
+ : Min(DBL_MAX)
{ }
double Min;
}
void ServiceGroupsTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&ServiceGroupsTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "alias", Column(&ServiceGroupsTable::AliasAccessor, objectAccessor));
ServiceGroupsTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
using namespace icinga;
ServicesTable::ServicesTable(LivestatusGroupByType type)
- : Table(type)
+ : Table(type)
{
AddColumns(this);
}
void ServicesTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "description", Column(&ServicesTable::ShortNameAccessor, objectAccessor));
table->AddColumn(prefix + "service_description", Column(&ServicesTable::ShortNameAccessor, objectAccessor)); //ugly compatibility hack
if (table->GetGroupByType() == LivestatusGroupByServiceGroup) {
/* _1 = row, _2 = groupByType, _3 = groupByObject */
Log(LogDebug, "Livestatus")
- << "Processing services group by servicegroup table.";
+ << "Processing services group by servicegroup table.";
ServiceGroupsTable::AddColumns(table, "servicegroup_", std::bind(&ServicesTable::ServiceGroupAccessor, _1, _2, _3));
} else if (table->GetGroupByType() == LivestatusGroupByHostGroup) {
/* _1 = row, _2 = groupByType, _3 = groupByObject */
Log(LogDebug, "Livestatus")
- << "Processing services group by hostgroup table.";
+ << "Processing services group by hostgroup table.";
HostGroupsTable::AddColumns(table, "hostgroup_", std::bind(&ServicesTable::HostGroupAccessor, _1, _2, _3));
}
}
return Empty;
MacroProcessor::ResolverList resolvers {
- { "service", service },
- { "host", service->GetHost() },
- { "icinga", IcingaApplication::GetInstance() }
+ { "service", service },
+ { "host", service->GetHost() },
+ { "icinga", IcingaApplication::GetInstance() }
};
return MacroProcessor::ResolveMacros(service->GetNotes(), resolvers);
return Empty;
MacroProcessor::ResolverList resolvers {
- { "service", service },
- { "host", service->GetHost() },
- { "icinga", IcingaApplication::GetInstance() }
+ { "service", service },
+ { "host", service->GetHost() },
+ { "icinga", IcingaApplication::GetInstance() }
};
return MacroProcessor::ResolveMacros(service->GetNotesUrl(), resolvers);
return Empty;
MacroProcessor::ResolverList resolvers {
- { "service", service },
- { "host", service->GetHost() },
- { "icinga", IcingaApplication::GetInstance() }
+ { "service", service },
+ { "host", service->GetHost() },
+ { "icinga", IcingaApplication::GetInstance() }
};
return MacroProcessor::ResolveMacros(service->GetActionUrl(), resolvers);
return Empty;
MacroProcessor::ResolverList resolvers {
- { "service", service },
- { "host", service->GetHost() },
- { "icinga", IcingaApplication::GetInstance() }
+ { "service", service },
+ { "host", service->GetHost() },
+ { "icinga", IcingaApplication::GetInstance() }
};
return MacroProcessor::ResolveMacros(service->GetIconImage(), resolvers);
ServicesTable(LivestatusGroupByType type = LivestatusGroupByNone);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
state_hist_service_states->Add(state_hist_bag);
Log(LogDebug, "StateHistTable")
- << "statehist: Adding new object '" << checkable->GetName() << "' to services cache.";
+ << "statehist: Adding new object '" << checkable->GetName() << "' to services cache.";
} else {
state_hist_service_states = m_CheckablesCache[checkable];
state_hist_bag = state_hist_service_states->Get(state_hist_service_states->GetLength()-1); /* fetch latest state from history */
state_hist_service_states->Add(state_hist_bag_new);
Log(LogDebug, "StateHistTable")
- << "statehist: State change detected for object '" << checkable->GetName() << "' in '" << log_line << "'.";
+ << "statehist: State change detected for object '" << checkable->GetName() << "' in '" << log_line << "'.";
}
break;
case LogEntryTypeHostFlapping:
}
void StateHistTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "time", Column(&StateHistTable::TimeAccessor, objectAccessor));
table->AddColumn(prefix + "lineno", Column(&StateHistTable::LinenoAccessor, objectAccessor));
void StateHistTable::FetchRows(const AddRowFunction& addRowFn)
{
Log(LogDebug, "StateHistTable")
- << "Pre-selecting log file from " << m_TimeFrom << " until " << m_TimeUntil;
+ << "Pre-selecting log file from " << m_TimeFrom << " until " << m_TimeUntil;
/* create log file index */
LivestatusLogUtility::CreateLogIndex(m_CompatLogPath, m_LogFileIndex);
StateHistTable(const String& compat_log_path, time_t from, time_t until);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
}
void StatusTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "neb_callbacks", Column(&Table::ZeroAccessor, objectAccessor));
table->AddColumn(prefix + "neb_callbacks_rate", Column(&Table::ZeroAccessor, objectAccessor));
StatusTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
using namespace icinga;
StdAggregator::StdAggregator(const String& attr)
- : m_StdAttr(attr)
+ : m_StdAttr(attr)
{ }
StdAggregatorState *StdAggregator::EnsureState(AggregatorState **state)
struct I2_LIVESTATUS_API StdAggregatorState : public AggregatorState
{
StdAggregatorState(void)
- : StdSum(0), StdQSum(0), StdCount(0)
+ : StdSum(0), StdQSum(0), StdCount(0)
{ }
double StdSum;
using namespace icinga;
SumAggregator::SumAggregator(const String& attr)
- : m_SumAttr(attr)
+ : m_SumAttr(attr)
{ }
SumAggregatorState *SumAggregator::EnsureState(AggregatorState **state)
struct I2_LIVESTATUS_API SumAggregatorState : public AggregatorState
{
SumAggregatorState(void)
- : Sum(0)
+ : Sum(0)
{ }
double Sum;
using namespace icinga;
Table::Table(LivestatusGroupByType type)
- : m_GroupByType(type), m_GroupByObject(Empty)
+ : m_GroupByType(type), m_GroupByObject(Empty)
{ }
Table::Ptr Table::GetByName(const String& name, const String& compat_log_path, const unsigned long& from, const unsigned long& until)
}
void TimePeriodsTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&TimePeriodsTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "alias", Column(&TimePeriodsTable::AliasAccessor, objectAccessor));
TimePeriodsTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
}
void ZonesTable::AddColumns(Table *table, const String& prefix,
- const Column::ObjectAccessor& objectAccessor)
+ const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&ZonesTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "parent", Column(&ZonesTable::ParentAccessor, objectAccessor));
ZonesTable(void);
static void AddColumns(Table *table, const String& prefix = String(),
- const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
+ const Column::ObjectAccessor& objectAccessor = Column::ObjectAccessor());
virtual String GetName(void) const override;
virtual String GetPrefix(void) const override;
ICorRuntimeHost *runtimeHost;
if (FAILED(CorBindToRuntimeEx(nullptr, nullptr,
- STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN | STARTUP_CONCURRENT_GC,
- CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (void **)&runtimeHost))) {
+ STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN | STARTUP_CONCURRENT_GC,
+ CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (void **)&runtimeHost))) {
return;
}
}
void ClrCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
CheckCommand::Ptr commandObj = checkable->GetCheckCommand();
Value raw_command = commandObj->GetCommandLine();
String name = kv.second;
Value value = MacroProcessor::ResolveMacros(name, resolvers, checkable->GetLastCheckResult(),
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
envMacros->Set(kv.first, value);
}
vtObject = it->second;
} else {
String clr_assembly = MacroProcessor::ResolveMacros("$clr_assembly$", resolvers, checkable->GetLastCheckResult(),
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
String clr_type = MacroProcessor::ResolveMacros("$clr_type$", resolvers, checkable->GetLastCheckResult(),
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
if (resolvedMacros && !useResolvedMacros)
return;
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
ClrCheckTask(void);
REGISTER_SCRIPTFUNCTION_NS(Internal, ClusterCheck, &ClusterCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void ClusterCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
if (resolvedMacros && !useResolvedMacros)
return;
if (status->Get("num_not_conn_endpoints") > 0) {
cr->SetState(ServiceCritical);
cr->SetOutput("Icinga 2 Cluster Problem: " + Convert::ToString(status->Get("num_not_conn_endpoints")) +
- " Endpoints (" + not_connected_endpoints + ") not connected.");
+ " Endpoints (" + not_connected_endpoints + ") not connected.");
} else {
cr->SetState(ServiceOK);
cr->SetOutput("Icinga 2 Cluster is running: Connected Endpoints: "+ Convert::ToString(status->Get("num_conn_endpoints")) +
- " (" + connected_endpoints + ").");
+ " (" + connected_endpoints + ").");
}
checkable->ProcessCheckResult(cr);
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
ClusterCheckTask(void);
REGISTER_SCRIPTFUNCTION_NS(Internal, ClusterZoneCheck, &ClusterZoneCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void ClusterZoneCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
ApiListener::Ptr listener = ApiListener::GetInstance();
resolvers.emplace_back("icinga", IcingaApplication::GetInstance());
String zoneName = MacroProcessor::ResolveMacros("$cluster_zone$", resolvers, checkable->GetLastCheckResult(),
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
String missingLagWarning;
String missingLagCritical;
double lagWarning = MacroProcessor::ResolveMacros("$cluster_lag_warning$", resolvers, checkable->GetLastCheckResult(),
- &missingLagWarning, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ &missingLagWarning, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
double lagCritical = MacroProcessor::ResolveMacros("$cluster_lag_critical$", resolvers, checkable->GetLastCheckResult(),
- &missingLagCritical, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ &missingLagCritical, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
if (resolvedMacros && !useResolvedMacros)
return;
if (missingLagCritical.IsEmpty() && zoneLag > lagCritical) {
cr->SetState(ServiceCritical);
cr->SetOutput("Zone '" + zoneName + "' is connected. Log lag: " + Utility::FormatDuration(zoneLag)
- + " greater than critical threshold: " + Utility::FormatDuration(lagCritical));
+ + " greater than critical threshold: " + Utility::FormatDuration(lagCritical));
} else if (missingLagWarning.IsEmpty() && zoneLag > lagWarning) {
cr->SetState(ServiceWarning);
cr->SetOutput("Zone '" + zoneName + "' is connected. Log lag: " + Utility::FormatDuration(zoneLag)
- + " greater than warning threshold: " + Utility::FormatDuration(lagWarning));
+ + " greater than warning threshold: " + Utility::FormatDuration(lagWarning));
}
Array::Ptr perfdata = new Array();
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
ClusterZoneCheckTask(void);
REGISTER_SCRIPTFUNCTION_NS(Internal, DummyCheck, &DummyCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void DummyCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
CheckCommand::Ptr commandObj = checkable->GetCheckCommand();
resolvers.emplace_back("icinga", IcingaApplication::GetInstance());
int dummyState = MacroProcessor::ResolveMacros("$dummy_state$", resolvers, checkable->GetLastCheckResult(),
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
String dummyText = MacroProcessor::ResolveMacros("$dummy_text$", resolvers, checkable->GetLastCheckResult(),
- nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
+ nullptr, MacroProcessor::EscapeCallback(), resolvedMacros, useResolvedMacros);
if (resolvedMacros && !useResolvedMacros)
return;
{
public:
static void ScriptFunc(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
DummyCheckTask(void);
REGISTER_SCRIPTFUNCTION_NS(Internal, ExceptionCheck, &ExceptionCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void ExceptionCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
if (resolvedMacros && !useResolvedMacros)
return;
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
ExceptionCheckTask(void);
REGISTER_SCRIPTFUNCTION_NS(Internal, IcingaCheck, &IcingaCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void IcingaCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
if (resolvedMacros && !useResolvedMacros)
return;
perfdata->Add(new PerfdataValue("sum_bytes_received_per_second", bytesReceivedPerSecond));
cr->SetOutput("Icinga 2 has been running for " + Utility::FormatDuration(uptime) +
- ". Version: " + Application::GetAppVersion());
+ ". Version: " + Application::GetAppVersion());
cr->SetPerformanceData(perfdata);
double lastReloadFailed = Application::GetLastReloadFailed();
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
IcingaCheckTask(void);
REGISTER_SCRIPTFUNCTION_NS(Internal, NullCheck, &NullCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void NullCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
if (resolvedMacros && !useResolvedMacros)
return;
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
NullCheckTask(void);
{
public:
static void ScriptFunc(const Checkable::Ptr& service,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
NullEventTask(void);
REGISTER_SCRIPTFUNCTION_NS(Internal, PluginCheck, &PluginCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void PluginCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
CheckCommand::Ptr commandObj = checkable->GetCheckCommand();
resolvers.emplace_back("icinga", IcingaApplication::GetInstance());
PluginUtility::ExecuteCommand(commandObj, checkable, checkable->GetLastCheckResult(),
- resolvers, resolvedMacros, useResolvedMacros,
- std::bind(&PluginCheckTask::ProcessFinishedHandler, checkable, cr, _1, _2));
+ resolvers, resolvedMacros, useResolvedMacros,
+ std::bind(&PluginCheckTask::ProcessFinishedHandler, checkable, cr, _1, _2));
if (!resolvedMacros || useResolvedMacros)
Checkable::IncreasePendingChecks();
if (pr.ExitStatus > 3) {
Process::Arguments parguments = Process::PrepareCommand(commandLine);
Log(LogWarning, "PluginCheckTask")
- << "Check command for object '" << checkable->GetName() << "' (PID: " << pr.PID
- << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code "
- << pr.ExitStatus << ", output: " << pr.Output;
+ << "Check command for object '" << checkable->GetName() << "' (PID: " << pr.PID
+ << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code "
+ << pr.ExitStatus << ", output: " << pr.Output;
}
String output = pr.Output.Trim();
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
PluginCheckTask(void);
static void ProcessFinishedHandler(const Checkable::Ptr& service,
- const CheckResult::Ptr& cr, const Value& commandLine, const ProcessResult& pr);
+ const CheckResult::Ptr& cr, const Value& commandLine, const ProcessResult& pr);
};
}
REGISTER_SCRIPTFUNCTION_NS(Internal, PluginEvent, &PluginEventTask::ScriptFunc, "checkable:resolvedMacros:useResolvedMacros");
void PluginEventTask::ScriptFunc(const Checkable::Ptr& checkable,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
EventCommand::Ptr commandObj = checkable->GetEventCommand();
resolvers.emplace_back("icinga", IcingaApplication::GetInstance());
PluginUtility::ExecuteCommand(commandObj, checkable, checkable->GetLastCheckResult(),
- resolvers, resolvedMacros, useResolvedMacros,
- std::bind(&PluginEventTask::ProcessFinishedHandler, checkable, _1, _2));
+ resolvers, resolvedMacros, useResolvedMacros,
+ std::bind(&PluginEventTask::ProcessFinishedHandler, checkable, _1, _2));
}
void PluginEventTask::ProcessFinishedHandler(const Checkable::Ptr& checkable, const Value& commandLine, const ProcessResult& pr)
if (pr.ExitStatus != 0) {
Process::Arguments parguments = Process::PrepareCommand(commandLine);
Log(LogNotice, "PluginEventTask")
- << "Event command for object '" << checkable->GetName() << "' (PID: " << pr.PID
- << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code "
- << pr.ExitStatus << ", output: " << pr.Output;
+ << "Event command for object '" << checkable->GetName() << "' (PID: " << pr.PID
+ << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code "
+ << pr.ExitStatus << ", output: " << pr.Output;
}
}
{
public:
static void ScriptFunc(const Checkable::Ptr& service,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
PluginEventTask(void);
static void ProcessFinishedHandler(const Checkable::Ptr& checkable,
- const Value& commandLine, const ProcessResult& pr);
+ const Value& commandLine, const ProcessResult& pr);
};
}
REGISTER_SCRIPTFUNCTION_NS(Internal, PluginNotification, &PluginNotificationTask::ScriptFunc, "notification:user:cr:itype:author:comment:resolvedMacros:useResolvedMacros");
void PluginNotificationTask::ScriptFunc(const Notification::Ptr& notification,
- const User::Ptr& user, const CheckResult::Ptr& cr, int itype,
- const String& author, const String& comment, const Dictionary::Ptr& resolvedMacros,
- bool useResolvedMacros)
+ const User::Ptr& user, const CheckResult::Ptr& cr, int itype,
+ const String& author, const String& comment, const Dictionary::Ptr& resolvedMacros,
+ bool useResolvedMacros)
{
NotificationCommand::Ptr commandObj = notification->GetCommand();
resolvers.emplace_back("icinga", IcingaApplication::GetInstance());
PluginUtility::ExecuteCommand(commandObj, checkable, cr, resolvers,
- resolvedMacros, useResolvedMacros,
- std::bind(&PluginNotificationTask::ProcessFinishedHandler, checkable, _1, _2));
+ resolvedMacros, useResolvedMacros,
+ std::bind(&PluginNotificationTask::ProcessFinishedHandler, checkable, _1, _2));
}
void PluginNotificationTask::ProcessFinishedHandler(const Checkable::Ptr& checkable, const Value& commandLine, const ProcessResult& pr)
if (pr.ExitStatus != 0) {
Process::Arguments parguments = Process::PrepareCommand(commandLine);
Log(LogWarning, "PluginNotificationTask")
- << "Notification command for object '" << checkable->GetName() << "' (PID: " << pr.PID
- << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code "
- << pr.ExitStatus << ", output: " << pr.Output;
+ << "Notification command for object '" << checkable->GetName() << "' (PID: " << pr.PID
+ << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code "
+ << pr.ExitStatus << ", output: " << pr.Output;
}
}
{
public:
static void ScriptFunc(const Notification::Ptr& notification,
- const User::Ptr& user, const CheckResult::Ptr& cr, int itype,
- const String& author, const String& comment,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const User::Ptr& user, const CheckResult::Ptr& cr, int itype,
+ const String& author, const String& comment,
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
PluginNotificationTask(void);
static void ProcessFinishedHandler(const Checkable::Ptr& checkable,
- const Value& commandLine, const ProcessResult& pr);
+ const Value& commandLine, const ProcessResult& pr);
};
}
REGISTER_SCRIPTFUNCTION_NS(Internal, RandomCheck, &RandomCheckTask::ScriptFunc, "checkable:cr:resolvedMacros:useResolvedMacros");
void RandomCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
if (resolvedMacros && !useResolvedMacros)
return;
{
public:
static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
- const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
+ const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros);
private:
RandomCheckTask(void);
ObjectImpl<NotificationComponent>::Start(runtimeCreated);
Log(LogInformation, "NotificationComponent")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
Checkable::OnNotificationsRequested.connect(std::bind(&NotificationComponent::SendNotificationsHandler, this, _1,
- _2, _3, _4, _5));
+ _2, _3, _4, _5));
m_NotificationTimer = new Timer();
m_NotificationTimer->SetInterval(5);
void NotificationComponent::Stop(bool runtimeRemoved)
{
Log(LogInformation, "NotificationComponent")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
ObjectImpl<NotificationComponent>::Stop(runtimeRemoved);
}
try {
Log(LogNotice, "NotificationComponent")
- << "Attempting to send reminder notification '" << notification->GetName() << "'";
+ << "Attempting to send reminder notification '" << notification->GetName() << "'";
notification->BeginExecuteNotification(NotificationProblem, checkable->GetLastCheckResult(), false, true);
} catch (const std::exception& ex) {
Log(LogWarning, "NotificationComponent")
- << "Exception occured during notification for object '"
- << GetName() << "': " << DiagnosticInformation(ex);
+ << "Exception occured during notification for object '"
+ << GetName() << "': " << DiagnosticInformation(ex);
}
}
}
* Processes icinga::SendNotifications messages.
*/
void NotificationComponent::SendNotificationsHandler(const Checkable::Ptr& checkable, NotificationType type,
- const CheckResult::Ptr& cr, const String& author, const String& text)
+ const CheckResult::Ptr& cr, const String& author, const String& text)
{
checkable->SendNotifications(type, cr, author, text);
}
void NotificationTimerHandler(void);
void SendNotificationsHandler(const Checkable::Ptr& checkable, NotificationType type,
- const CheckResult::Ptr& cr, const String& author, const String& text);
+ const CheckResult::Ptr& cr, const String& author, const String& text);
};
}
m_EventPrefix = "icinga2.event.";
- Log(LogInformation, "ElasticsearchWriter")
- << "'" << GetName() << "' started.";
+ Log(LogInformation, "ElasticsearchWriter")
+ << "'" << GetName() << "' started.";
m_WorkQueue.SetExceptionCallback(std::bind(&ElasticsearchWriter::ExceptionHandler, this, _1));
void ElasticsearchWriter::Stop(bool runtimeRemoved)
{
Log(LogInformation, "ElasticsearchWriter")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
m_WorkQueue.Join();
pdv = PerfdataValue::Parse(val);
} catch (const std::exception&) {
Log(LogWarning, "ElasticsearchWriter")
- << "Ignoring invalid perfdata value: '" << val << "' for object '"
- << checkable->GetName() << "'.";
+ << "Ignoring invalid perfdata value: '" << val << "' for object '"
+ << checkable->GetName() << "'.";
}
}
}
void ElasticsearchWriter::NotificationSentToAllUsersHandler(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 Checkable::Ptr& checkable, const std::set<User::Ptr>& users, NotificationType type,
+ const CheckResult::Ptr& cr, const String& author, const String& text)
{
m_WorkQueue.Enqueue(std::bind(&ElasticsearchWriter::NotificationSentToAllUsersHandlerInternal, this,
- notification, checkable, users, type, cr, author, text));
+ notification, checkable, users, type, cr, author, text));
}
void ElasticsearchWriter::NotificationSentToAllUsersHandlerInternal(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 Checkable::Ptr& checkable, const std::set<User::Ptr>& users, NotificationType type,
+ const CheckResult::Ptr& cr, const String& author, const String& text)
{
AssertOnWorkQueue();
CONTEXT("Elasticwriter processing notification to all users '" + checkable->GetName() + "'");
Log(LogDebug, "ElasticsearchWriter")
- << "Processing notification for '" << checkable->GetName() << "'";
+ << "Processing notification for '" << checkable->GetName() << "'";
Host::Ptr host;
Service::Ptr service;
String fieldsBody = JsonEncode(fields);
Log(LogDebug, "ElasticsearchWriter")
- << "Add to fields to message list: '" << fieldsBody << "'.";
+ << "Add to fields to message list: '" << fieldsBody << "'.";
m_DataBuffer.emplace_back(indexBody + fieldsBody);
/* Flush if we've buffered too much to prevent excessive memory use. */
if (static_cast<int>(m_DataBuffer.size()) >= GetFlushThreshold()) {
Log(LogDebug, "ElasticsearchWriter")
- << "Data buffer overflow writing " << m_DataBuffer.size() << " data points";
+ << "Data buffer overflow writing " << m_DataBuffer.size() << " data points";
Flush();
}
}
/* Flush if there are any data available. */
if (m_DataBuffer.size() > 0) {
Log(LogDebug, "ElasticsearchWriter")
- << "Timer expired writing " << m_DataBuffer.size() << " data points";
+ << "Timer expired writing " << m_DataBuffer.size() << " data points";
Flush();
}
}
/* Don't log the request body to debug log, this is already done above. */
Log(LogDebug, "ElasticsearchWriter")
- << "Sending " << req.RequestMethod << " request" << ((!username.IsEmpty() && !password.IsEmpty()) ? " with basic auth" : "" )
- << " to '" << url->Format() << "'.";
+ << "Sending " << req.RequestMethod << " request" << ((!username.IsEmpty() && !password.IsEmpty()) ? " with basic auth" : "" )
+ << " to '" << url->Format() << "'.";
try {
req.WriteBody(body.CStr(), body.GetLength());
; /* Do nothing */
} catch (const std::exception& ex) {
Log(LogWarning, "ElasticsearchWriter")
- << "Failed to parse HTTP response from host '" << GetHost() << "' port '" << GetPort() << "': " << DiagnosticInformation(ex, false);
+ << "Failed to parse HTTP response from host '" << GetHost() << "' port '" << GetPort() << "': " << DiagnosticInformation(ex, false);
throw ex;
}
if (!resp.Complete) {
Log(LogWarning, "ElasticsearchWriter")
- << "Failed to read a complete HTTP response from the Elasticsearch server.";
+ << "Failed to read a complete HTTP response from the Elasticsearch server.";
return;
}
/* More verbose error logging with Elasticsearch is hidden behind a proxy. */
if (!username.IsEmpty() && !password.IsEmpty()) {
Log(LogCritical, "ElasticsearchWriter")
- << "401 Unauthorized. Please ensure that the user '" << username
- << "' is able to authenticate against the HTTP API/Proxy.";
+ << "401 Unauthorized. Please ensure that the user '" << username
+ << "' is able to authenticate against the HTTP API/Proxy.";
} else {
Log(LogCritical, "ElasticsearchWriter")
- << "401 Unauthorized. The HTTP API requires authentication but no username/password has been configured.";
+ << "401 Unauthorized. The HTTP API requires authentication but no username/password has been configured.";
}
return;
}
Log(LogWarning, "ElasticsearchWriter")
- << "Unexpected response code " << resp.StatusCode;
+ << "Unexpected response code " << resp.StatusCode;
String contentType = resp.Headers->Get("content-type");
if (contentType != "application/json") {
Log(LogWarning, "ElasticsearchWriter")
- << "Unexpected Content-Type: " << contentType;
+ << "Unexpected Content-Type: " << contentType;
return;
}
jsonResponse = JsonDecode(buffer.get());
} catch (...) {
Log(LogWarning, "ElasticsearchWriter")
- << "Unable to parse JSON response:\n" << buffer.get();
+ << "Unable to parse JSON response:\n" << buffer.get();
return;
}
String error = jsonResponse->Get("error");
Log(LogCritical, "ElasticsearchWriter")
- << "Elasticsearch error message:\n" << error;
+ << "Elasticsearch error message:\n" << error;
return;
}
TcpSocket::Ptr socket = new TcpSocket();
Log(LogNotice, "ElasticsearchWriter")
- << "Connecting to Elasticsearch on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Connecting to Elasticsearch on host '" << GetHost() << "' port '" << GetPort() << "'.";
try {
socket->Connect(GetHost(), GetPort());
} catch (const std::exception& ex) {
Log(LogWarning, "ElasticsearchWriter")
- << "Can't connect to Elasticsearch on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Can't connect to Elasticsearch on host '" << GetHost() << "' port '" << GetPort() << "'.";
throw ex;
}
sslContext = MakeSSLContext(GetCertPath(), GetKeyPath(), GetCaPath());
} catch (const std::exception& ex) {
Log(LogWarning, "ElasticsearchWriter")
- << "Unable to create SSL context.";
+ << "Unable to create SSL context.";
throw ex;
}
tlsStream->Handshake();
} catch (const std::exception& ex) {
Log(LogWarning, "ElasticsearchWriter")
- << "TLS handshake with host '" << GetHost() << "' on port " << GetPort() << " failed.";
+ << "TLS handshake with host '" << GetHost() << "' on port " << GetPort() << " failed.";
throw ex;
}
void CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr);
void InternalCheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr);
void NotificationSentToAllUsersHandler(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 Checkable::Ptr& checkable, const std::set<User::Ptr>& users, NotificationType type,
+ const CheckResult::Ptr& cr, const String& author, const String& text);
void NotificationSentToAllUsersHandlerInternal(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 Checkable::Ptr& checkable, const std::set<User::Ptr>& users, NotificationType type,
+ const CheckResult::Ptr& cr, const String& author, const String& text);
void Enqueue(String type, const Dictionary::Ptr& fields, double ts);
REGISTER_STATSFUNCTION(GelfWriter, &GelfWriter::StatsFunc);
GelfWriter::GelfWriter(void)
- : m_WorkQueue(10000000, 1)
+ : m_WorkQueue(10000000, 1)
{ }
void GelfWriter::OnConfigLoaded(void)
ObjectImpl<GelfWriter>::Start(runtimeCreated);
Log(LogInformation, "GelfWriter")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
/* Register exception handler for WQ tasks. */
m_WorkQueue.SetExceptionCallback(std::bind(&GelfWriter::ExceptionHandler, this, _1));
void GelfWriter::Stop(bool runtimeRemoved)
{
Log(LogInformation, "GelfWriter")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
m_WorkQueue.Join();
Log(LogCritical, "GelfWriter", "Exception during Graylog Gelf operation: Verify that your backend is operational!");
Log(LogDebug, "GelfWriter")
- << "Exception during Graylog Gelf operation: " << DiagnosticInformation(exp);
+ << "Exception during Graylog Gelf operation: " << DiagnosticInformation(exp);
if (GetConnected()) {
m_Stream->Close();
TcpSocket::Ptr socket = new TcpSocket();
Log(LogNotice, "GelfWriter")
- << "Reconnecting to Graylog Gelf on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Reconnecting to Graylog Gelf on host '" << GetHost() << "' port '" << GetPort() << "'.";
try {
socket->Connect(GetHost(), GetPort());
} catch (const std::exception& ex) {
Log(LogCritical, "GelfWriter")
- << "Can't connect to Graylog Gelf on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Can't connect to Graylog Gelf on host '" << GetHost() << "' port '" << GetPort() << "'.";
throw ex;
}
SetConnected(true);
Log(LogInformation, "GelfWriter")
- << "Finished reconnecting to Graylog Gelf in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
+ << "Finished reconnecting to Graylog Gelf in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
}
void GelfWriter::ReconnectTimerHandler(void)
CONTEXT("GELF Processing check result for '" + checkable->GetName() + "'");
Log(LogDebug, "GelfWriter")
- << "Processing check result for '" << checkable->GetName() << "'";
+ << "Processing check result for '" << checkable->GetName() << "'";
Host::Ptr host;
Service::Ptr service;
pdv = PerfdataValue::Parse(val);
} catch (const std::exception&) {
Log(LogWarning, "GelfWriter")
- << "Ignoring invalid perfdata value: '" << val << "' for object '"
- << checkable->GetName() << "'.";
+ << "Ignoring invalid perfdata value: '" << val << "' for object '"
+ << checkable->GetName() << "'.";
}
}
}
void GelfWriter::NotificationToUserHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
- const User::Ptr& user, NotificationType notificationType, CheckResult::Ptr const& cr,
- const String& author, const String& commentText, const String& commandName)
+ const User::Ptr& user, NotificationType notificationType, CheckResult::Ptr const& cr,
+ const String& author, const String& commentText, const String& commandName)
{
m_WorkQueue.Enqueue(std::bind(&GelfWriter::NotificationToUserHandlerInternal, this,
- notification, checkable, user, notificationType, cr, author, commentText, commandName));
+ notification, checkable, user, notificationType, cr, author, commentText, commandName));
}
void GelfWriter::NotificationToUserHandlerInternal(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
- const User::Ptr& user, NotificationType notificationType, CheckResult::Ptr const& cr,
- const String& author, const String& commentText, const String& commandName)
+ const User::Ptr& user, NotificationType notificationType, CheckResult::Ptr const& cr,
+ const String& author, const String& commentText, const String& commandName)
{
AssertOnWorkQueue();
- CONTEXT("GELF Processing notification to all users '" + checkable->GetName() + "'");
+ CONTEXT("GELF Processing notification to all users '" + checkable->GetName() + "'");
Log(LogDebug, "GelfWriter")
- << "Processing notification for '" << checkable->GetName() << "'";
+ << "Processing notification for '" << checkable->GetName() << "'";
Host::Ptr host;
Service::Ptr service;
CONTEXT("GELF Processing state change '" + checkable->GetName() + "'");
Log(LogDebug, "GelfWriter")
- << "Processing state change for '" << checkable->GetName() << "'";
+ << "Processing state change for '" << checkable->GetName() << "'";
Host::Ptr host;
Service::Ptr service;
try {
Log(LogDebug, "GelfWriter")
- << "Sending '" << log << "'.";
+ << "Sending '" << log << "'.";
m_Stream->Write(log.CStr(), log.GetLength());
} catch (const std::exception& ex) {
Log(LogCritical, "GelfWriter")
- << "Cannot write to TCP socket on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Cannot write to TCP socket on host '" << GetHost() << "' port '" << GetPort() << "'.";
throw ex;
}
void CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr);
void CheckResultHandlerInternal(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr);
void NotificationToUserHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
- const User::Ptr& user, NotificationType notificationType, const CheckResult::Ptr& cr,
- const String& author, const String& commentText, const String& commandName);
+ const User::Ptr& user, NotificationType notificationType, const CheckResult::Ptr& cr,
+ const String& author, const String& commentText, const String& commandName);
void NotificationToUserHandlerInternal(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
- const User::Ptr& user, NotificationType notification_type, const CheckResult::Ptr& cr,
- const String& author, const String& comment_text, const String& command_name);
+ const User::Ptr& user, NotificationType notification_type, const CheckResult::Ptr& cr,
+ const String& author, const String& comment_text, const String& command_name);
void StateChangeHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, StateType type);
void StateChangeHandlerInternal(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, StateType type);
REGISTER_STATSFUNCTION(GraphiteWriter, &GraphiteWriter::StatsFunc);
GraphiteWriter::GraphiteWriter(void)
- : m_WorkQueue(10000000, 1)
+ : m_WorkQueue(10000000, 1)
{ }
void GraphiteWriter::OnConfigLoaded(void)
ObjectImpl<GraphiteWriter>::Start(runtimeCreated);
Log(LogInformation, "GraphiteWriter")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
/* Register exception handler for WQ tasks. */
m_WorkQueue.SetExceptionCallback(std::bind(&GraphiteWriter::ExceptionHandler, this, _1));
void GraphiteWriter::Stop(bool runtimeRemoved)
{
Log(LogInformation, "GraphiteWriter")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
m_WorkQueue.Join();
Log(LogCritical, "GraphiteWriter", "Exception during Graphite operation: Verify that your backend is operational!");
Log(LogDebug, "GraphiteWriter")
- << "Exception during Graphite operation: " << DiagnosticInformation(exp);
+ << "Exception during Graphite operation: " << DiagnosticInformation(exp);
if (GetConnected()) {
m_Stream->Close();
TcpSocket::Ptr socket = new TcpSocket();
Log(LogNotice, "GraphiteWriter")
- << "Reconnecting to Graphite on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Reconnecting to Graphite on host '" << GetHost() << "' port '" << GetPort() << "'.";
try {
socket->Connect(GetHost(), GetPort());
} catch (const std::exception& ex) {
Log(LogCritical, "GraphiteWriter")
- << "Can't connect to Graphite on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Can't connect to Graphite on host '" << GetHost() << "' port '" << GetPort() << "'.";
throw ex;
}
SetConnected(true);
Log(LogInformation, "GraphiteWriter")
- << "Finished reconnecting to Graphite in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
+ << "Finished reconnecting to Graphite in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
}
void GraphiteWriter::ReconnectTimerHandler(void)
pdv = PerfdataValue::Parse(val);
} catch (const std::exception&) {
Log(LogWarning, "GraphiteWriter")
- << "Ignoring invalid perfdata value: " << val;
+ << "Ignoring invalid perfdata value: " << val;
continue;
}
}
msgbuf << prefix << "." << name << " " << Convert::ToString(value) << " " << static_cast<long>(ts);
Log(LogDebug, "GraphiteWriter")
- << "Add to metric list:'" << msgbuf.str() << "'.";
+ << "Add to metric list:'" << msgbuf.str() << "'.";
// do not send \n to debug log
msgbuf << "\n";
m_Stream->Write(metric.CStr(), metric.GetLength());
} catch (const std::exception& ex) {
Log(LogCritical, "GraphiteWriter")
- << "Cannot write to TCP socket on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Cannot write to TCP socket on host '" << GetHost() << "' port '" << GetPort() << "'.";
throw ex;
}
DECLARE_PTR_TYPEDEFS(InfluxdbInteger);
InfluxdbInteger(int value)
- : m_Value(value)
+ : m_Value(value)
{ }
int GetValue(void) const
REGISTER_STATSFUNCTION(InfluxdbWriter, &InfluxdbWriter::StatsFunc);
InfluxdbWriter::InfluxdbWriter(void)
- : m_WorkQueue(10000000, 1)
+ : m_WorkQueue(10000000, 1)
{ }
void InfluxdbWriter::OnConfigLoaded(void)
ObjectImpl<InfluxdbWriter>::Start(runtimeCreated);
Log(LogInformation, "InfluxdbWriter")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
/* Register exception handler for WQ tasks. */
m_WorkQueue.SetExceptionCallback(std::bind(&InfluxdbWriter::ExceptionHandler, this, _1));
void InfluxdbWriter::Stop(bool runtimeRemoved)
{
Log(LogInformation, "InfluxdbWriter")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
m_WorkQueue.Join();
Log(LogCritical, "InfluxdbWriter", "Exception during InfluxDB operation: Verify that your backend is operational!");
Log(LogDebug, "InfluxdbWriter")
- << "Exception during InfluxDB operation: " << DiagnosticInformation(exp);
+ << "Exception during InfluxDB operation: " << DiagnosticInformation(exp);
//TODO: Close the connection, if we keep it open.
}
TcpSocket::Ptr socket = new TcpSocket();
Log(LogNotice, "InfluxdbWriter")
- << "Reconnecting to InfluxDB on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Reconnecting to InfluxDB on host '" << GetHost() << "' port '" << GetPort() << "'.";
try {
socket->Connect(GetHost(), GetPort());
} catch (const std::exception& ex) {
Log(LogWarning, "InfluxdbWriter")
- << "Can't connect to InfluxDB on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Can't connect to InfluxDB on host '" << GetHost() << "' port '" << GetPort() << "'.";
throw ex;
}
sslContext = MakeSSLContext(GetSslCert(), GetSslKey(), GetSslCaCert());
} catch (const std::exception& ex) {
Log(LogWarning, "InfluxdbWriter")
- << "Unable to create SSL context.";
+ << "Unable to create SSL context.";
throw ex;
}
tlsStream->Handshake();
} catch (const std::exception& ex) {
Log(LogWarning, "InfluxdbWriter")
- << "TLS handshake with host '" << GetHost() << "' failed.";
+ << "TLS handshake with host '" << GetHost() << "' failed.";
throw ex;
}
pdv = PerfdataValue::Parse(val);
} catch (const std::exception&) {
Log(LogWarning, "InfluxdbWriter")
- << "Ignoring invalid perfdata value: " << val;
+ << "Ignoring invalid perfdata value: " << val;
continue;
}
}
fields->Set("max", pdv->GetMax());
}
if (!pdv->GetUnit().IsEmpty()) {
- fields->Set("unit", pdv->GetUnit());
- }
+ fields->Set("unit", pdv->GetUnit());
+ }
SendMetric(tmpl, pdv->GetLabel(), fields, ts);
}
{
if (value.IsObjectType<InfluxdbInteger>()) {
std::ostringstream os;
- os << static_cast<InfluxdbInteger::Ptr>(value)->GetValue()
- << "i";
+ os << static_cast<InfluxdbInteger::Ptr>(value)->GetValue() << "i";
return os.str();
}
#ifdef I2_DEBUG
Log(LogDebug, "InfluxdbWriter")
- << "Add to metric list: '" << msgbuf.str() << "'.";
+ << "Add to metric list: '" << msgbuf.str() << "'.";
#endif /* I2_DEBUG */
// Buffer the data point
// Flush if we've buffered too much to prevent excessive memory use
if (static_cast<int>(m_DataBuffer.size()) >= GetFlushThreshold()) {
Log(LogDebug, "InfluxdbWriter")
- << "Data buffer overflow writing " << m_DataBuffer.size() << " data points";
+ << "Data buffer overflow writing " << m_DataBuffer.size() << " data points";
try {
Flush();
return;
Log(LogDebug, "InfluxdbWriter")
- << "Timer expired writing " << m_DataBuffer.size() << " data points";
+ << "Timer expired writing " << m_DataBuffer.size() << " data points";
Flush();
}
req.Finish();
} catch (const std::exception& ex) {
Log(LogWarning, "InfluxdbWriter")
- << "Cannot write to TCP socket on host '" << GetHost() << "' port '" << GetPort() << "'.";
+ << "Cannot write to TCP socket on host '" << GetHost() << "' port '" << GetPort() << "'.";
throw ex;
}
; /* Do nothing */
} catch (const std::exception& ex) {
Log(LogWarning, "InfluxdbWriter")
- << "Failed to parse HTTP response from host '" << GetHost() << "' port '" << GetPort() << "': " << DiagnosticInformation(ex);
+ << "Failed to parse HTTP response from host '" << GetHost() << "' port '" << GetPort() << "': " << DiagnosticInformation(ex);
throw ex;
}
if (!resp.Complete) {
Log(LogWarning, "InfluxdbWriter")
- << "Failed to read a complete HTTP response from the InfluxDB server.";
+ << "Failed to read a complete HTTP response from the InfluxDB server.";
return;
}
if (resp.StatusCode != 204) {
Log(LogWarning, "InfluxdbWriter")
- << "Unexpected response code: " << resp.StatusCode;
+ << "Unexpected response code: " << resp.StatusCode;
String contentType = resp.Headers->Get("content-type");
if (contentType != "application/json") {
Log(LogWarning, "InfluxdbWriter")
- << "Unexpected Content-Type: " << contentType;
+ << "Unexpected Content-Type: " << contentType;
return;
}
jsonResponse = JsonDecode(buffer.get());
} catch (...) {
Log(LogWarning, "InfluxdbWriter")
- << "Unable to parse JSON response:\n" << buffer.get();
+ << "Unable to parse JSON response:\n" << buffer.get();
return;
}
String error = jsonResponse->Get("error");
Log(LogCritical, "InfluxdbWriter")
- << "InfluxDB error message:\n" << error;
+ << "InfluxDB error message:\n" << error;
return;
}
ObjectImpl<OpenTsdbWriter>::Start(runtimeCreated);
Log(LogInformation, "OpentsdbWriter")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
m_ReconnectTimer = new Timer();
m_ReconnectTimer->SetInterval(10);
void OpenTsdbWriter::Stop(bool runtimeRemoved)
{
Log(LogInformation, "OpentsdbWriter")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
ObjectImpl<OpenTsdbWriter>::Stop(runtimeRemoved);
}
ObjectImpl<PerfdataWriter>::Start(runtimeCreated);
Log(LogInformation, "PerfdataWriter")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
Checkable::OnNewCheckResult.connect(std::bind(&PerfdataWriter::CheckResultHandler, this, _1, _2));
void PerfdataWriter::Stop(bool runtimeRemoved)
{
Log(LogInformation, "PerfdataWriter")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
ObjectImpl<PerfdataWriter>::Stop(runtimeRemoved);
}
String finalFile = perfdata_path + "." + Convert::ToString((long)Utility::GetTime());
if (rename(temp_path.CStr(), finalFile.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(temp_path));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(temp_path));
}
}
}
if (!output.good())
Log(LogWarning, "PerfdataWriter")
- << "Could not open perfdata file '" << temp_path << "' for writing. Perfdata will be lost.";
+ << "Could not open perfdata file '" << temp_path << "' for writing. Perfdata will be lost.";
}
void PerfdataWriter::RotationTimerHandler(void)
[config] String host_format_template {
default {{{
return "DATATYPE::HOSTPERFDATA\t"
- "TIMET::$host.last_check$\t"
- "HOSTNAME::$host.name$\t"
- "HOSTPERFDATA::$host.perfdata$\t"
- "HOSTCHECKCOMMAND::$host.check_command$\t"
- "HOSTSTATE::$host.state$\t"
- "HOSTSTATETYPE::$host.state_type$";
+ "TIMET::$host.last_check$\t"
+ "HOSTNAME::$host.name$\t"
+ "HOSTPERFDATA::$host.perfdata$\t"
+ "HOSTCHECKCOMMAND::$host.check_command$\t"
+ "HOSTSTATE::$host.state$\t"
+ "HOSTSTATETYPE::$host.state_type$";
}}}
};
[config] String service_format_template {
default {{{
return "DATATYPE::SERVICEPERFDATA\t"
- "TIMET::$service.last_check$\t"
- "HOSTNAME::$host.name$\t"
- "SERVICEDESC::$service.name$\t"
- "SERVICEPERFDATA::$service.perfdata$\t"
- "SERVICECHECKCOMMAND::$service.check_command$\t"
- "HOSTSTATE::$host.state$\t"
- "HOSTSTATETYPE::$host.state_type$\t"
- "SERVICESTATE::$service.state$\t"
- "SERVICESTATETYPE::$service.state_type$";
+ "TIMET::$service.last_check$\t"
+ "HOSTNAME::$host.name$\t"
+ "SERVICEDESC::$service.name$\t"
+ "SERVICEPERFDATA::$service.perfdata$\t"
+ "SERVICECHECKCOMMAND::$service.check_command$\t"
+ "HOSTSTATE::$host.state$\t"
+ "HOSTSTATETYPE::$host.state_type$\t"
+ "SERVICESTATE::$service.state$\t"
+ "SERVICESTATETYPE::$service.state_type$";
}}}
};
objs = FilterUtility::GetFilterTargets(qd, params, user);
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 404,
- "No objects found.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "No objects found.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
return true;
}
} else {
Array::Ptr results = new Array();
Log(LogNotice, "ApiActionHandler")
- << "Running action " << actionName;
+ << "Running action " << actionName;
for (const ConfigObject::Ptr& obj : objs) {
try {
DECLARE_PTR_TYPEDEFS(ActionsHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
using namespace icinga;
ApiAction::ApiAction(const std::vector<String>& types, const Callback& action)
- : m_Types(types), m_Callback(action)
+ : m_Types(types), m_Callback(action)
{ }
Value ApiAction::Invoke(const ConfigObject::Ptr& target, const Dictionary::Ptr& params)
using namespace icinga;
ApiClient::ApiClient(const String& host, const String& port,
- const String& user, const String& password)
- : m_Connection(new HttpClientConnection(host, port, true)), m_User(user), m_Password(password)
+ const String& user, const String& password)
+ : m_Connection(new HttpClientConnection(host, port, true)), m_User(user), m_Password(password)
{
m_Connection->Start();
}
}
void ApiClient::TypesHttpCompletionCallback(HttpRequest& request, HttpResponse& response,
- const TypesCompletionCallback& callback)
+ const TypesCompletionCallback& callback)
{
Dictionary::Ptr result;
callback(boost::exception_ptr(), types);
} catch (const std::exception& ex) {
Log(LogCritical, "ApiClient")
- << "Error while decoding response: " << DiagnosticInformation(ex);
+ << "Error while decoding response: " << DiagnosticInformation(ex);
callback(boost::current_exception(), std::vector<ApiType::Ptr>());
}
}
void ApiClient::GetObjects(const String& pluralType, const ObjectsCompletionCallback& callback,
- const std::vector<String>& names, const std::vector<String>& attrs, const std::vector<String>& joins, bool all_joins) const
+ const std::vector<String>& names, const std::vector<String>& attrs, const std::vector<String>& joins, bool all_joins) const
{
Url::Ptr url = new Url();
url->SetScheme("https");
}
void ApiClient::ObjectsHttpCompletionCallback(HttpRequest& request,
- HttpResponse& response, const ObjectsCompletionCallback& callback)
+ HttpResponse& response, const ObjectsCompletionCallback& callback)
{
Dictionary::Ptr result;
}
void ApiClient::ExecuteScript(const String& session, const String& command, bool sandboxed,
- const ExecuteScriptCompletionCallback& callback) const
+ const ExecuteScriptCompletionCallback& callback) const
{
Url::Ptr url = new Url();
url->SetScheme("https");
}
void ApiClient::ExecuteScriptHttpCompletionCallback(HttpRequest& request,
- HttpResponse& response, const ExecuteScriptCompletionCallback& callback)
+ HttpResponse& response, const ExecuteScriptCompletionCallback& callback)
{
Dictionary::Ptr result;
}
void ApiClient::AutocompleteScript(const String& session, const String& command, bool sandboxed,
- const AutocompleteScriptCompletionCallback& callback) const
+ const AutocompleteScriptCompletionCallback& callback) const
{
Url::Ptr url = new Url();
url->SetScheme("https");
}
void ApiClient::AutocompleteScriptHttpCompletionCallback(HttpRequest& request,
- HttpResponse& response, const AutocompleteScriptCompletionCallback& callback)
+ HttpResponse& response, const AutocompleteScriptCompletionCallback& callback)
{
Dictionary::Ptr result;
DECLARE_PTR_TYPEDEFS(ApiClient);
ApiClient(const String& host, const String& port,
- const String& user, const String& password);
+ const String& user, const String& password);
typedef std::function<void(boost::exception_ptr, const std::vector<ApiType::Ptr>&)> TypesCompletionCallback;
void GetTypes(const TypesCompletionCallback& callback) const;
typedef std::function<void(boost::exception_ptr, const std::vector<ApiObject::Ptr>&)> ObjectsCompletionCallback;
void GetObjects(const String& pluralType, const ObjectsCompletionCallback& callback,
- const std::vector<String>& names = std::vector<String>(),
- const std::vector<String>& attrs = std::vector<String>(),
- const std::vector<String>& joins = std::vector<String>(), bool all_joins = false) const;
+ const std::vector<String>& names = std::vector<String>(),
+ const std::vector<String>& attrs = std::vector<String>(),
+ const std::vector<String>& joins = std::vector<String>(), bool all_joins = false) const;
typedef std::function<void(boost::exception_ptr, const Value&)> ExecuteScriptCompletionCallback;
void ExecuteScript(const String& session, const String& command, bool sandboxed,
- const ExecuteScriptCompletionCallback& callback) const;
+ const ExecuteScriptCompletionCallback& callback) const;
typedef std::function<void(boost::exception_ptr, const Array::Ptr&)> AutocompleteScriptCompletionCallback;
void AutocompleteScript(const String& session, const String& command, bool sandboxed,
- const AutocompleteScriptCompletionCallback& callback) const;
+ const AutocompleteScriptCompletionCallback& callback) const;
private:
HttpClientConnection::Ptr m_Connection;
String m_Password;
static void TypesHttpCompletionCallback(HttpRequest& request,
- HttpResponse& response, const TypesCompletionCallback& callback);
+ HttpResponse& response, const TypesCompletionCallback& callback);
static void ObjectsHttpCompletionCallback(HttpRequest& request,
- HttpResponse& response, const ObjectsCompletionCallback& callback);
+ HttpResponse& response, const ObjectsCompletionCallback& callback);
static void ExecuteScriptHttpCompletionCallback(HttpRequest& request,
- HttpResponse& response, const ExecuteScriptCompletionCallback& callback);
+ HttpResponse& response, const ExecuteScriptCompletionCallback& callback);
static void AutocompleteScriptHttpCompletionCallback(HttpRequest& request,
- HttpResponse& response, const AutocompleteScriptCompletionCallback& callback);
+ HttpResponse& response, const AutocompleteScriptCompletionCallback& callback);
};
}
using namespace icinga;
ApiFunction::ApiFunction(const Callback& function)
-: m_Callback(function)
+ : m_Callback(function)
{ }
Value ApiFunction::Invoke(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& arguments)
Value ApiListener::ConfigUpdateObjectAPIHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params)
{
Log(LogNotice, "ApiListener")
- << "Received update for object: " << JsonEncode(params);
+ << "Received update for object: " << JsonEncode(params);
/* check permissions */
ApiListener::Ptr listener = ApiListener::GetInstance();
/* discard messages if the client is not configured on this node */
if (!endpoint) {
Log(LogNotice, "ApiListener")
- << "Discarding 'config update object' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'config update object' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
/* discard messages if the sender is in a child zone */
if (!Zone::GetLocalZone()->IsChildOf(endpoint->GetZone())) {
Log(LogNotice, "ApiListener")
- << "Discarding 'config update object' message from '"
- << origin->FromClient->GetIdentity() << "' for object '"
- << objName << "' of type '" << objType << "'. Sender is in a child zone.";
+ << "Discarding 'config update object' message from '"
+ << origin->FromClient->GetIdentity() << "' for object '"
+ << objName << "' of type '" << objType << "'. Sender is in a child zone.";
return Empty;
}
/* ignore messages if the endpoint does not accept config */
if (!listener->GetAcceptConfig()) {
Log(LogWarning, "ApiListener")
- << "Ignoring config update from '" << origin->FromClient->GetIdentity() << "' for object '" << objName << "' of type '" << objType << "'. '" << listener->GetName() << "' does not accept config.";
+ << "Ignoring config update from '" << origin->FromClient->GetIdentity() << "' for object '" << objName << "' of type '" << objType << "'. '" << listener->GetName() << "' does not accept config.";
return Empty;
}
if (!ctype) {
Log(LogCritical, "ApiListener")
- << "Config type '" << objType << "' does not exist.";
+ << "Config type '" << objType << "' does not exist.";
return Empty;
}
Array::Ptr errors = new Array();
if (!ConfigObjectUtility::CreateObject(ptype,
- objName, config, errors)) {
+ objName, config, errors)) {
Log(LogCritical, "ApiListener")
- << "Could not create object '" << objName << "':";
+ << "Could not create object '" << objName << "':";
- ObjectLock olock(errors);
+ ObjectLock olock(errors);
for (const String& error : errors) {
- Log(LogCritical, "ApiListener", error);
- }
+ Log(LogCritical, "ApiListener", error);
+ }
return Empty;
}
/* update object attributes if version was changed or if this is a new object */
if (newObject || objVersion <= object->GetVersion()) {
Log(LogNotice, "ApiListener")
- << "Discarding config update for object '" << object->GetName()
- << "': Object version " << std::fixed << object->GetVersion()
- << " is more recent than the received version " << std::fixed << objVersion << ".";
+ << "Discarding config update for object '" << object->GetName()
+ << "': Object version " << std::fixed << object->GetVersion()
+ << " is more recent than the received version " << std::fixed << objVersion << ".";
return Empty;
}
Log(LogNotice, "ApiListener")
- << "Processing config update for object '" << object->GetName()
- << "': Object version " << object->GetVersion()
- << " is older than the received version " << objVersion << ".";
+ << "Processing config update for object '" << object->GetName()
+ << "': Object version " << object->GetVersion()
+ << " is older than the received version " << objVersion << ".";
Dictionary::Ptr modified_attributes = params->Get("modified_attributes");
Value ApiListener::ConfigDeleteObjectAPIHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params)
{
Log(LogNotice, "ApiListener")
- << "Received update for object: " << JsonEncode(params);
+ << "Received update for object: " << JsonEncode(params);
/* check permissions */
ApiListener::Ptr listener = ApiListener::GetInstance();
if (!listener->GetAcceptConfig()) {
Log(LogWarning, "ApiListener")
- << "Ignoring config update. '" << listener->GetName() << "' does not accept config.";
+ << "Ignoring config update. '" << listener->GetName() << "' does not accept config.";
return Empty;
}
if (!endpoint) {
Log(LogNotice, "ApiListener")
- << "Discarding 'config update object' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'config update object' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
/* discard messages if the sender is in a child zone */
if (!Zone::GetLocalZone()->IsChildOf(endpoint->GetZone())) {
Log(LogWarning, "ApiListener")
- << "Discarding 'config update object' message from '"
- << origin->FromClient->GetIdentity() << "'.";
+ << "Discarding 'config update object' message from '"
+ << origin->FromClient->GetIdentity() << "'.";
return Empty;
}
if (!ctype) {
Log(LogCritical, "ApiListener")
- << "Config type '" << params->Get("type") << "' does not exist.";
+ << "Config type '" << params->Get("type") << "' does not exist.";
return Empty;
}
if (!object) {
Log(LogNotice, "ApiListener")
- << "Could not delete non-existent object '" << params->Get("name") << "' with type '" << params->Get("type") << "'.";
+ << "Could not delete non-existent object '" << params->Get("name") << "' with type '" << params->Get("type") << "'.";
return Empty;
}
if (object->GetPackage() != "_api") {
Log(LogCritical, "ApiListener")
- << "Could not delete object '" << object->GetName() << "': Not created by the API.";
+ << "Could not delete object '" << object->GetName() << "': Not created by the API.";
return Empty;
}
}
void ApiListener::UpdateConfigObject(const ConfigObject::Ptr& object, const MessageOrigin::Ptr& origin,
- const JsonRpcConnection::Ptr& client)
+ const JsonRpcConnection::Ptr& client)
{
/* only send objects to zones which have access to the object */
if (client) {
if (target_zone && !target_zone->CanAccessObject(object)) {
Log(LogDebug, "ApiListener")
- << "Not sending 'update config' message to unauthorized zone '" << target_zone->GetName() << "'"
- << " for object: '" << object->GetName() << "'.";
+ << "Not sending 'update config' message to unauthorized zone '" << target_zone->GetName() << "'"
+ << " for object: '" << object->GetName() << "'.";
return;
}
#ifdef I2_DEBUG
Log(LogDebug, "ApiListener")
- << "Sent update for object '" << object->GetName() << "': " << JsonEncode(params);
+ << "Sent update for object '" << object->GetName() << "': " << JsonEncode(params);
#endif /* I2_DEBUG */
if (client)
void ApiListener::DeleteConfigObject(const ConfigObject::Ptr& object, const MessageOrigin::Ptr& origin,
- const JsonRpcConnection::Ptr& client)
+ const JsonRpcConnection::Ptr& client)
{
if (object->GetPackage() != "_api")
return;
if (target_zone && !target_zone->CanAccessObject(object)) {
Log(LogDebug, "ApiListener")
- << "Not sending 'delete config' message to unauthorized zone '" << target_zone->GetName() << "'"
- << " for object: '" << object->GetName() << "'.";
+ << "Not sending 'delete config' message to unauthorized zone '" << target_zone->GetName() << "'"
+ << " for object: '" << object->GetName() << "'.";
return;
}
#ifdef I2_DEBUG
Log(LogDebug, "ApiListener")
- << "Sent delete for object '" << object->GetName() << "': " << JsonEncode(params);
+ << "Sent delete for object '" << object->GetName() << "': " << JsonEncode(params);
#endif /* I2_DEBUG */
if (client)
Zone::Ptr azone = endpoint->GetZone();
Log(LogInformation, "ApiListener")
- << "Syncing runtime objects to endpoint '" << endpoint->GetName() << "'.";
+ << "Syncing runtime objects to endpoint '" << endpoint->GetName() << "'.";
for (const Type::Ptr& type : Type::GetAllTypes()) {
ConfigType *dtype = dynamic_cast<ConfigType *>(type.get());
}
Log(LogInformation, "ApiListener")
- << "Finished syncing runtime objects to endpoint '" << endpoint->GetName() << "'.";
+ << "Finished syncing runtime objects to endpoint '" << endpoint->GetName() << "'.";
}
CONTEXT("Creating config update for file '" + file + "'");
Log(LogNotice, "ApiListener")
- << "Creating config update for file '" << file << "'.";
+ << "Creating config update for file '" << file << "'.";
std::ifstream fp(file.CStr(), std::ifstream::binary);
if (!fp)
/* skip update if our configuration files are more recent */
if (oldTimestamp >= newTimestamp) {
Log(LogNotice, "ApiListener")
- << "Our configuration is more recent than the received configuration update."
- << " Ignoring configuration file update for path '" << configDir << "'. Current timestamp '"
- << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", oldTimestamp) << "' ("
- << std::fixed << std::setprecision(6) << oldTimestamp
- << ") >= received timestamp '"
- << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", newTimestamp) << "' ("
- << newTimestamp << ").";
+ << "Our configuration is more recent than the received configuration update."
+ << " Ignoring configuration file update for path '" << configDir << "'. Current timestamp '"
+ << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", oldTimestamp) << "' ("
+ << std::fixed << std::setprecision(6) << oldTimestamp
+ << ") >= received timestamp '"
+ << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", newTimestamp) << "' ("
+ << newTimestamp << ").";
return false;
}
String path = configDir + "/" + kv.first;
Log(LogInformation, "ApiListener")
- << "Updating configuration file: " << path;
+ << "Updating configuration file: " << path;
/* Sync string content only. */
String content = kv.second;
}
Log(LogInformation, "ApiListener")
- << "Applying configuration file update for path '" << configDir << "' (" << numBytes << " Bytes). Received timestamp '"
- << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", newTimestamp) << "' ("
- << std::fixed << std::setprecision(6) << newTimestamp
- << "), Current timestamp '"
- << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", oldTimestamp) << "' ("
- << oldTimestamp << ").";
+ << "Applying configuration file update for path '" << configDir << "' (" << numBytes << " Bytes). Received timestamp '"
+ << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", newTimestamp) << "' ("
+ << std::fixed << std::setprecision(6) << newTimestamp
+ << "), Current timestamp '"
+ << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", oldTimestamp) << "' ("
+ << oldTimestamp << ").";
ObjectLock xlock(oldConfig);
for (const Dictionary::Pair& kv : oldConfig) {
String oldDir = Application::GetLocalStateDir() + "/lib/icinga2/api/zones/" + zone->GetName();
Log(LogInformation, "ApiListener")
- << "Copying " << sumUpdates << " zone configuration files for zone '" << zone->GetName() << "' to '" << oldDir << "'.";
+ << "Copying " << sumUpdates << " zone configuration files for zone '" << zone->GetName() << "' to '" << oldDir << "'.";
Utility::MkDirP(oldDir, 0700);
continue;
Log(LogInformation, "ApiListener")
- << "Syncing configuration files for " << (zone->IsGlobal() ? "global " : "")
- << "zone '" << zone->GetName() << "' to endpoint '" << endpoint->GetName() << "'.";
+ << "Syncing configuration files for " << (zone->IsGlobal() ? "global " : "")
+ << "zone '" << zone->GetName() << "' to endpoint '" << endpoint->GetName() << "'.";
ConfigDirInformation config = LoadConfigDir(zonesDir + "/" + zone->GetName());
configUpdateV1->Set(zone->GetName(), config.UpdateV1);
if (!listener->GetAcceptConfig()) {
Log(LogWarning, "ApiListener")
- << "Ignoring config update. '" << listener->GetName() << "' does not accept config.";
+ << "Ignoring config update. '" << listener->GetName() << "' does not accept config.";
return Empty;
}
Log(LogInformation, "ApiListener")
- << "Applying config update from endpoint '" << origin->FromClient->GetEndpoint()->GetName()
- << "' of zone '" << GetFromZoneName(origin->FromZone) << "'.";
+ << "Applying config update from endpoint '" << origin->FromClient->GetEndpoint()->GetName()
+ << "' of zone '" << GetFromZoneName(origin->FromZone) << "'.";
Dictionary::Ptr updateV1 = params->Get("update");
Dictionary::Ptr updateV2 = params->Get("update_v2");
if (!zone) {
Log(LogWarning, "ApiListener")
- << "Ignoring config update for unknown zone '" << kv.first << "'.";
+ << "Ignoring config update for unknown zone '" << kv.first << "'.";
continue;
}
if (ConfigCompiler::HasZoneConfigAuthority(kv.first)) {
Log(LogWarning, "ApiListener")
- << "Ignoring config update for zone '" << kv.first << "' because we have an authoritative version of the zone's config.";
+ << "Ignoring config update for zone '" << kv.first << "' because we have an authoritative version of the zone's config.";
continue;
}
if (!oldCertPath.IsEmpty() && stat(oldCertPath.CStr(), &st1) >= 0 && (stat(newCertPath.CStr(), &st2) < 0 || st1.st_mtime > st2.st_mtime)) {
Log(LogWarning, "ApiListener")
- << "Copying '" << oldCertPath << "' certificate file to '" << newCertPath << "'";
+ << "Copying '" << oldCertPath << "' certificate file to '" << newCertPath << "'";
Utility::MkDirP(Utility::DirName(newCertPath), 0700);
Utility::CopyFile(oldCertPath, newCertPath);
cert = GetX509Certificate(defaultCertPath);
} catch (const std::exception&) {
BOOST_THROW_EXCEPTION(ScriptError("Cannot get certificate from cert path: '"
- + defaultCertPath + "'.", GetDebugInfo()));
+ + defaultCertPath + "'.", GetDebugInfo()));
}
try {
SetIdentity(GetCertificateCN(cert));
} catch (const std::exception&) {
BOOST_THROW_EXCEPTION(ScriptError("Cannot get certificate common name from cert path: '"
- + defaultCertPath + "'.", GetDebugInfo()));
+ + defaultCertPath + "'.", GetDebugInfo()));
}
Log(LogInformation, "ApiListener")
- << "My API identity: " << GetIdentity();
+ << "My API identity: " << GetIdentity();
UpdateSSLContext();
}
context = MakeSSLContext(GetDefaultCertPath(), GetDefaultKeyPath(), GetDefaultCaPath());
} catch (const std::exception&) {
BOOST_THROW_EXCEPTION(ScriptError("Cannot make SSL context for cert path: '"
- + GetDefaultCertPath() + "' key path: '" + GetDefaultKeyPath() + "' ca path: '" + GetDefaultCaPath() + "'.", GetDebugInfo()));
+ + GetDefaultCertPath() + "' key path: '" + GetDefaultKeyPath() + "' ca path: '" + GetDefaultCaPath() + "'.", GetDebugInfo()));
}
if (!GetCrlPath().IsEmpty()) {
AddCRLToSSLContext(context, GetCrlPath());
} catch (const std::exception&) {
BOOST_THROW_EXCEPTION(ScriptError("Cannot add certificate revocation list to SSL context for crl path: '"
- + GetCrlPath() + "'.", GetDebugInfo()));
+ + GetCrlPath() + "'.", GetDebugInfo()));
}
}
SetCipherListToSSLContext(context, GetCipherList());
} catch (const std::exception&) {
BOOST_THROW_EXCEPTION(ScriptError("Cannot set cipher list to SSL context for cipher list: '"
- + GetCipherList() + "'.", GetDebugInfo()));
+ + GetCipherList() + "'.", GetDebugInfo()));
}
}
void ApiListener::Start(bool runtimeCreated)
{
Log(LogInformation, "ApiListener")
- << "'" << GetName() << "' started.";
+ << "'" << GetName() << "' started.";
SyncZoneDirs();
/* create the primary JSON-RPC listener */
if (!AddListener(GetBindHost(), GetBindPort())) {
Log(LogCritical, "ApiListener")
- << "Cannot add listener on host '" << GetBindHost() << "' for port '" << GetBindPort() << "'.";
+ << "Cannot add listener on host '" << GetBindHost() << "' for port '" << GetBindPort() << "'.";
Application::Exit(EXIT_FAILURE);
}
ObjectImpl<ApiListener>::Stop(runtimeDeleted);
Log(LogInformation, "ApiListener")
- << "'" << GetName() << "' stopped.";
+ << "'" << GetName() << "' stopped.";
boost::mutex::scoped_lock lock(m_LogLock);
CloseLogFile();
}
Log(LogInformation, "ApiListener")
- << "Adding new listener on port '" << service << "'";
+ << "Adding new listener on port '" << service << "'";
TcpSocket::Ptr server = new TcpSocket();
server->Bind(node, service, AF_UNSPEC);
} catch (const std::exception&) {
Log(LogCritical, "ApiListener")
- << "Cannot bind TCP socket for host '" << node << "' on port '" << service << "'.";
+ << "Cannot bind TCP socket for host '" << node << "' on port '" << service << "'.";
return false;
}
String port = endpoint->GetPort();
Log(LogInformation, "ApiListener")
- << "Reconnecting to endpoint '" << endpoint->GetName() << "' via host '" << host << "' and port '" << port << "'";
+ << "Reconnecting to endpoint '" << endpoint->GetName() << "' via host '" << host << "' and port '" << port << "'";
TcpSocket::Ptr client = new TcpSocket();
info << "Cannot connect to host '" << host << "' on port '" << port << "'";
Log(LogCritical, "ApiListener", info.str());
Log(LogDebug, "ApiListener")
- << info.str() << "\n" << DiagnosticInformation(ex);
+ << info.str() << "\n" << DiagnosticInformation(ex);
}
Log(LogInformation, "ApiListener")
- << "Finished reconnecting to endpoint '" << endpoint->GetName() << "' via host '" << host << "' and port '" << port << "'";
+ << "Finished reconnecting to endpoint '" << endpoint->GetName() << "' via host '" << host << "' and port '" << port << "'";
}
void ApiListener::NewClientHandler(const Socket::Ptr& client, const String& hostname, ConnectionRole role)
NewClientHandlerInternal(client, hostname, role);
} catch (const std::exception& ex) {
Log(LogCritical, "ApiListener")
- << "Exception while handling new API client connection: " << DiagnosticInformation(ex, false);
+ << "Exception while handling new API client connection: " << DiagnosticInformation(ex, false);
Log(LogDebug, "ApiListener")
- << "Exception while handling new API client connection: " << DiagnosticInformation(ex);
+ << "Exception while handling new API client connection: " << DiagnosticInformation(ex);
}
}
tlsStream = new TlsStream(client, hostname, role, m_SSLContext);
} catch (const std::exception&) {
Log(LogCritical, "ApiListener")
- << "Cannot create TLS stream from client connection (" << conninfo << ")";
+ << "Cannot create TLS stream from client connection (" << conninfo << ")";
return;
}
}
tlsStream->Handshake();
} catch (const std::exception&) {
Log(LogCritical, "ApiListener")
- << "Client TLS handshake failed (" << conninfo << ")";
+ << "Client TLS handshake failed (" << conninfo << ")";
return;
}
identity = GetCertificateCN(cert);
} catch (const std::exception&) {
Log(LogCritical, "ApiListener")
- << "Cannot get certificate common name from cert path: '" << GetDefaultCertPath() << "'.";
+ << "Cannot get certificate common name from cert path: '" << GetDefaultCertPath() << "'.";
return;
}
if (identity != hostname) {
Log(LogWarning, "ApiListener")
<< "Unexpected certificate common name while connecting to endpoint '"
- << hostname << "': got '" << identity << "'";
+ << hostname << "': got '" << identity << "'";
return;
} else if (!verify_ok) {
Log(LogWarning, "ApiListener")
}
} else {
Log(LogInformation, "ApiListener")
- << "New client connection " << conninfo << " (no client certificate)";
+ << "New client connection " << conninfo << " (no client certificate)";
}
ClientType ctype;
if (!tlsStream->IsDataAvailable()) {
Log(LogWarning, "ApiListener")
- << "No data received on new API connection for identity '" << identity << "'. Ensure that the remote endpoints are properly configured in a cluster setup.";
+ << "No data received on new API connection for identity '" << identity << "'. Ensure that the remote endpoints are properly configured in a cluster setup.";
return;
}
if (myZone->GetParent() == eZone) {
Log(LogInformation, "ApiListener")
- << "Requesting new certificate for this Icinga instance from endpoint '" << endpoint->GetName() << "'.";
+ << "Requesting new certificate for this Icinga instance from endpoint '" << endpoint->GetName() << "'.";
JsonRpcConnection::SendCertificateRequest(aclient, nullptr, String());
*/
Log(LogInformation, "ApiListener")
- << "Sending config updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
+ << "Sending config updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
/* sync zone file config */
SendConfigUpdate(aclient);
Log(LogInformation, "ApiListener")
- << "Finished sending config file updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
+ << "Finished sending config file updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
/* sync runtime config */
SendRuntimeConfigObjects(aclient);
Log(LogInformation, "ApiListener")
- << "Finished sending runtime config updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
+ << "Finished sending runtime config updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
if (!needSync) {
ObjectLock olock2(endpoint);
}
Log(LogInformation, "ApiListener")
- << "Sending replay log for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
+ << "Sending replay log for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
ReplayLog(aclient);
UpdateObjectAuthority();
Log(LogInformation, "ApiListener")
- << "Finished sending replay log for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
+ << "Finished sending replay log for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
} catch (const std::exception& ex) {
{
ObjectLock olock2(endpoint);
}
Log(LogCritical, "ApiListener")
- << "Error while syncing endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex, false);
+ << "Error while syncing endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex, false);
Log(LogDebug, "ApiListener")
- << "Error while syncing endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex);
+ << "Error while syncing endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex);
}
Log(LogInformation, "ApiListener")
- << "Finished syncing endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
+ << "Finished syncing endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
}
void ApiListener::ApiTimerHandler(void)
if (!need) {
String path = GetApiDir() + "log/" + Convert::ToString(ts);
Log(LogNotice, "ApiListener")
- << "Removing old log file: " << path;
+ << "Removing old log file: " << path;
(void)unlink(path.CStr());
}
}
}
Log(LogNotice, "ApiListener")
- << "Setting log position for identity '" << endpoint->GetName() << "': "
- << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S", ts);
+ << "Setting log position for identity '" << endpoint->GetName() << "': "
+ << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S", ts);
}
}
/* only connect to endpoints in a) the same zone b) our parent zone c) immediate child zones */
if (my_zone != zone && my_zone != zone->GetParent() && zone != my_zone->GetParent()) {
Log(LogDebug, "ApiListener")
- << "Not connecting to Zone '" << zone->GetName()
- << "' because it's not in the same zone, a parent or a child zone.";
+ << "Not connecting to Zone '" << zone->GetName()
+ << "' because it's not in the same zone, a parent or a child zone.";
continue;
}
/* don't connect to ourselves */
if (endpoint == GetLocalEndpoint()) {
Log(LogDebug, "ApiListener")
- << "Not connecting to Endpoint '" << endpoint->GetName() << "' because that's us.";
+ << "Not connecting to Endpoint '" << endpoint->GetName() << "' because that's us.";
continue;
}
/* don't try to connect to endpoints which don't have a host and port */
if (endpoint->GetHost().IsEmpty() || endpoint->GetPort().IsEmpty()) {
Log(LogDebug, "ApiListener")
- << "Not connecting to Endpoint '" << endpoint->GetName()
- << "' because the host/port attributes are missing.";
+ << "Not connecting to Endpoint '" << endpoint->GetName()
+ << "' because the host/port attributes are missing.";
continue;
}
/* don't try to connect if there's already a connection attempt */
if (endpoint->GetConnecting()) {
Log(LogDebug, "ApiListener")
- << "Not connecting to Endpoint '" << endpoint->GetName()
- << "' because we're already trying to connect to it.";
+ << "Not connecting to Endpoint '" << endpoint->GetName()
+ << "' because we're already trying to connect to it.";
continue;
}
/* don't try to connect if we're already connected */
if (endpoint->GetConnected()) {
Log(LogDebug, "ApiListener")
- << "Not connecting to Endpoint '" << endpoint->GetName()
- << "' because we're already connected to it.";
+ << "Not connecting to Endpoint '" << endpoint->GetName()
+ << "' because we're already connected to it.";
continue;
}
if (master)
Log(LogNotice, "ApiListener")
- << "Current zone master: " << master->GetName();
+ << "Current zone master: " << master->GetName();
std::vector<String> names;
for (const Endpoint::Ptr& endpoint : ConfigType::GetObjectsByType<Endpoint>())
names.emplace_back(endpoint->GetName() + " (" + Convert::ToString(endpoint->GetClients().size()) + ")");
Log(LogNotice, "ApiListener")
- << "Connected endpoints: " << Utility::NaturalJoin(names);
+ << "Connected endpoints: " << Utility::NaturalJoin(names);
}
static void CleanupCertificateRequest(const String& path, double expiryTime)
}
void ApiListener::RelayMessage(const MessageOrigin::Ptr& origin,
- const ConfigObject::Ptr& secobj, const Dictionary::Ptr& message, bool log)
+ const ConfigObject::Ptr& secobj, const Dictionary::Ptr& message, bool log)
{
if (!IsActive())
return;
if (!endpoint->GetSyncing()) {
Log(LogNotice, "ApiListener")
- << "Sending message '" << message->Get("method") << "' to '" << endpoint->GetName() << "'";
+ << "Sending message '" << message->Get("method") << "' to '" << endpoint->GetName() << "'";
double maxTs = 0;
/* only relay the message to a) the same zone, b) the parent zone and c) direct child zones. Exception is a global zone. */
if (!targetZone->GetGlobal() &&
- targetZone != myZone &&
- targetZone != myZone->GetParent() &&
- targetZone->GetParent() != myZone) {
+ targetZone != myZone &&
+ targetZone != myZone->GetParent() &&
+ targetZone->GetParent() != myZone) {
return true;
}
}
void ApiListener::SyncRelayMessage(const MessageOrigin::Ptr& origin,
- const ConfigObject::Ptr& secobj, const Dictionary::Ptr& message, bool log)
+ const ConfigObject::Ptr& secobj, const Dictionary::Ptr& message, bool log)
{
double ts = Utility::GetTime();
message->Set("ts", ts);
Log(LogNotice, "ApiListener")
- << "Relaying '" << message->Get("method") << "' message";
+ << "Relaying '" << message->Get("method") << "' message";
if (origin && origin->FromZone)
message->Set("originZone", origin->FromZone->GetName());
if (!fp->good()) {
Log(LogWarning, "ApiListener")
- << "Could not open spool file: " << path;
+ << "Could not open spool file: " << path;
return;
}
continue;
Log(LogNotice, "ApiListener")
- << "Replaying log: " << path;
+ << "Replaying log: " << path;
std::fstream *fp = new std::fstream(path.CStr(), std::fstream::in | std::fstream::binary);
StdioStream::Ptr logStream = new StdioStream(fp, true);
pmessage = JsonDecode(message);
} catch (const std::exception&) {
Log(LogWarning, "ApiListener")
- << "Unexpected end-of-file for cluster log: " << path;
+ << "Unexpected end-of-file for cluster log: " << path;
/* Log files may be incomplete or corrupted. This is perfectly OK. */
break;
count++;
} catch (const std::exception& ex) {
Log(LogWarning, "ApiListener")
- << "Error while replaying log for endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex, false);
+ << "Error while replaying log for endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex, false);
Log(LogDebug, "ApiListener")
- << "Error while replaying log for endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex);
+ << "Error while replaying log for endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex);
break;
}
if (count > 0) {
Log(LogInformation, "ApiListener")
- << "Replayed " << count << " messages.";
+ << "Replayed " << count << " messages.";
}
Log(LogNotice, "ApiListener")
- << "Replayed " << count << " messages.";
+ << "Replayed " << count << " messages.";
if (last_sync) {
{
/* only check endpoints in a) the same zone b) our parent zone c) immediate child zones */
if (my_zone != zone && my_zone != zone->GetParent() && zone != my_zone->GetParent()) {
Log(LogDebug, "ApiListener")
- << "Not checking connection to Zone '" << zone->GetName() << "' because it's not in the same zone, a parent or a child zone.";
+ << "Not checking connection to Zone '" << zone->GetName() << "' because it's not in the same zone, a parent or a child zone.";
continue;
}
if (value != SSL_TXT_TLSV1
#ifdef SSL_TXT_TLSV1_1
- && value != SSL_TXT_TLSV1_1 &&
- value != SSL_TXT_TLSV1_2
+ && value != SSL_TXT_TLSV1_1 &&
+ value != SSL_TXT_TLSV1_2
#endif /* SSL_TXT_TLSV1_1 */
- ) {
+ ) {
String message = "Invalid TLS version. Must be one of '" SSL_TXT_TLSV1 "'";
#ifdef SSL_TXT_TLSV1_1
message += ", '" SSL_TXT_TLSV1_1 "' or '" SSL_TXT_TLSV1_2 "'";
/* configsync */
void UpdateConfigObject(const ConfigObject::Ptr& object, const MessageOrigin::Ptr& origin,
- const JsonRpcConnection::Ptr& client = nullptr);
+ const JsonRpcConnection::Ptr& client = nullptr);
void DeleteConfigObject(const ConfigObject::Ptr& object, const MessageOrigin::Ptr& origin,
- const JsonRpcConnection::Ptr& client = nullptr);
+ const JsonRpcConnection::Ptr& client = nullptr);
void SendRuntimeConfigObjects(const JsonRpcConnection::Ptr& aclient);
void SyncClient(const JsonRpcConnection::Ptr& aclient, const Endpoint::Ptr& endpoint, bool needSync);
response.WriteBody(content.CStr(), content.GetLength());
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 500, "Could not read file.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
}
return true;
DECLARE_PTR_TYPEDEFS(ConfigFilesHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
String ConfigObjectUtility::GetConfigDir(void)
{
return ConfigPackageUtility::GetPackageDir() + "/_api/" +
- ConfigPackageUtility::GetActiveStage("_api");
+ ConfigPackageUtility::GetActiveStage("_api");
}
String ConfigObjectUtility::GetObjectConfigPath(const Type::Ptr& type, const String& fullName)
boost::algorithm::to_lower(typeDir);
return GetConfigDir() + "/conf.d/" + typeDir +
- "/" + EscapeName(fullName) + ".conf";
+ "/" + EscapeName(fullName) + ".conf";
}
String ConfigObjectUtility::EscapeName(const String& name)
}
String ConfigObjectUtility::CreateObjectConfig(const Type::Ptr& type, const String& fullName,
- bool ignoreOnError, const Array::Ptr& templates, const Dictionary::Ptr& attrs)
+ bool ignoreOnError, const Array::Ptr& templates, const Dictionary::Ptr& attrs)
{
NameComposer *nc = dynamic_cast<NameComposer *>(type.get());
Dictionary::Ptr nameParts;
}
bool ConfigObjectUtility::CreateObject(const Type::Ptr& type, const String& fullName,
- const String& config, const Array::Ptr& errors)
+ const String& config, const Array::Ptr& errors)
{
{
boost::mutex::scoped_lock lock(ConfigPackageUtility::GetStaticMutex());
if (errors) {
if (unlink(path.CStr()) < 0 && errno != ENOENT) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("unlink")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("unlink")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
}
for (const boost::exception_ptr& ex : upq.GetExceptions()) {
} catch (const std::exception& ex) {
if (unlink(path.CStr()) < 0 && errno != ENOENT) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("unlink")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("unlink")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
}
if (errors)
if (!parents.empty() && !cascade) {
if (errors)
errors->Add("Object '" + object->GetName() + "' of type '" + type->GetName() +
- "' cannot be deleted because other objects depend on it. "
- "Use cascading delete to delete it anyway.");
+ "' cannot be deleted because other objects depend on it. "
+ "Use cascading delete to delete it anyway.");
return false;
}
if (Utility::PathExists(path)) {
if (unlink(path.CStr()) < 0 && errno != ENOENT) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("unlink")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("unlink")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
}
}
static String GetObjectConfigPath(const Type::Ptr& type, const String& fullName);
static String CreateObjectConfig(const Type::Ptr& type, const String& fullName,
- bool ignoreOnError, const Array::Ptr& templates, const Dictionary::Ptr& attrs);
+ bool ignoreOnError, const Array::Ptr& templates, const Dictionary::Ptr& attrs);
static bool CreateObject(const Type::Ptr& type, const String& fullName,
- const String& config, const Array::Ptr& errors);
+ const String& config, const Array::Ptr& errors);
static bool DeleteObject(const ConfigObject::Ptr& object, bool cascade, const Array::Ptr& errors);
DECLARE_PTR_TYPEDEFS(ConfigPackagesHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
private:
void HandleGet(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response);
+ HttpResponse& response);
void HandlePost(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params);
+ HttpResponse& response, const Dictionary::Ptr& params);
void HandleDelete(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params);
+ HttpResponse& response, const Dictionary::Ptr& params);
};
{
std::vector<String> packages;
Utility::Glob(GetPackageDir() + "/*", std::bind(&ConfigPackageUtility::CollectDirNames,
- _1, std::ref(packages)), GlobDirectory);
+ _1, std::ref(packages)), GlobDirectory);
return packages;
}
String filePath = path + "/" + kv.first;
Log(LogInformation, "ConfigPackageUtility")
- << "Updating configuration file: " << filePath;
+ << "Updating configuration file: " << filePath;
// Pass the directory and generate a dir tree, if it does not already exist
Utility::MkDirP(Utility::DirName(filePath), 0750);
String activePath = GetPackageDir() + "/" + packageName + "/active.conf";
std::ofstream fpActive(activePath.CStr(), std::ofstream::out | std::ostream::binary | std::ostream::trunc);
fpActive << "if (!globals.contains(\"ActiveStages\")) {\n"
- << " globals.ActiveStages = {}\n"
- << "}\n"
- << "\n"
- << "if (globals.contains(\"ActiveStageOverride\")) {\n"
- << " var arr = ActiveStageOverride.split(\":\")\n"
- << " if (arr[0] == \"" << packageName << "\") {\n"
- << " if (arr.len() < 2) {\n"
- << " log(LogCritical, \"Config\", \"Invalid value for ActiveStageOverride\")\n"
- << " } else {\n"
- << " ActiveStages[\"" << packageName << "\"] = arr[1]\n"
- << " }\n"
- << " }\n"
- << "}\n"
- << "\n"
- << "if (!ActiveStages.contains(\"" << packageName << "\")) {\n"
- << " ActiveStages[\"" << packageName << "\"] = \"" << stageName << "\"\n"
- << "}\n";
+ << " globals.ActiveStages = {}\n"
+ << "}\n"
+ << "\n"
+ << "if (globals.contains(\"ActiveStageOverride\")) {\n"
+ << " var arr = ActiveStageOverride.split(\":\")\n"
+ << " if (arr[0] == \"" << packageName << "\") {\n"
+ << " if (arr.len() < 2) {\n"
+ << " log(LogCritical, \"Config\", \"Invalid value for ActiveStageOverride\")\n"
+ << " } else {\n"
+ << " ActiveStages[\"" << packageName << "\"] = arr[1]\n"
+ << " }\n"
+ << " }\n"
+ << "}\n"
+ << "\n"
+ << "if (!ActiveStages.contains(\"" << packageName << "\")) {\n"
+ << " ActiveStages[\"" << packageName << "\"] = \"" << stageName << "\"\n"
+ << "}\n";
fpActive.close();
}
String path = GetPackageDir() + "/" + packageName + "/" + stageName + "/include.conf";
std::ofstream fp(path.CStr(), std::ofstream::out | std::ostream::binary | std::ostream::trunc);
fp << "include \"../active.conf\"\n"
- << "if (ActiveStages[\"" << packageName << "\"] == \"" << stageName << "\") {\n"
- << " include_recursive \"conf.d\"\n"
- << " include_zones \"" << packageName << "\", \"zones.d\"\n"
- << "}\n";
+ << "if (ActiveStages[\"" << packageName << "\"] == \"" << stageName << "\") {\n"
+ << " include_recursive \"conf.d\"\n"
+ << " include_zones \"" << packageName << "\", \"zones.d\"\n"
+ << "}\n";
fp.close();
}
Application::RequestRestart();
} else {
Log(LogCritical, "ConfigPackageUtility")
- << "Config validation failed for package '"
- << packageName << "' and stage '" << stageName << "'.";
+ << "Config validation failed for package '"
+ << packageName << "' and stage '" << stageName << "'.";
}
}
int rc = lstat(path.CStr(), &statbuf);
if (rc < 0)
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("lstat")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("lstat")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
paths.emplace_back(path, S_ISDIR(statbuf.st_mode));
#else /* _WIN32 */
int rc = _stat(path.CStr(), &statbuf);
if (rc < 0)
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("_stat")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(path));
+ << boost::errinfo_api_function("_stat")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(path));
paths.emplace_back(path, ((statbuf.st_mode & S_IFMT) == S_IFDIR));
#endif /* _WIN32 */
ConfigPackageUtility::DeleteStage(packageName, stageName);
} catch (const std::exception& ex) {
return HttpUtility::SendJsonError(response, 500,
- "Failed to delete stage.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "Failed to delete stage.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
}
Dictionary::Ptr result1 = new Dictionary();
DECLARE_PTR_TYPEDEFS(ConfigStagesHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
private:
void HandleGet(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params);
+ HttpResponse& response, const Dictionary::Ptr& params);
void HandlePost(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params);
+ HttpResponse& response, const Dictionary::Ptr& params);
void HandleDelete(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params);
+ HttpResponse& response, const Dictionary::Ptr& params);
};
}
bool ConsoleHandler::ExecuteScriptHelper(HttpRequest& request, HttpResponse& response,
- const String& command, const String& session, bool sandboxed)
+ const String& command, const String& session, bool sandboxed)
{
Log(LogNotice, "Console")
- << "Executing expression: " << command;
+ << "Executing expression: " << command;
EnsureFrameCleanupTimer();
std::ostringstream msgbuf;
msgbuf << di.Path << ": " << lsf.Lines[di.Path] << "\n"
- << String(di.Path.GetLength() + 2, ' ')
- << String(di.FirstColumn, ' ') << String(di.LastColumn - di.FirstColumn + 1, '^') << "\n"
- << ex.what() << "\n";
+ << String(di.Path.GetLength() + 2, ' ')
+ << String(di.FirstColumn, ' ') << String(di.LastColumn - di.FirstColumn + 1, '^') << "\n"
+ << ex.what() << "\n";
resultInfo->Set("code", 500);
resultInfo->Set("status", String(msgbuf.str()));
}
bool ConsoleHandler::AutocompleteScriptHelper(HttpRequest& request, HttpResponse& response,
- const String& command, const String& session, bool sandboxed)
+ const String& command, const String& session, bool sandboxed)
{
Log(LogInformation, "Console")
- << "Auto-completing expression: " << command;
+ << "Auto-completing expression: " << command;
EnsureFrameCleanupTimer();
DECLARE_PTR_TYPEDEFS(ConsoleHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
static std::vector<String> GetAutocompletionSuggestions(const String& word, ScriptFrame& frame);
private:
static bool ExecuteScriptHelper(HttpRequest& request, HttpResponse& response,
- const String& command, const String& session, bool sandboxed);
+ const String& command, const String& session, bool sandboxed);
static bool AutocompleteScriptHelper(HttpRequest& request, HttpResponse& response,
- const String& command, const String& session, bool sandboxed);
+ const String& command, const String& session, bool sandboxed);
};
DECLARE_PTR_TYPEDEFS(CreateObjectHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
objs = FilterUtility::GetFilterTargets(qd, params, user);
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 404,
- "No objects found.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "No objects found.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
return true;
}
DECLARE_PTR_TYPEDEFS(DeleteObjectHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
boost::signals2::signal<void(const Endpoint::Ptr&, const JsonRpcConnection::Ptr&)> Endpoint::OnDisconnected;
Endpoint::Endpoint(void)
- : m_MessagesSent(60), m_MessagesReceived(60), m_BytesSent(60), m_BytesReceived(60)
+ : m_MessagesSent(60), m_MessagesReceived(60), m_BytesSent(60), m_BytesReceived(60)
{ }
void Endpoint::OnAllConfigLoaded(void)
if (!m_Zone)
BOOST_THROW_EXCEPTION(ScriptError("Endpoint '" + GetName() +
- "' does not belong to a zone.", GetDebugInfo()));
+ "' does not belong to a zone.", GetDebugInfo()));
}
void Endpoint::SetCachedZone(const Zone::Ptr& zone)
{
if (m_Zone)
BOOST_THROW_EXCEPTION(ScriptError("Endpoint '" + GetName()
- + "' is in more than one zone.", GetDebugInfo()));
+ + "' is in more than one zone.", GetDebugInfo()));
m_Zone = zone;
}
m_Clients.erase(client);
Log(LogWarning, "ApiListener")
- << "Removing API client for endpoint '" << GetName() << "'. " << m_Clients.size() << " API clients left.";
+ << "Removing API client for endpoint '" << GetName() << "'. " << m_Clients.size() << " API clients left.";
SetConnecting(false);
}
using namespace icinga;
EventQueue::EventQueue(const String& name)
- : m_Name(name)
+ : m_Name(name)
{ }
bool EventQueue::CanProcessEvent(const String& type) const
return;
} catch (const std::exception& ex) {
Log(LogWarning, "EventQueue")
- << "Error occurred while evaluating event filter for queue '" << m_Name << "': " << DiagnosticInformation(ex);
+ << "Error occurred while evaluating event filter for queue '" << m_Name << "': " << DiagnosticInformation(ex);
return;
}
DECLARE_PTR_TYPEDEFS(EventsHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
}
bool FilterUtility::EvaluateFilter(ScriptFrame& frame, Expression *filter,
- const Object::Ptr& target, const String& variableName)
+ const Object::Ptr& target, const String& variableName)
{
if (!filter)
return true;
}
static void FilteredAddTarget(ScriptFrame& permissionFrame, Expression *permissionFilter,
- ScriptFrame& frame, Expression *ufilter, std::vector<Value>& result, const String& variableName, const Object::Ptr& target)
+ ScriptFrame& frame, Expression *ufilter, std::vector<Value>& result, const String& variableName, const Object::Ptr& target)
{
if (FilterUtility::EvaluateFilter(permissionFrame, permissionFilter, target, variableName) && FilterUtility::EvaluateFilter(frame, ufilter, target, variableName))
result.push_back(target);
if (!foundPermission) {
Log(LogWarning, "FilterUtility")
- << "Missing permission: " << requiredPermission;
+ << "Missing permission: " << requiredPermission;
BOOST_THROW_EXCEPTION(ScriptError("Missing permission: " + requiredPermission));
}
frame.Self = uvars;
provider->FindTargets(type, std::bind(&FilteredAddTarget,
- std::ref(permissionFrame), permissionFilter,
- std::ref(frame), &*ufilter, std::ref(result), variableName, _1));
+ std::ref(permissionFrame), permissionFilter,
+ std::ref(frame), &*ufilter, std::ref(result), variableName, _1));
}
return result;
static Type::Ptr TypeFromPluralName(const String& pluralName);
static void CheckPermission(const ApiUser::Ptr& user, const String& permission, Expression **filter = nullptr);
static std::vector<Value> GetFilterTargets(const QueryDescription& qd, const Dictionary::Ptr& query,
- const ApiUser::Ptr& user, const String& variableName = String());
+ const ApiUser::Ptr& user, const String& variableName = String());
static bool EvaluateFilter(ScriptFrame& frame, Expression *filter,
- const Object::Ptr& target, const String& variableName = String());
+ const Object::Ptr& target, const String& variableName = String());
};
}
using namespace icinga;
StreamReadStatus HttpChunkedEncoding::ReadChunkFromStream(const Stream::Ptr& stream,
- char **data, size_t *size, ChunkReadContext& context, bool may_wait)
+ char **data, size_t *size, ChunkReadContext& context, bool may_wait)
{
if (context.LengthIndicator == -1) {
String line;
int LengthIndicator;
ChunkReadContext(StreamReadContext& scontext)
- : StreamContext(scontext), LengthIndicator(-1)
+ : StreamContext(scontext), LengthIndicator(-1)
{ }
};
struct I2_REMOTE_API HttpChunkedEncoding
{
static StreamReadStatus ReadChunkFromStream(const Stream::Ptr& stream,
- char **data, size_t *size, ChunkReadContext& ccontext, bool may_wait = false);
+ char **data, size_t *size, ChunkReadContext& ccontext, bool may_wait = false);
static void WriteChunkToStream(const Stream::Ptr& stream, const char *data, size_t count);
};
else
ASSERT(!"Non-TLS HTTP connections not supported.");
/* m_Stream = new NetworkStream(socket);
- -- does not currently work because the NetworkStream class doesn't support async I/O */
+ * -- does not currently work because the NetworkStream class doesn't support async I/O
+ */
/* the stream holds an owning reference to this object through the callback we're registering here */
m_Stream->RegisterDataHandler(std::bind(&HttpClientConnection::DataAvailableHandler, HttpClientConnection::Ptr(this), _1));
; /* empty loop body */
} catch (const std::exception& ex) {
Log(LogWarning, "HttpClientConnection")
- << "Error while reading Http response: " << DiagnosticInformation(ex);
+ << "Error while reading Http response: " << DiagnosticInformation(ex);
close = true;
Disconnect();
}
void HttpClientConnection::SubmitRequest(const std::shared_ptr<HttpRequest>& request,
- const HttpCompletionCallback& callback)
+ const HttpCompletionCallback& callback)
{
m_Requests.emplace_back(request, callback);
request->Finish();
using namespace icinga;
HttpRequest::HttpRequest(const Stream::Ptr& stream)
- : Complete(false),
- ProtocolVersion(HttpVersion11),
- Headers(new Dictionary()),
- m_Stream(stream),
- m_State(HttpRequestStart)
+ : Complete(false),
+ ProtocolVersion(HttpVersion11),
+ Headers(new Dictionary()),
+ m_Stream(stream),
+ m_State(HttpRequestStart)
{ }
bool HttpRequest::Parse(StreamReadContext& src, bool may_wait)
std::vector<String> tokens;
boost::algorithm::split(tokens, line, boost::is_any_of(" "));
Log(LogDebug, "HttpRequest")
- << "line: " << line << ", tokens: " << tokens.size();
+ << "line: " << line << ", tokens: " << tokens.size();
if (tokens.size() != 3)
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid HTTP request"));
using namespace icinga;
HttpResponse::HttpResponse(const Stream::Ptr& stream, const HttpRequest& request)
- : Complete(false), m_State(HttpResponseStart), m_Request(request), m_Stream(stream)
+ : Complete(false), m_State(HttpResponseStart), m_Request(request), m_Stream(stream)
{ }
void HttpResponse::SetStatus(int code, const String& message)
if (m_CurrentRequest.Complete) {
m_RequestQueue.Enqueue(std::bind(&HttpServerConnection::ProcessMessageAsync,
- HttpServerConnection::Ptr(this), m_CurrentRequest));
+ HttpServerConnection::Ptr(this), m_CurrentRequest));
m_Seen = Utility::GetTime();
m_PendingRequests++;
String requestUrl = request.RequestUrl->Format();
Log(LogInformation, "HttpServerConnection")
- << "Request: " << request.RequestMethod << " " << requestUrl
- << " (from " << m_Stream->GetSocket()->GetPeerAddress() << ", user: " << (user ? user->GetName() : "<unauthenticated>") << ")";
+ << "Request: " << request.RequestMethod << " " << requestUrl
+ << " (from " << m_Stream->GetSocket()->GetPeerAddress() << ", user: " << (user ? user->GetName() : "<unauthenticated>") << ")";
HttpResponse response(m_Stream, request);
response.WriteBody(msg.CStr(), msg.GetLength());
} else if (!user) {
Log(LogWarning, "HttpServerConnection")
- << "Unauthorized request: " << request.RequestMethod << " " << requestUrl;
+ << "Unauthorized request: " << request.RequestMethod << " " << requestUrl;
response.SetStatus(401, "Unauthorized");
response.AddHeader("WWW-Authenticate", "Basic realm=\"Icinga 2\"");
HttpHandler::ProcessRequest(user, request, response);
} catch (const std::exception& ex) {
Log(LogCritical, "HttpServerConnection")
- << "Unhandled exception while processing Http request: " << DiagnosticInformation(ex);
+ << "Unhandled exception while processing Http request: " << DiagnosticInformation(ex);
response.SetStatus(503, "Unhandled exception");
String errorInfo = DiagnosticInformation(ex);
; /* empty loop body */
} catch (const std::exception& ex) {
Log(LogWarning, "HttpServerConnection")
- << "Error while reading Http request: " << DiagnosticInformation(ex);
+ << "Error while reading Http request: " << DiagnosticInformation(ex);
close = true;
}
{
if (m_Seen < Utility::GetTime() - 10 && m_PendingRequests == 0) {
Log(LogInformation, "HttpServerConnection")
- << "No messages for Http connection have been received in the last 10 seconds.";
+ << "No messages for Http connection have been received in the last 10 seconds.";
Disconnect();
}
}
if (!body.IsEmpty()) {
#ifdef I2_DEBUG
Log(LogDebug, "HttpUtility")
- << "Request body: '" << body << "'";
+ << "Request body: '" << body << "'";
#endif /* I2_DEBUG */
result = JsonDecode(body);
}
}
void HttpUtility::SendJsonError(HttpResponse& response, const int code,
- const String& info, const String& diagnosticInformation)
+ const String& info, const String& diagnosticInformation)
{
Dictionary::Ptr result = new Dictionary();
response.SetStatus(code, HttpUtility::GetErrorNameByCode(code));
static void SendJsonBody(HttpResponse& response, const Value& val);
static Value GetLastParameter(const Dictionary::Ptr& params, const String& key);
static void SendJsonError(HttpResponse& response, const int code,
- const String& verbose = String(), const String& diagnosticInformation = String());
+ const String& verbose = String(), const String& diagnosticInformation = String());
private:
static String GetErrorNameByCode(int code);
DECLARE_PTR_TYPEDEFS(InfoHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
if (!value.IsObjectType<Dictionary>()) {
BOOST_THROW_EXCEPTION(std::invalid_argument("JSON-RPC"
- " message must be a dictionary."));
+ " message must be a dictionary."));
}
return value;
for (const JsonRpcConnection::Ptr& client : endpoint->GetClients()) {
if (client->m_NextHeartbeat != 0 && client->m_NextHeartbeat < Utility::GetTime()) {
Log(LogWarning, "JsonRpcConnection")
- << "Client for endpoint '" << endpoint->GetName() << "' has requested "
- << "heartbeat message but hasn't responded in time. Closing connection.";
+ << "Client for endpoint '" << endpoint->GetName() << "' has requested "
+ << "heartbeat message but hasn't responded in time. Closing connection.";
client->Disconnect();
continue;
bool signedByCA = VerifyCertificate(cacert, cert);
Log(LogInformation, "JsonRpcConnection")
- << "Received certificate request for CN '" << cn << "'"
- << (signedByCA ? "" : " not") << " signed by our CA.";
+ << "Received certificate request for CN '" << cn << "'"
+ << (signedByCA ? "" : " not") << " signed by our CA.";
if (signedByCA) {
time_t now;
if (X509_cmp_time(X509_get_notBefore(cert.get()), &forceRenewalEnd) != -1 && X509_cmp_time(X509_get_notAfter(cert.get()), &renewalStart) != -1) {
Log(LogInformation, "JsonRpcConnection")
- << "The certificate for CN '" << cn << "' cannot be renewed yet.";
+ << "The certificate for CN '" << cn << "' cannot be renewed yet.";
result->Set("status_code", 1);
result->Set("error", "The certificate for CN '" + cn + "' cannot be renewed yet.");
return result;
result->Set("error", "Could not calculate fingerprint for the X509 certificate for CN '" + cn + "'.");
Log(LogWarning, "JsonRpcConnection")
- << "Could not calculate fingerprint for the X509 certificate requested for CN '"
- << cn << "'.";
+ << "Could not calculate fingerprint for the X509 certificate requested for CN '"
+ << cn << "'.";
return result;
}
if (!certResponse.IsEmpty()) {
Log(LogInformation, "JsonRpcConnection")
- << "Sending certificate response for CN '" << cn
- << "' to endpoint '" << client->GetIdentity() << "'.";
+ << "Sending certificate response for CN '" << cn
+ << "' to endpoint '" << client->GetIdentity() << "'.";
result->Set("cert", certResponse);
result->Set("status_code", 0);
if (ticket != realTicket) {
Log(LogWarning, "JsonRpcConnection")
- << "Ticket for CN '" << cn << "' is invalid.";
+ << "Ticket for CN '" << cn << "' is invalid.";
result->Set("status_code", 1);
result->Set("error", "Invalid ticket for CN '" + cn + "'.");
* a certificate it wouldn't be able to use to connect to us anyway) */
if (!VerifyCertificate(cacert, newcert)) {
Log(LogWarning, "JsonRpcConnection")
- << "The CA in '" << listener->GetDefaultCaPath() << "' does not match the CA which Icinga uses "
- << "for its own cluster connections. This is most likely a configuration problem.";
+ << "The CA in '" << listener->GetDefaultCaPath() << "' does not match the CA which Icinga uses "
+ << "for its own cluster connections. This is most likely a configuration problem.";
goto delayed_request;
}
/* Send the signed certificate update. */
Log(LogInformation, "JsonRpcConnection")
- << "Sending certificate response for CN '" << cn << "' to endpoint '"
- << client->GetIdentity() << "'" << (!ticket.IsEmpty() ? " (auto-signing ticket)" : "" ) << ".";
+ << "Sending certificate response for CN '" << cn << "' to endpoint '"
+ << client->GetIdentity() << "'" << (!ticket.IsEmpty() ? " (auto-signing ticket)" : "" ) << ".";
result->Set("cert", CertificateToString(newcert));
result->Set("error", "Certificate request for CN '" + cn + "' is pending. Waiting for approval from the parent Icinga instance.");
Log(LogInformation, "JsonRpcConnection")
- << "Certificate request for CN '" << cn << "' is pending. Waiting for approval.";
+ << "Certificate request for CN '" << cn << "' is pending. Waiting for approval.";
return result;
}
{
if (origin->FromZone && !Zone::GetLocalZone()->IsChildOf(origin->FromZone)) {
Log(LogWarning, "ClusterEvents")
- << "Discarding 'update certificate' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
+ << "Discarding 'update certificate' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
return Empty;
}
String cn = GetCertificateCN(newCert);
Log(LogInformation, "JsonRpcConnection")
- << "Received certificate update message for CN '" << cn << "'";
+ << "Received certificate update message for CN '" << cn << "'";
/* Check if this is a certificate update for a subordinate instance. */
std::shared_ptr<EVP_PKEY> oldKey = std::shared_ptr<EVP_PKEY>(X509_get_pubkey(oldCert.get()), EVP_PKEY_free);
std::shared_ptr<EVP_PKEY> newKey = std::shared_ptr<EVP_PKEY>(X509_get_pubkey(newCert.get()), EVP_PKEY_free);
if (X509_NAME_cmp(X509_get_subject_name(oldCert.get()), X509_get_subject_name(newCert.get())) != 0 ||
- EVP_PKEY_cmp(oldKey.get(), newKey.get()) != 1) {
+ EVP_PKEY_cmp(oldKey.get(), newKey.get()) != 1) {
String certFingerprint = params->Get("fingerprint_request");
/* Validate the fingerprint format. */
if (!boost::regex_match(certFingerprint.GetData(), expr)) {
Log(LogWarning, "JsonRpcConnection")
- << "Endpoint '" << origin->FromClient->GetIdentity() << "' sent an invalid certificate fingerprint: '"
- << certFingerprint << "' for CN '" << cn << "'.";
+ << "Endpoint '" << origin->FromClient->GetIdentity() << "' sent an invalid certificate fingerprint: '"
+ << certFingerprint << "' for CN '" << cn << "'.";
return Empty;
}
/* Save the received signed certificate request to disk. */
if (Utility::PathExists(requestPath)) {
Log(LogInformation, "JsonRpcConnection")
- << "Saved certificate update for CN '" << cn << "'";
+ << "Saved certificate update for CN '" << cn << "'";
Dictionary::Ptr request = Utility::LoadJsonFile(requestPath);
request->Set("cert_response", cert);
String caPath = listener->GetDefaultCaPath();
Log(LogInformation, "JsonRpcConnection")
- << "Updating CA certificate in '" << caPath << "'.";
+ << "Updating CA certificate in '" << caPath << "'.";
std::fstream cafp;
String tempCaPath = Utility::CreateTempFile(caPath + ".XXXXXX", 0644, cafp);
if (rename(tempCaPath.CStr(), caPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempCaPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempCaPath));
}
/* Update signed certificate. */
String certPath = listener->GetDefaultCertPath();
Log(LogInformation, "JsonRpcConnection")
- << "Updating client certificate for CN '" << cn << "' in '" << certPath << "'.";
+ << "Updating client certificate for CN '" << cn << "' in '" << certPath << "'.";
std::fstream certfp;
String tempCertPath = Utility::CreateTempFile(certPath + ".XXXXXX", 0644, certfp);
if (rename(tempCertPath.CStr(), certPath.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("rename")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(tempCertPath));
+ << boost::errinfo_api_function("rename")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(tempCertPath));
}
/* Remove ticket for successful signing request. */
if (unlink(ticketPath.CStr()) < 0 && errno != ENOENT) {
BOOST_THROW_EXCEPTION(posix_error()
- << boost::errinfo_api_function("unlink")
- << boost::errinfo_errno(errno)
- << boost::errinfo_file_name(ticketPath));
+ << boost::errinfo_api_function("unlink")
+ << boost::errinfo_errno(errno)
+ << boost::errinfo_file_name(ticketPath));
}
/* Update the certificates at runtime and reconnect all endpoints. */
Log(LogInformation, "JsonRpcConnection")
- << "Updating the client certificate for CN '" << cn << "' at runtime and reconnecting the endpoints.";
+ << "Updating the client certificate for CN '" << cn << "' at runtime and reconnecting the endpoints.";
listener->UpdateSSLContext();
static Timer::Ptr l_HeartbeatTimer;
JsonRpcConnection::JsonRpcConnection(const String& identity, bool authenticated,
- const TlsStream::Ptr& stream, ConnectionRole role)
+ const TlsStream::Ptr& stream, ConnectionRole role)
: m_ID(l_JsonRpcConnectionNextID++), m_Identity(identity), m_Authenticated(authenticated), m_Stream(stream),
- m_Role(role), m_Timestamp(Utility::GetTime()), m_Seen(Utility::GetTime()),
- m_NextHeartbeat(0), m_HeartbeatTimeout(0)
+ m_Role(role), m_Timestamp(Utility::GetTime()), m_Seen(Utility::GetTime()), m_NextHeartbeat(0), m_HeartbeatTimeout(0)
{
boost::call_once(l_JsonRpcConnectionOnceFlag, &JsonRpcConnection::StaticInitialize);
std::ostringstream info;
info << "Error while sending JSON-RPC message for identity '" << m_Identity << "'";
Log(LogWarning, "JsonRpcConnection")
- << info.str() << "\n" << DiagnosticInformation(ex);
+ << info.str() << "\n" << DiagnosticInformation(ex);
Disconnect();
}
void JsonRpcConnection::Disconnect(void)
{
Log(LogWarning, "JsonRpcConnection")
- << "API client disconnected for identity '" << m_Identity << "'";
+ << "API client disconnected for identity '" << m_Identity << "'";
m_Stream->Close();
MessageHandler(jsonString);
} catch (const std::exception& ex) {
Log(LogWarning, "JsonRpcConnection")
- << "Error while reading JSON-RPC message for identity '" << m_Identity
- << "': " << DiagnosticInformation(ex);
+ << "Error while reading JSON-RPC message for identity '" << m_Identity
+ << "': " << DiagnosticInformation(ex);
Disconnect();
return;
Log(LogWarning, "JsonRpcConnection",
- "We received a JSON-RPC response message. This should never happen because we're only ever sending notifications.");
+ "We received a JSON-RPC response message. This should never happen because we're only ever sending notifications.");
return;
}
String method = vmethod;
Log(LogNotice, "JsonRpcConnection")
- << "Received '" << method << "' message from '" << m_Identity << "'";
+ << "Received '" << method << "' message from '" << m_Identity << "'";
Dictionary::Ptr resultMessage = new Dictionary();
if (!afunc) {
Log(LogNotice, "JsonRpcConnection")
- << "Call to non-existent function '" << method << "' from endpoint '" << m_Identity << "'.";
+ << "Call to non-existent function '" << method << "' from endpoint '" << m_Identity << "'.";
} else {
resultMessage->Set("result", afunc->Invoke(origin, message->Get("params")));
}
String diagInfo = DiagnosticInformation(ex);
resultMessage->Set("error", diagInfo);
Log(LogWarning, "JsonRpcConnection")
- << "Error while processing message for identity '" << m_Identity << "'\n" << diagInfo;
+ << "Error while processing message for identity '" << m_Identity << "'\n" << diagInfo;
}
if (message->Contains("id")) {
; /* empty loop body */
} catch (const std::exception& ex) {
Log(LogWarning, "JsonRpcConnection")
- << "Error while reading JSON-RPC message for identity '" << m_Identity
- << "': " << DiagnosticInformation(ex);
+ << "Error while reading JSON-RPC message for identity '" << m_Identity
+ << "': " << DiagnosticInformation(ex);
Disconnect();
{
if (m_Seen < Utility::GetTime() - 60 && (!m_Endpoint || !m_Endpoint->GetSyncing())) {
Log(LogInformation, "JsonRpcConnection")
- << "No messages for identity '" << m_Identity << "' have been received in the last 60 seconds.";
+ << "No messages for identity '" << m_Identity << "' have been received in the last 60 seconds.";
Disconnect();
}
}
objs = FilterUtility::GetFilterTargets(qd, params, user);
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 404,
- "No objects found.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "No objects found.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
return true;
}
if (attrsVal.GetReflectionType() != Dictionary::TypeInstance) {
HttpUtility::SendJsonError(response, 400,
- "Invalid type for 'attrs' attribute specified. Dictionary type is required.", Empty);
+ "Invalid type for 'attrs' attribute specified. Dictionary type is required.", Empty);
return true;
}
DECLARE_PTR_TYPEDEFS(ModifyObjectHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
REGISTER_URLHANDLER("/v1/objects", ObjectQueryHandler);
Dictionary::Ptr ObjectQueryHandler::SerializeObjectAttrs(const Object::Ptr& object,
- const String& attrPrefix, const Array::Ptr& attrs, bool isJoin, bool allAttrs)
+ const String& attrPrefix, const Array::Ptr& attrs, bool isJoin, bool allAttrs)
{
Type::Ptr type = object->GetReflectionType();
uattrs = params->Get("attrs");
} catch (const std::exception&) {
HttpUtility::SendJsonError(response, 400,
- "Invalid type for 'attrs' attribute specified. Array type is required.", Empty);
- return true;
+ "Invalid type for 'attrs' attribute specified. Array type is required.", Empty);
+ return true;
}
try {
ujoins = params->Get("joins");
} catch (const std::exception&) {
HttpUtility::SendJsonError(response, 400,
- "Invalid type for 'joins' attribute specified. Array type is required.", Empty);
- return true;
+ "Invalid type for 'joins' attribute specified. Array type is required.", Empty);
+ return true;
}
try {
umetas = params->Get("meta");
} catch (const std::exception&) {
HttpUtility::SendJsonError(response, 400,
- "Invalid type for 'meta' attribute specified. Array type is required.", Empty);
+ "Invalid type for 'meta' attribute specified. Array type is required.", Empty);
return true;
}
objs = FilterUtility::GetFilterTargets(qd, params, user);
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 404,
- "No objects found.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "No objects found.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
return true;
}
DECLARE_PTR_TYPEDEFS(ObjectQueryHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
private:
static Dictionary::Ptr SerializeObjectAttrs(const Object::Ptr& object, const String& attrPrefix,
- const Array::Ptr& attrs, bool isJoin, bool allAttrs);
+ const Array::Ptr& attrs, bool isJoin, bool allAttrs);
};
}
if (Utility::PathExists(caCertFile) && Utility::PathExists(caKeyFile)) {
Log(LogCritical, "cli")
- << "CA files '" << caCertFile << "' and '" << caKeyFile << "' already exist.";
+ << "CA files '" << caCertFile << "' and '" << caKeyFile << "' already exist.";
return 1;
}
if (!req) {
Log(LogCritical, "SSL")
- << "Could not read X509 certificate request from '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
+ << "Could not read X509 certificate request from '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
return 1;
}
client->Connect(host, port);
} catch (const std::exception& ex) {
Log(LogCritical, "pki")
- << "Cannot connect to host '" << host << "' on port '" << port << "'";
+ << "Cannot connect to host '" << host << "' on port '" << port << "'";
Log(LogDebug, "pki")
- << "Cannot connect to host '" << host << "' on port '" << port << "':\n" << DiagnosticInformation(ex);
+ << "Cannot connect to host '" << host << "' on port '" << port << "':\n" << DiagnosticInformation(ex);
return std::shared_ptr<X509>();
}
sslContext = MakeSSLContext();
} catch (const std::exception& ex) {
Log(LogCritical, "pki")
- << "Cannot make SSL context.";
+ << "Cannot make SSL context.";
Log(LogDebug, "pki")
- << "Cannot make SSL context:\n" << DiagnosticInformation(ex);
+ << "Cannot make SSL context:\n" << DiagnosticInformation(ex);
return std::shared_ptr<X509>();
}
if (fpcert.fail()) {
Log(LogCritical, "pki")
- << "Could not write certificate to file '" << trustedfile << "'.";
+ << "Could not write certificate to file '" << trustedfile << "'.";
return 1;
}
Log(LogInformation, "pki")
- << "Writing certificate to file '" << trustedfile << "'.";
+ << "Writing certificate to file '" << trustedfile << "'.";
return 0;
}
}
int PkiUtility::RequestCertificate(const String& host, const String& port, const String& keyfile,
- const String& certfile, const String& cafile, const std::shared_ptr<X509>& trustedCert, const String& ticket)
+ const String& certfile, const String& cafile, const std::shared_ptr<X509>& trustedCert, const String& ticket)
{
TcpSocket::Ptr client = new TcpSocket();
client->Connect(host, port);
} catch (const std::exception& ex) {
Log(LogCritical, "cli")
- << "Cannot connect to host '" << host << "' on port '" << port << "'";
+ << "Cannot connect to host '" << host << "' on port '" << port << "'";
Log(LogDebug, "cli")
- << "Cannot connect to host '" << host << "' on port '" << port << "':\n" << DiagnosticInformation(ex);
+ << "Cannot connect to host '" << host << "' on port '" << port << "':\n" << DiagnosticInformation(ex);
return 1;
}
sslContext = MakeSSLContext(certfile, keyfile);
} catch (const std::exception& ex) {
Log(LogCritical, "cli")
- << "Cannot make SSL context for cert path: '" << certfile << "' key path: '" << keyfile << "' ca path: '" << cafile << "'.";
+ << "Cannot make SSL context for cert path: '" << certfile << "' key path: '" << keyfile << "' ca path: '" << cafile << "'.";
Log(LogDebug, "cli")
- << "Cannot make SSL context for cert path: '" << certfile << "' key path: '" << keyfile << "' ca path: '" << cafile << "':\n" << DiagnosticInformation(ex);
+ << "Cannot make SSL context for cert path: '" << certfile << "' key path: '" << keyfile << "' ca path: '" << cafile << "':\n" << DiagnosticInformation(ex);
return 1;
}
StringToCertificate(result->Get("ca"));
} catch (const std::exception& ex) {
Log(LogCritical, "cli")
- << "Could not write CA file: " << DiagnosticInformation(ex, false);
+ << "Could not write CA file: " << DiagnosticInformation(ex, false);
return 1;
}
Log(LogInformation, "cli")
- << "Writing CA certificate to file '" << cafile << "'.";
+ << "Writing CA certificate to file '" << cafile << "'.";
std::ofstream fpca;
fpca.open(cafile.CStr());
if (fpca.fail()) {
Log(LogCritical, "cli")
- << "Could not open CA certificate file '" << cafile << "' for writing.";
+ << "Could not open CA certificate file '" << cafile << "' for writing.";
return 1;
}
}
}
Log(severity, "cli")
- << "!!! " << result->Get("error");
+ << "!!! " << result->Get("error");
if (status == 1)
return 1;
StringToCertificate(result->Get("cert"));
} catch (const std::exception& ex) {
Log(LogCritical, "cli")
- << "Could not write certificate file: " << DiagnosticInformation(ex, false);
+ << "Could not write certificate file: " << DiagnosticInformation(ex, false);
return 1;
}
Log(LogInformation, "cli")
- << "Writing signed certificate to file '" << certfile << "'.";
+ << "Writing signed certificate to file '" << certfile << "'.";
std::ofstream fpcert;
fpcert.open(certfile.CStr());
if (fpcert.fail()) {
Log(LogCritical, "cli")
- << "Could not write certificate to file '" << certfile << "'.";
+ << "Could not write certificate to file '" << certfile << "'.";
return 1;
}
for (unsigned int i = 0; i < diglen; i++) {
info << std::setfill('0') << std::setw(2) << std::uppercase
- << std::hex << static_cast<int>(md[i]) << ' ';
+ << std::hex << static_cast<int>(md[i]) << ' ';
}
info << '\n';
static int WriteCert(const std::shared_ptr<X509>& cert, const String& trustedfile);
static int GenTicket(const String& cn, const String& salt, std::ostream& ticketfp);
static int RequestCertificate(const String& host, const String& port, const String& keyfile,
- const String& certfile, const String& cafile, const std::shared_ptr<X509>& trustedcert,
- const String& ticket = String());
+ const String& certfile, const String& cafile, const std::shared_ptr<X509>& trustedcert,
+ const String& ticket = String());
static String GetCertificateInformation(const std::shared_ptr<X509>& certificate);
static Dictionary::Ptr GetCertificateRequests(void);
DECLARE_PTR_TYPEDEFS(StatusTargetProvider);
virtual void FindTargets(const String& type,
- const std::function<void (const Value&)>& addTarget) const override
+ const std::function<void (const Value&)>& addTarget) const override
{
Dictionary::Ptr statsFunctions = ScriptGlobal::Get("StatsFunctions", &Empty);
objs = FilterUtility::GetFilterTargets(qd, params, user);
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 404,
- "No objects found.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "No objects found.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
return true;
}
DECLARE_PTR_TYPEDEFS(StatusHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
}
virtual void FindTargets(const String& type,
- const std::function<void (const Value&)>& addTarget) const override
+ const std::function<void (const Value&)>& addTarget) const override
{
Type::Ptr ptype = Type::GetByName(type);
objs = FilterUtility::GetFilterTargets(qd, params, user, "tmpl");
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 404,
- "No templates found.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "No templates found.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
return true;
}
DECLARE_PTR_TYPEDEFS(TemplateQueryHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
DECLARE_PTR_TYPEDEFS(TypeTargetProvider);
virtual void FindTargets(const String& type,
- const std::function<void (const Value&)>& addTarget) const override
+ const std::function<void (const Value&)>& addTarget) const override
{
for (const Type::Ptr& target : Type::GetAllTypes()) {
addTarget(target);
objs = FilterUtility::GetFilterTargets(qd, params, user);
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 404,
- "No objects found.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "No objects found.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
return true;
}
DECLARE_PTR_TYPEDEFS(TypeQueryHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
#define ACSCHEME ALPHA NUMERIC ".-+"
//authority = [ userinfo "@" ] host [ ":" port ]
-#define ACUSERINFO UNRESERVED SUB_DELIMS
+#define ACUSERINFO UNRESERVED SUB_DELIMS
#define ACHOST UNRESERVED SUB_DELIMS
#define ACPORT NUMERIC
if (kv.second.size() == 1) {
param += key;
param += kv.second[0].IsEmpty() ?
- String() : "=" + Utility::EscapeString(kv.second[0], ACQUERY_ENCODE, false);
+ String() : "=" + Utility::EscapeString(kv.second[0], ACQUERY_ENCODE, false);
continue;
}
}
virtual void FindTargets(const String& type,
- const std::function<void (const Value&)>& addTarget) const override
+ const std::function<void (const Value&)>& addTarget) const override
{
{
Dictionary::Ptr globals = ScriptGlobal::GetGlobals();
objs = FilterUtility::GetFilterTargets(qd, params, user, "variable");
} catch (const std::exception& ex) {
HttpUtility::SendJsonError(response, 404,
- "No variables found.",
- HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
+ "No variables found.",
+ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
return true;
}
DECLARE_PTR_TYPEDEFS(VariableQueryHandler);
virtual bool HandleRequest(const ApiUser::Ptr& user, HttpRequest& request,
- HttpResponse& response, const Dictionary::Ptr& params) override;
+ HttpResponse& response, const Dictionary::Ptr& params) override;
};
}
if (value && value->GetLength() > 2) {
Log(LogWarning, "Zone")
- << "The Zone object '" << GetName() << "' has more than two endpoints."
- << " Due to a known issue this type of configuration is strongly"
- << " discouraged and may cause Icinga to use excessive amounts of CPU time.";
+ << "The Zone object '" << GetName() << "' has more than two endpoints."
+ << " Due to a known issue this type of configuration is strongly"
+ << " discouraged and may cause Icinga to use excessive amounts of CPU time.";
}
}
static BOOL debug = FALSE;
-INT wmain(INT argc, WCHAR **argv)
+INT wmain(INT argc, WCHAR **argv)
{
std::vector<drive> vDrives;
printInfoStruct printInfo{ };
return printOutput(printInfo, vDrives);
}
-static INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
+static INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
WCHAR namePath[MAX_PATH];
GetModuleFileName(NULL, namePath, MAX_PATH);
}
}
- if (vm.count("path"))
+ if (vm.count("path"))
printInfo.drives = vm["path"].as<std::vector<std::wstring>>();
if (vm.count("exclude_device"))
return -1;
}
-static INT printOutput(printInfoStruct& printInfo, std::vector<drive>& vDrives)
+static INT printOutput(printInfoStruct& printInfo, std::vector<drive>& vDrives)
{
if (debug)
std::wcout << "Constructing output string\n";
if (vDrives.size() > 1) {
if (printInfo.showUsed) {
std::wcout << "Total " << (printInfo.showUsed ? tUsed : tFree) << unit
- << " (" << removeZero(std::round(tUsed / tCap * 100.0)) << "%); ";
+ << " (" << removeZero(std::round(tUsed / tCap * 100.0)) << "%); ";
}
}
if (debug)
std::wcout << "Getting volume mountpoints (includes NTFS folders)\n"
- << "Getting first volume\n";
+ << "Getting first volume\n";
hVolume = FindFirstVolume(szVolumeName, MAX_PATH);
if (hVolume == INVALID_HANDLE_VALUE)
volumeNameEnd = wcslen(szVolumeName) - 1;
szVolumePathNames = reinterpret_cast<WCHAR*>(new WCHAR[dwVolumePathNamesLen]);
- while (!GetVolumePathNamesForVolumeName(szVolumeName, szVolumePathNames, dwVolumePathNamesLen,
- &dwVolumePathNamesLen)) {
+ while (!GetVolumePathNamesForVolumeName(szVolumeName, szVolumePathNames, dwVolumePathNamesLen,
+ &dwVolumePathNamesLen)) {
if (GetLastError() != ERROR_MORE_DATA)
break;
delete[] reinterpret_cast<WCHAR*>(szVolumePathNames);
for (const std::wstring& wsDriveName : vExclude_Drives)
{
- vDrives.erase(std::remove_if(vDrives.begin(), vDrives.end(),
- std::bind(checkName, _1, wsDriveName + L'\\')), vDrives.end());
+ vDrives.erase(std::remove_if(vDrives.begin(), vDrives.end(),
+ std::bind(checkName, _1, wsDriveName + L'\\')), vDrives.end());
}
}
return -1;
return 3;
}
-static INT check_drives(std::vector<drive>& vDrives, printInfoStruct& printInfo)
+static INT check_drives(std::vector<drive>& vDrives, printInfoStruct& printInfo)
{
if (!printInfo.exclude_drives.empty()) {
if (debug)
for (std::wstring& wsDrive : printInfo.exclude_drives)
{
printInfo.drives.erase(std::remove(printInfo.drives.begin(), printInfo.drives.end(), wsDrive),
- printInfo.drives.end());
+ printInfo.drives.end());
}
}
drive.free = round((tempFree.QuadPart / pow(1024.0, unit)));
if (debug)
- std::wcout << "\tAfter conversion: " << drive.free << '\n'
- << "\tused: " << tempUsed.QuadPart << '\n';
+ std::wcout << "\tAfter conversion: " << drive.free << '\n'
+ << "\tused: " << tempUsed.QuadPart << '\n';
drive.used = round((tempUsed.QuadPart / pow(1024.0, unit)));
static BOOL debug = FALSE;
-INT wmain(INT argc, WCHAR **argv)
+INT wmain(INT argc, WCHAR **argv)
{
printInfoStruct printInfo{ };
po::variables_map vm;
return -1;
}
-INT printOutput(printInfoStruct& printInfo)
+INT printOutput(printInfoStruct& printInfo)
{
if (debug)
std::wcout << L"Constructing output string" << '\n';
state = CRITICAL;
std::wstringstream perf;
- perf << L"% | load=" << printInfo.load << L"%;" << printInfo.warn.pString() << L";"
+ perf << L"% | load=" << printInfo.load << L"%;" << printInfo.warn.pString() << L";"
<< printInfo.crit.pString() << L";0;100" << '\n';
switch (state) {
return state;
}
-INT check_load(printInfoStruct& printInfo)
+INT check_load(printInfoStruct& printInfo)
{
PDH_HQUERY phQuery = NULL;
PDH_HCOUNTER phCounter;
static BOOL debug = FALSE;
static BOOL noisatap = FALSE;
-INT wmain(INT argc, WCHAR **argv)
+INT wmain(INT argc, WCHAR **argv)
{
std::vector<nInterface> vInterfaces;
std::map<std::wstring, std::wstring> mapNames;
return printOutput(printInfo, vInterfaces, mapNames);
}
-INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
+INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
WCHAR namePath[MAX_PATH];
GetModuleFileName(NULL, namePath, MAX_PATH);
return state;
}
-INT check_network(std::vector <nInterface>& vInterfaces)
+INT check_network(std::vector <nInterface>& vInterfaces)
{
CONST WCHAR *perfIn = L"\\Network Interface(*)\\Bytes Received/sec";
CONST WCHAR *perfOut = L"\\Network Interface(*)\\Bytes Sent/sec";
goto die;
err = PdhAddEnglishCounter(phQuery, perfIn, NULL, &phCounterIn);
- if (!SUCCEEDED(err))
+ if (!SUCCEEDED(err))
goto die;
err = PdhAddEnglishCounter(phQuery, perfOut, NULL, &phCounterOut);
- if (!SUCCEEDED(err))
+ if (!SUCCEEDED(err))
goto die;
if (debug)
* decodes it to a Dictionary and then tells 'QueryEndpoint()' that it's done
*/
static void ResultHttpCompletionCallback(const HttpRequest& request, HttpResponse& response, bool& ready,
- boost::condition_variable& cv, boost::mutex& mtx, Dictionary::Ptr& result)
+ boost::condition_variable& cv, boost::mutex& mtx, Dictionary::Ptr& result)
{
String body;
char buffer[1024];
if (l_Debug) {
std::cout << "Received answer\n"
- << "\tHTTP code: " << response.StatusCode << "\n"
- << "\tHTTP message: '" << response.StatusMessage << "'\n"
- << "\tHTTP body: '" << body << "'.\n";
+ << "\tHTTP code: " << response.StatusCode << "\n"
+ << "\tHTTP message: '" << response.StatusMessage << "'\n"
+ << "\tHTTP body: '" << body << "'.\n";
}
// Only try to decode the body if the 'HttpRequest' was successful
* query name and all the arguments formatted as an URL.
*/
static Dictionary::Ptr QueryEndpoint(const String& host, const String& port, const String& password,
- const String& endpoint)
+ const String& endpoint)
{
HttpClientConnection::Ptr m_Connection = new HttpClientConnection(host, port, true);
Application::InitializeBase();
Dictionary::Ptr result = QueryEndpoint(vm["host"].as<std::string>(), vm["port"].as<std::string>(),
- vm["password"].as<std::string>(), endpoint);
+ vm["password"].as<std::string>(), endpoint);
// Application::Exit() is the clean way to exit after calling InitializeBase()
Application::Exit(FormatOutput(result));
return TRUE;
}
-BOOL GetIntstancesAndCountersOfObject(CONST std::wstring wsObject,
- std::vector<std::wstring>& vecInstances,
- std::vector<std::wstring>& vecCounters)
+BOOL GetIntstancesAndCountersOfObject(CONST std::wstring wsObject,
+ std::vector<std::wstring>& vecInstances, std::vector<std::wstring>& vecCounters)
{
LPWSTR szDataSource = NULL, szMachineName = NULL,
mszCounterList = NULL, mszInstanceList = NULL;
if (!GetIntstancesAndCountersOfObject(pI.wsFullPath, vecInstances, vecCounters)) {
std::wcout << "Could not enumerate instances and counters of " << pI.wsFullPath << '\n'
- << "Make sure it exists!\n";
+ << "Make sure it exists!\n";
return;
}
std::wcout << "> Has no instances\n";
else {
for (std::vector<std::wstring>::iterator it = vecInstances.begin();
- it != vecInstances.end(); ++it) {
+ it != vecInstances.end(); ++it) {
std::wcout << "> " << *it << '\n';
}
}
std::wcout << "> Has no counters\n";
else {
for (std::vector<std::wstring>::iterator it = vecCounters.begin();
- it != vecCounters.end(); ++it) {
+ it != vecCounters.end(); ++it) {
std::wcout << "> " << *it << '\n';
}
}
if (FAILED(status))
goto die;
- /*
- /* Most counters need two queries to provide a value.
- /* Those which need only one will return the second.
+ /*
+ * Most counters need two queries to provide a value.
+ * Those which need only one will return the second.
*/
Sleep(pI.dwPerformanceWait);
if (FAILED(status))
goto die;
- status = PdhGetFormattedCounterArray(hCounter, pI.dwRequestedType,
- &dwBufferSize, &dwItemCount, pDisplayValues);
+ status = PdhGetFormattedCounterArray(hCounter, pI.dwRequestedType, &dwBufferSize, &dwItemCount, pDisplayValues);
if (status != PDH_MORE_DATA)
goto die;
pDisplayValues = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM*>(new BYTE[dwBufferSize]);
- status = PdhGetFormattedCounterArray(hCounter, pI.dwRequestedType,
- &dwBufferSize, &dwItemCount, pDisplayValues);
+ status = PdhGetFormattedCounterArray(hCounter, pI.dwRequestedType, &dwBufferSize, &dwItemCount, pDisplayValues);
if (FAILED(status))
goto die;
if (pi.tCrit.rend(pi.dValue)) {
std::wcout << "PERFMON CRITICAL \"" << (vm.count("perf-syntax") ? vm["perf-syntax"].as<std::wstring>() : pi.wsFullPath)
- << "\" = " << pi.dValue << " | " << wssPerfData.str() << '\n';
+ << "\" = " << pi.dValue << " | " << wssPerfData.str() << '\n';
return 2;
}
if (pi.tWarn.rend(pi.dValue)) {
std::wcout << "PERFMON WARNING \"" << (vm.count("perf-syntax") ? vm["perf-syntax"].as<std::wstring>() : pi.wsFullPath)
- << "\" = " << pi.dValue << " | " << wssPerfData.str() << '\n';
+ << "\" = " << pi.dValue << " | " << wssPerfData.str() << '\n';
return 1;
}
std::wcout << "PERFMON OK \"" << (vm.count("perf-syntax") ? vm["perf-syntax"].as<std::wstring>() : pi.wsFullPath)
- << "\" = " << pi.dValue << " | " << wssPerfData.str() << '\n';
+ << "\" = " << pi.dValue << " | " << wssPerfData.str() << '\n';
return 0;
}
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN //else winsock will be included with windows.h and conflict with winsock2
-#endif
+#endif
#include <winsock2.h>
#include <iphlpapi.h>
std::wstringstream perf;
perf << L"rta=" << response.avg << L"ms;" << printInfo.warn.pString() << L";"
- << printInfo.crit.pString() << L";0;" << " pl=" << removeZero(plp) << "%;"
+ << printInfo.crit.pString() << L";0;" << " pl=" << removeZero(plp) << "%;"
<< printInfo.wpl.pString() << ";" << printInfo.cpl.pString() << ";0;100";
if (response.dropped == printInfo.num) {
static BOOL debug = FALSE;
-INT wmain(INT argc, WCHAR **argv)
+INT wmain(INT argc, WCHAR **argv)
{
po::variables_map vm;
printInfoStruct printInfo = { };
return printOutput(countProcs(), printInfo);
}
-INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
+INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
WCHAR namePath[MAX_PATH];
GetModuleFileName(NULL, namePath, MAX_PATH);
}
}
- if (vm.count("user"))
+ if (vm.count("user"))
printInfo.user = vm["user"].as<std::wstring>();
if (vm.count("debug"))
return state;
}
-INT countProcs()
+INT countProcs()
{
if (debug)
std::wcout << L"Counting all processes" << '\n';
return numProcs;
}
-INT countProcs(CONST std::wstring user)
+INT countProcs(CONST std::wstring user)
{
if (debug)
std::wcout << L"Counting all processes of user" << user << '\n';
//get ProcessToken
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID);
- if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
+ if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
//Won't count pid 0 (system idle) and 4/8 (Sytem)
continue;
//Get dwReturnLength in first call
dwReturnLength = 1;
if (!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwReturnLength)
- && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
+ && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
continue;
pSIDTokenUser = reinterpret_cast<PTOKEN_USER>(new BYTE[dwReturnLength]);
return -1;
}
-INT printOutput(CONST printInfoStruct& printInfo)
+INT printOutput(CONST printInfoStruct& printInfo)
{
if (debug)
std::wcout << L"Constructing output string" << '\n';
return 3;
}
- if (printInfo.ServiceState != 0x04)
+ if (printInfo.ServiceState != 0x04)
printInfo.warn ? state = WARNING : state = CRITICAL;
switch (state) {
return L"";
}
-DWORD ServiceStatus(CONST printInfoStruct& printInfo)
+DWORD ServiceStatus(CONST printInfoStruct& printInfo)
{
SC_HANDLE hSCM;
SC_HANDLE hService;
static BOOL debug = FALSE;
-INT wmain(INT argc, WCHAR **argv)
+INT wmain(INT argc, WCHAR **argv)
{
printInfoStruct printInfo = { };
po::variables_map vm;
return printOutput(printInfo);
}
-INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
+INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
WCHAR namePath[MAX_PATH];
GetModuleFileName(NULL, namePath, MAX_PATH);
return -1;
}
-INT printOutput(printInfoStruct& printInfo)
+INT printOutput(printInfoStruct& printInfo)
{
if (debug)
std::wcout << L"Constructing output string" << '\n';
switch (state) {
case OK:
std::wcout << L"SWAP OK - " << printInfo.percentFree << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";"
- << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
+ << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
<< L";0;" << printInfo.tSwap << '\n';
break;
case WARNING:
std::wcout << L"SWAP WARNING - " << printInfo.percentFree << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";"
- << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
+ << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
<< L";0;" << printInfo.tSwap << '\n';
break;
case CRITICAL:
std::wcout << L"SWAP CRITICAL - " << printInfo.percentFree << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";"
- << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
+ << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
<< L";0;" << printInfo.tSwap << '\n';
break;
}
return state;
}
-INT check_swap(printInfoStruct& printInfo)
+INT check_swap(printInfoStruct& printInfo
{
MEMORYSTATUSEX MemBuf;
MemBuf.dwLength = sizeof(MemBuf);
static BOOL debug = FALSE;
-INT wmain(INT argc, WCHAR **argv)
+INT wmain(INT argc, WCHAR **argv)
{
printInfoStruct printInfo = { FALSE, FALSE, 0, FALSE, FALSE, FALSE };
po::variables_map vm;
return printOutput(printInfo);
}
-INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
+INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
WCHAR namePath[MAX_PATH];
GetModuleFileName(NULL, namePath, MAX_PATH);
return state;
}
-INT check_update(printInfoStruct& printInfo)
+INT check_update(printInfoStruct& printInfo)
{
if (debug)
std::wcout << "Initializing COM library" << '\n';
pSession->CreateUpdateSearcher(&pSearcher);
/*
- IsInstalled = 0: All updates, including languagepacks and features
- BrowseOnly = 0: No features or languagepacks, security and unnamed
- BrowseOnly = 1: Nothing, broken
- RebootRequired = 1: Reboot required
- */
+ * IsInstalled = 0: All updates, including languagepacks and features
+ * BrowseOnly = 0: No features or languagepacks, security and unnamed
+ * BrowseOnly = 1: Nothing, broken
+ * RebootRequired = 1: Reboot required
+ */
criteria = SysAllocString(CRITERIA);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa386526%28v=vs.85%29.aspx
return printOutput(printInfo);
}
-INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
+INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
WCHAR namePath[MAX_PATH];
GetModuleFileName(NULL, namePath, MAX_PATH);
} catch (std::invalid_argument) {
std::wcout << L"Unknown unit type " << vm["unit"].as<std::wstring>() << '\n';
return 3;
- }
+ }
} else
printInfo.unit = TunitS;
return -1;
}
-INT printOutput(printInfoStruct& printInfo)
+INT printOutput(printInfoStruct& printInfo)
{
if (debug)
std::wcout << L"Constructing output string" << '\n';
return state;
}
-VOID getUptime(printInfoStruct& printInfo)
+VOID getUptime(printInfoStruct& printInfo)
{
if (debug)
std::wcout << L"Getting uptime in milliseconds" << '\n';
std::wcout << L"Converting requested unit (default: seconds)" << '\n';
switch (printInfo.unit) {
- case TunitH:
+ case TunitH:
printInfo.time = boost::chrono::duration_cast<boost::chrono::hours>(uptime).count();
break;
case TunitM:
static BOOL debug = FALSE;
-INT wmain(INT argc, WCHAR **argv)
+INT wmain(INT argc, WCHAR **argv)
{
printInfoStruct printInfo = { };
po::variables_map vm;
return printOutput(printInfo);
}
-INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
+INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
WCHAR namePath[MAX_PATH];
GetModuleFileName(NULL, namePath, MAX_PATH);
return -1;
}
-INT printOutput(printInfoStruct& printInfo)
+INT printOutput(printInfoStruct& printInfo)
{
if (debug)
std::wcout << L"Constructing output string" << '\n';
return state;
}
-INT check_users(printInfoStruct& printInfo)
+INT check_users(printInfoStruct& printInfo)
{
DOUBLE users = 0;
WTS_SESSION_INFOW *pSessionInfo = NULL;
DWORD count;
DWORD index;
- if (debug)
+ if (debug)
std::wcout << L"Trying to enumerate terminal sessions" << '\n';
if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &count)) {
upperAbs = upper / 100.0 * max;
}
- std::wstring s, lowerStr = removeZero(lowerAbs),
+ std::wstring s, lowerStr = removeZero(lowerAbs)
upperStr = removeZero(upperAbs);
if (lower != upper) {
s.append(L"[").append(lowerStr).append(L"-")
.append(upperStr).append(L"]");
- } else
+ } else
s.append(lowerStr);
return s;
throw std::invalid_argument("Unknown unit type");
}
-std::wstring BunitStr(CONST Bunit& unit)
+std::wstring BunitStr(CONST Bunit& unit)
{
switch (unit) {
case BunitB:
throw std::invalid_argument("Unknown unit type");
}
-std::wstring TunitStr(CONST Tunit& unit)
+std::wstring TunitStr(CONST Tunit& unit)
{
switch (unit) {
case TunitMS:
clearText.push_back("123");
clearText.push_back("1234");
clearText.push_back(
- "VsowLvPqEiAeITDmo-5L_NB-k7fsT3sT2d3K9O4iC2uBk41hvCPAxrgGSxrdeX5s"
- "Zo0Z9b1kxDZlzf8GHQ9ARW6YLeGODMtiZo8cKkUzfSbxyZ_wlE9u6pCTTg9kODCM"
- "Ve-X_a3jWkOy89RoDkT5ahKBY-8S25L6wlvWt8ZyQ2bLxfplzEzuHgEknTMKKp2K"
- "jRlwI2p3gF4FYeQM7dx0E5O782Lh1P3IC6jPNqiZgTgWmsRYZbAN8oU2V626bQxD"
- "n8prQ0Xr_3aPdP7VIVgxNZMnF0NJrQvB_rzq1Dip1UM_xH_9nansbX25E64OQU-r"
- "q54EdO-vb_9FvyqdeVTJ3UTgXIP7OXtz4K8xlEHWdb1-hJChVvDc0KSnN5HVN2NJ"
- "yJrAofVyHBxXGRnGMdN8cOwvxzBFsz2Hih_lIqm1NVULm9_J9GoesY-aN8JzGocU"
- "U3hbhFQBiUlzliuodhwg4RXRcfmPHQRo7kWKaohpySkvqmWcXEAt2LPJ8nH70fW7"
- "vudgzwwWTnNcMlf0Wa-nKL4xXNNPQD0obDCfogN8uKuGqi0DltOUmFK62Zkkb0_d"
- "45grssnD5q89MjDGBkGMXuLY_JLOqc7Y9VV6H48vzoTNK1a2kOGV2TrAD8syuA5Z"
- "o8RLKjTqAYjKTUqEJjg0MflpiBnbDQvRqiSXs1cJuFNXRLpEC5GoqGqMd0zAGn4u"
- "5J3OurVd0SFp8_vkYUI6YwNUe00y8_Dn6DOBh_0KKADphZBgple82_8HrnQNreQn"
- "GkB2TpIsjwWud0yuhI-jQZEMNNlhEYMLwx7B-xTGhn0LFC1pLEXn_kZ2NOgDgUHd"
- "bdj906o3N2Jjo9Fb5GXkCrt-fNEYBjeXvIu73yeTGmsiAzfiICNHi_PmGkgq8fYQ"
- "O9lQgyRHCMic8zU7ffWuSoUPRgHsqztLHaCDbYIrNmgrn2taxcXSb57Xm_l-1xBH"
- "bZqdMvBziapJXaLJmhUg03lgdsIc_OuJmzt-sytDLVGIuNqpa4dETdhLsI7qis4B"
+ "VsowLvPqEiAeITDmo-5L_NB-k7fsT3sT2d3K9O4iC2uBk41hvCPAxrgGSxrdeX5s"
+ "Zo0Z9b1kxDZlzf8GHQ9ARW6YLeGODMtiZo8cKkUzfSbxyZ_wlE9u6pCTTg9kODCM"
+ "Ve-X_a3jWkOy89RoDkT5ahKBY-8S25L6wlvWt8ZyQ2bLxfplzEzuHgEknTMKKp2K"
+ "jRlwI2p3gF4FYeQM7dx0E5O782Lh1P3IC6jPNqiZgTgWmsRYZbAN8oU2V626bQxD"
+ "n8prQ0Xr_3aPdP7VIVgxNZMnF0NJrQvB_rzq1Dip1UM_xH_9nansbX25E64OQU-r"
+ "q54EdO-vb_9FvyqdeVTJ3UTgXIP7OXtz4K8xlEHWdb1-hJChVvDc0KSnN5HVN2NJ"
+ "yJrAofVyHBxXGRnGMdN8cOwvxzBFsz2Hih_lIqm1NVULm9_J9GoesY-aN8JzGocU"
+ "U3hbhFQBiUlzliuodhwg4RXRcfmPHQRo7kWKaohpySkvqmWcXEAt2LPJ8nH70fW7"
+ "vudgzwwWTnNcMlf0Wa-nKL4xXNNPQD0obDCfogN8uKuGqi0DltOUmFK62Zkkb0_d"
+ "45grssnD5q89MjDGBkGMXuLY_JLOqc7Y9VV6H48vzoTNK1a2kOGV2TrAD8syuA5Z"
+ "o8RLKjTqAYjKTUqEJjg0MflpiBnbDQvRqiSXs1cJuFNXRLpEC5GoqGqMd0zAGn4u"
+ "5J3OurVd0SFp8_vkYUI6YwNUe00y8_Dn6DOBh_0KKADphZBgple82_8HrnQNreQn"
+ "GkB2TpIsjwWud0yuhI-jQZEMNNlhEYMLwx7B-xTGhn0LFC1pLEXn_kZ2NOgDgUHd"
+ "bdj906o3N2Jjo9Fb5GXkCrt-fNEYBjeXvIu73yeTGmsiAzfiICNHi_PmGkgq8fYQ"
+ "O9lQgyRHCMic8zU7ffWuSoUPRgHsqztLHaCDbYIrNmgrn2taxcXSb57Xm_l-1xBH"
+ "bZqdMvBziapJXaLJmhUg03lgdsIc_OuJmzt-sytDLVGIuNqpa4dETdhLsI7qis4B"
);
// 1024 chars
std::bitset<20> stateChangeBuf = obj->GetFlappingBuffer();
int oldestIndex = (obj->GetFlappingBuffer() & 0xFF00000) >> 20;
- std::cout << "Flapping: " << obj->IsFlapping() << "\nHT: " << obj->GetFlappingThresholdHigh() << " LT: " << obj->GetFlappingThresholdLow()
- << "\nOur value: " << obj->GetFlappingCurrent() << "\nPtr: " << oldestIndex << " Buf: " << stateChangeBuf.to_ulong() << '\n';
+ std::cout << "Flapping: " << obj->IsFlapping() << "\nHT: " << obj->GetFlappingThresholdHigh() << " LT: "
+ << obj->GetFlappingThresholdLow() << "\nOur value: " << obj->GetFlappingCurrent() << "\nPtr: " << oldestIndex
+ << " Buf: " << stateChangeBuf.to_ulong() << '\n';
}
static void LogHostStatus(const Host::Ptr &host)
{
std::cout << "Current status: state: " << host->GetState() << " state_type: " << host->GetStateType()
- << " check attempt: " << host->GetCheckAttempt() << "/" << host->GetMaxCheckAttempts() << std::endl;
+ << " check attempt: " << host->GetCheckAttempt() << "/" << host->GetMaxCheckAttempts() << std::endl;
}
#endif /* I2_DEBUG */
BOOST_AUTO_TEST_CASE(host_not_flapping)
{
#ifndef I2_DEBUG
- BOOST_WARN_MESSAGE(false, "This test can only be run in a debug build!");
+ BOOST_WARN_MESSAGE(false, "This test can only be run in a debug build!");
#else /* I2_DEBUG */
std::cout << "Running test with a non-flapping host...\n";
BOOST_AUTO_TEST_CASE(host_flapping)
{
#ifndef I2_DEBUG
- BOOST_WARN_MESSAGE(false, "This test can only be run in a debug build!");
+ BOOST_WARN_MESSAGE(false, "This test can only be run in a debug build!");
#else /* I2_DEBUG */
std::cout << "Running test with host changing state with every check...\n";
BOOST_AUTO_TEST_CASE(host_flapping_recover)
{
#ifndef I2_DEBUG
- BOOST_WARN_MESSAGE(false, "This test can only be run in a debug build!");
+ BOOST_WARN_MESSAGE(false, "This test can only be run in a debug build!");
#else /* I2_DEBUG */
std::cout << "Running test with flapping recovery...\n";
Utility::SetTime(0);
- // A few warning
+ // A few warning
host->ProcessCheckResult(MakeCheckResult(ServiceWarning));
host->ProcessCheckResult(MakeCheckResult(ServiceWarning));
host->ProcessCheckResult(MakeCheckResult(ServiceWarning));
BOOST_AUTO_TEST_CASE(host_flapping_docs_example)
{
#ifndef I2_DEBUG
- BOOST_WARN_MESSAGE(false, "This test can only be run in a debug build!");
+ BOOST_WARN_MESSAGE(false, "This test can only be run in a debug build!");
#else /* I2_DEBUG */
std::cout << "Simulating the documentation example...\n";
void yyerror(YYLTYPE *locp, ClassCompiler *, const char *err)
{
- std::cerr << "in " << locp->path << " at " << locp->first_line << ":" << locp->first_column << "-" << locp->last_line << ":" << locp->last_column << ": "
- << err
- << std::endl;
+ std::cerr << "in " << locp->path << " at " << locp->first_line << ":" << locp->first_column << "-"
+ << locp->last_line << ":" << locp->last_column << ": " << err << std::endl;
std::exit(1);
}
using namespace icinga;
ClassCompiler::ClassCompiler(const std::string& path, std::istream& input,
- std::ostream& oimpl, std::ostream& oheader)
+ std::ostream& oimpl, std::ostream& oheader)
: m_Path(path), m_Input(input), m_Impl(oimpl), m_Header(oheader)
{
InitializeScanner();
void ClassCompiler::HandleNamespaceBegin(const std::string& name, const ClassDebugInfo&)
{
m_Header << "namespace " << name << std::endl
- << "{" << std::endl << std::endl;
+ << "{" << std::endl << std::endl;
m_Impl << "namespace " << name << std::endl
- << "{" << std::endl << std::endl;
+ << "{" << std::endl << std::endl;
}
void ClassCompiler::HandleNamespaceEnd(const ClassDebugInfo&)
ch = std::toupper(ch, locale);
m_Header << "#ifndef I2_" << libName << "_API" << std::endl
- << "# ifdef I2_" << libName << "_BUILD" << std::endl
- << "# define I2_" << libName << "_API I2_EXPORT" << std::endl
- << "# else /* I2_" << libName << "_BUILD */" << std::endl
- << "# define I2_" << libName << "_API I2_IMPORT" << std::endl
- << "# endif /* I2_" << libName << "_BUILD */" << std::endl
- << "#endif /* I2_" << libName << "_API */" << std::endl << std::endl;
+ << "# ifdef I2_" << libName << "_BUILD" << std::endl
+ << "# define I2_" << libName << "_API I2_EXPORT" << std::endl
+ << "# else /* I2_" << libName << "_BUILD */" << std::endl
+ << "# define I2_" << libName << "_API I2_IMPORT" << std::endl
+ << "# endif /* I2_" << libName << "_BUILD */" << std::endl
+ << "#endif /* I2_" << libName << "_API */" << std::endl << std::endl;
}
unsigned long ClassCompiler::SDBM(const std::string& str, size_t len = std::string::npos)
/* TypeHelper */
if (klass.Attributes & TAAbstract) {
m_Header << "template<>" << std::endl
- << "struct TypeHelper<" << klass.Name << ", " << ((klass.Attributes & TAVarArgConstructor) ? "true" : "false") << ">" << std::endl
- << "{" << std::endl
- << "\t" << "static ObjectFactory GetFactory(void)" << std::endl
- << "\t" << "{" << std::endl
- << "\t\t" << "return nullptr;" << std::endl
- << "\t" << "}" << std::endl
- << "};" << std::endl << std::endl;
+ << "struct TypeHelper<" << klass.Name << ", " << ((klass.Attributes & TAVarArgConstructor) ? "true" : "false") << ">" << std::endl
+ << "{" << std::endl
+ << "\t" << "static ObjectFactory GetFactory(void)" << std::endl
+ << "\t" << "{" << std::endl
+ << "\t\t" << "return nullptr;" << std::endl
+ << "\t" << "}" << std::endl
+ << "};" << std::endl << std::endl;
}
/* TypeImpl */
m_Header << "template<>" << std::endl
- << "class " << apiMacro << "TypeImpl<" << klass.Name << ">"
- << " : public Type";
+ << "class " << apiMacro << "TypeImpl<" << klass.Name << ">"
+ << " : public Type";
if (!klass.Parent.empty())
m_Header << "Impl<" << klass.Parent << ">";
m_Header << ", public " + klass.TypeBase;
m_Header << std::endl
- << "{" << std::endl
- << "public:" << std::endl
- << "\t" << "DECLARE_PTR_TYPEDEFS(TypeImpl<" << klass.Name << ">);" << std::endl << std::endl;
+ << "{" << std::endl
+ << "public:" << std::endl
+ << "\t" << "DECLARE_PTR_TYPEDEFS(TypeImpl<" << klass.Name << ">);" << std::endl << std::endl;
/* GetName */
m_Header << "\t" << "virtual String GetName(void) const;" << std::endl;
m_Impl << "String TypeImpl<" << klass.Name << ">::GetName(void) const" << std::endl
- << "{" << std::endl
- << "\t" << "return \"" << klass.Name << "\";" << std::endl
- << "}" << std::endl << std::endl;
+ << "{" << std::endl
+ << "\t" << "return \"" << klass.Name << "\";" << std::endl
+ << "}" << std::endl << std::endl;
/* GetAttributes */
m_Header << "\t" << "virtual int GetAttributes(void) const;" << std::endl;
m_Impl << "int TypeImpl<" << klass.Name << ">::GetAttributes(void) const" << std::endl
- << "{" << std::endl
- << "\t" << "return " << klass.Attributes << ";" << std::endl
- << "}" << std::endl << std::endl;
+ << "{" << std::endl
+ << "\t" << "return " << klass.Attributes << ";" << std::endl
+ << "}" << std::endl << std::endl;
/* GetBaseType */
m_Header << "\t" << "virtual Type::Ptr GetBaseType(void) const;" << std::endl;
m_Impl << "Type::Ptr TypeImpl<" << klass.Name << ">::GetBaseType(void) const" << std::endl
- << "{" << std::endl
- << "\t" << "return ";
+ << "{" << std::endl
+ << "\t" << "return ";
if (!klass.Parent.empty())
m_Impl << klass.Parent << "::TypeInstance";
m_Impl << "Object::TypeInstance";
m_Impl << ";" << std::endl
- << "}" << std::endl << std::endl;
+ << "}" << std::endl << std::endl;
/* GetFieldId */
m_Header << "\t" << "virtual int GetFieldId(const String& name) const;" << std::endl;
m_Impl << "int TypeImpl<" << klass.Name << ">::GetFieldId(const String& name) const" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Fields.empty()) {
m_Impl << "\t" << "int offset = ";
for (const auto& itf : itj.second) {
m_Impl << "\t\t\t" << "if (name == \"" << itf.second << "\")" << std::endl
- << "\t\t\t\t" << "return offset + " << itf.first << ";" << std::endl;
+ << "\t\t\t\t" << "return offset + " << itf.first << ";" << std::endl;
}
m_Impl << std::endl
- << "\t\t\t\tbreak;" << std::endl;
+ << "\t\t\t\tbreak;" << std::endl;
}
m_Impl << "\t}" << std::endl;
}
m_Impl << std::endl
- << "\t" << "return ";
+ << "\t" << "return ";
if (!klass.Parent.empty())
m_Impl << klass.Parent << "::TypeInstance->GetFieldId(name)";
m_Impl << "-1";
m_Impl << ";" << std::endl
- << "}" << std::endl << std::endl;
+ << "}" << std::endl << std::endl;
/* GetFieldInfo */
m_Header << "\t" << "virtual Field GetFieldInfo(int id) const;" << std::endl;
m_Impl << "Field TypeImpl<" << klass.Name << ">::GetFieldInfo(int id) const" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Parent.empty())
m_Impl << "\t" << "int real_id = id - " << klass.Parent << "::TypeInstance->GetFieldCount();" << std::endl
- << "\t" << "if (real_id < 0) { return " << klass.Parent << "::TypeInstance->GetFieldInfo(id); }" << std::endl;
+ << "\t" << "if (real_id < 0) { return " << klass.Parent << "::TypeInstance->GetFieldInfo(id); }" << std::endl;
if (!klass.Fields.empty()) {
m_Impl << "\t" << "switch (";
nameref = "nullptr";
m_Impl << "\t\t" << "case " << num << ":" << std::endl
- << "\t\t\t" << "return Field(" << num << ", \"" << ftype << "\", \"" << field.Name << "\", \"" << (field.NavigationName.empty() ? field.Name : field.NavigationName) << "\", " << nameref << ", " << field.Attributes << ", " << field.Type.ArrayRank << ");" << std::endl;
+ << "\t\t\t" << "return Field(" << num << ", \"" << ftype << "\", \"" << field.Name << "\", \"" << (field.NavigationName.empty() ? field.Name : field.NavigationName) << "\", " << nameref << ", " << field.Attributes << ", " << field.Type.ArrayRank << ");" << std::endl;
num++;
}
m_Impl << "\t\t" << "default:" << std::endl
- << "\t\t";
+ << "\t\t";
}
m_Impl << "\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl;
m_Header << "\t" << "virtual int GetFieldCount(void) const;" << std::endl;
m_Impl << "int TypeImpl<" << klass.Name << ">::GetFieldCount(void) const" << std::endl
- << "{" << std::endl
- << "\t" << "return " << klass.Fields.size();
+ << "{" << std::endl
+ << "\t" << "return " << klass.Fields.size();
if (!klass.Parent.empty())
m_Impl << " + " << klass.Parent << "::TypeInstance->GetFieldCount()";
m_Impl << ";" << std::endl
- << "}" << std::endl << std::endl;
+ << "}" << std::endl << std::endl;
/* GetFactory */
m_Header << "\t" << "virtual ObjectFactory GetFactory(void) const;" << std::endl;
m_Impl << "ObjectFactory TypeImpl<" << klass.Name << ">::GetFactory(void) const" << std::endl
- << "{" << std::endl
- << "\t" << "return TypeHelper<" << klass.Name << ", " << ((klass.Attributes & TAVarArgConstructor) ? "true" : "false") << ">::GetFactory();" << std::endl
- << "}" << std::endl << std::endl;
+ << "{" << std::endl
+ << "\t" << "return TypeHelper<" << klass.Name << ", " << ((klass.Attributes & TAVarArgConstructor) ? "true" : "false") << ">::GetFactory();" << std::endl
+ << "}" << std::endl << std::endl;
/* GetLoadDependencies */
m_Header << "\t" << "virtual std::vector<String> GetLoadDependencies(void) const;" << std::endl;
m_Impl << "std::vector<String> TypeImpl<" << klass.Name << ">::GetLoadDependencies(void) const" << std::endl
- << "{" << std::endl
- << "\t" << "std::vector<String> deps;" << std::endl;
+ << "{" << std::endl
+ << "\t" << "std::vector<String> deps;" << std::endl;
for (const std::string& dep : klass.LoadDependencies)
m_Impl << "\t" << "deps.push_back(\"" << dep << "\");" << std::endl;
m_Impl << "\t" << "return deps;" << std::endl
- << "}" << std::endl << std::endl;
+ << "}" << std::endl << std::endl;
/* RegisterAttributeHandler */
m_Header << "public:" << std::endl
- << "\t" << "virtual void RegisterAttributeHandler(int fieldId, const Type::AttributeHandler& callback);" << std::endl;
+ << "\t" << "virtual void RegisterAttributeHandler(int fieldId, const Type::AttributeHandler& callback);" << std::endl;
m_Impl << "void TypeImpl<" << klass.Name << ">::RegisterAttributeHandler(int fieldId, const Type::AttributeHandler& callback)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Parent.empty())
m_Impl << "\t" << "int real_id = fieldId - " << klass.Parent << "::TypeInstance->GetFieldCount(); " << std::endl
- << "\t" << "if (real_id < 0) { " << klass.Parent << "::TypeInstance->RegisterAttributeHandler(fieldId, callback); return; }" << std::endl;
+ << "\t" << "if (real_id < 0) { " << klass.Parent << "::TypeInstance->RegisterAttributeHandler(fieldId, callback); return; }" << std::endl;
if (!klass.Fields.empty()) {
m_Impl << "\t" << "switch (";
int num = 0;
for (const Field& field : klass.Fields) {
m_Impl << "\t\t" << "case " << num << ":" << std::endl
- << "\t\t\t" << "ObjectImpl<" << klass.Name << ">::On" << field.GetFriendlyName() << "Changed.connect(callback);" << std::endl
- << "\t\t\t" << "break;" << std::endl;
+ << "\t\t\t" << "ObjectImpl<" << klass.Name << ">::On" << field.GetFriendlyName() << "Changed.connect(callback);" << std::endl
+ << "\t\t\t" << "break;" << std::endl;
num++;
}
m_Impl << "\t\t" << "default:" << std::endl
- << "\t\t";
+ << "\t\t";
}
m_Impl << "\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl;
/* ObjectImpl */
m_Header << "template<>" << std::endl
- << "class " << apiMacro << "ObjectImpl<" << klass.Name << ">"
- << " : public " << (klass.Parent.empty() ? "Object" : klass.Parent) << std::endl
- << "{" << std::endl
- << "public:" << std::endl
- << "\t" << "DECLARE_PTR_TYPEDEFS(ObjectImpl<" << klass.Name << ">);" << std::endl << std::endl;
+ << "class " << apiMacro << "ObjectImpl<" << klass.Name << ">"
+ << " : public " << (klass.Parent.empty() ? "Object" : klass.Parent) << std::endl
+ << "{" << std::endl
+ << "public:" << std::endl
+ << "\t" << "DECLARE_PTR_TYPEDEFS(ObjectImpl<" << klass.Name << ">);" << std::endl << std::endl;
/* Validate */
m_Header << "\t" << "virtual void Validate(int types, const ValidationUtils& utils) override;" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::Validate(int types, const ValidationUtils& utils)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Parent.empty())
m_Impl << "\t" << klass.Parent << "::Validate(types, utils);" << std::endl << std::endl;
for (const Field& field : klass.Fields) {
m_Impl << "\t" << "if (" << (field.Attributes & (FAEphemeral|FAConfig|FAState)) << " & types)" << std::endl
- << "\t\t" << "Validate" << field.GetFriendlyName() << "(Get" << field.GetFriendlyName() << "(), utils);" << std::endl;
+ << "\t\t" << "Validate" << field.GetFriendlyName() << "(Get" << field.GetFriendlyName() << "(), utils);" << std::endl;
}
m_Impl << "}" << std::endl << std::endl;
m_Header << "\t" << "void SimpleValidate" << field.GetFriendlyName() << "(" << field.Type.GetArgumentType() << " " << argName << ", const ValidationUtils& utils);" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::SimpleValidate" << field.GetFriendlyName() << "(" << field.Type.GetArgumentType() << " " << argName << ", const ValidationUtils& utils)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (field.Attributes & FARequired) {
if (field.Type.GetRealType().find("::Ptr") != std::string::npos)
if (field.Type.ArrayRank > 0) {
m_Impl << "\t" << "if (avalue) {" << std::endl
- << "\t\t" << "ObjectLock olock(avalue);" << std::endl
- << "\t\t" << "for (const Value& value : avalue) {" << std::endl;
+ << "\t\t" << "ObjectLock olock(avalue);" << std::endl
+ << "\t\t" << "for (const Value& value : avalue) {" << std::endl;
}
std::string ftype = FieldTypeToIcingaName(field, true);
if (ftype == "Value") {
m_Impl << "\t" << "if (value.IsObjectType<Function>()) {" << std::endl
- << "\t\t" << "Function::Ptr func = value;" << std::endl
- << "\t\t" << "if (func->IsDeprecated())" << std::endl
- << "\t\t\t" << "Log(LogWarning, \"" << klass.Name << "\") << \"Attribute '" << field.Name << "' for object '\" << dynamic_cast<ConfigObject *>(this)->GetName() << \"' of type '\" << dynamic_cast<ConfigObject *>(this)->GetReflectionType()->GetName() << \"' is set to a deprecated function: \" << func->GetName();" << std::endl
- << "\t" << "}" << std::endl << std::endl;
+ << "\t\t" << "Function::Ptr func = value;" << std::endl
+ << "\t\t" << "if (func->IsDeprecated())" << std::endl
+ << "\t\t\t" << "Log(LogWarning, \"" << klass.Name << "\") << \"Attribute '" << field.Name << "' for object '\" << dynamic_cast<ConfigObject *>(this)->GetName() << \"' of type '\" << dynamic_cast<ConfigObject *>(this)->GetReflectionType()->GetName() << \"' is set to a deprecated function: \" << func->GetName();" << std::endl
+ << "\t" << "}" << std::endl << std::endl;
}
if (field.Type.IsName) {
m_Impl << "!value.IsEmpty() && ";
m_Impl << "!utils.ValidateName(\"" << field.Type.TypeName << "\", value))" << std::endl
- << "\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_cast<ConfigObject *>(this), boost::assign::list_of(\"" << field.Name << "\"), \"Object '\" + value + \"' of type '" << field.Type.TypeName
- << "' does not exist.\"));" << std::endl;
+ << "\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_cast<ConfigObject *>(this), boost::assign::list_of(\"" << field.Name << "\"), \"Object '\" + value + \"' of type '" << field.Type.TypeName
+ << "' does not exist.\"));" << std::endl;
} else if (field.Type.ArrayRank > 0 && (ftype == "Number" || ftype == "Boolean")) {
m_Impl << "\t" << "try {" << std::endl
- << "\t\t" << "Convert::ToDouble(value);" << std::endl
- << "\t" << "} catch (const std::invalid_argument&) {" << std::endl
- << "\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_cast<ConfigObject *>(this), boost::assign::list_of(\"" << field.Name << "\"), \"Array element '\" + value + \"' of type '\" + value.GetReflectionType()->GetName() + \"' is not valid here; expected type '" << ftype << "'.\"));" << std::endl
- << "\t" << "}" << std::endl;
+ << "\t\t" << "Convert::ToDouble(value);" << std::endl
+ << "\t" << "} catch (const std::invalid_argument&) {" << std::endl
+ << "\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_cast<ConfigObject *>(this), boost::assign::list_of(\"" << field.Name << "\"), \"Array element '\" + value + \"' of type '\" + value.GetReflectionType()->GetName() + \"' is not valid here; expected type '" << ftype << "'.\"));" << std::endl
+ << "\t" << "}" << std::endl;
}
if (field.Type.ArrayRank > 0) {
m_Impl << "\t\t" << "}" << std::endl
- << "\t" << "}" << std::endl;
+ << "\t" << "}" << std::endl;
}
m_Impl << "}" << std::endl << std::endl;
if (!klass.Fields.empty()) {
/* constructor */
m_Header << "public:" << std::endl
- << "\t" << "ObjectImpl<" << klass.Name << ">(void);" << std::endl;
+ << "\t" << "ObjectImpl<" << klass.Name << ">(void);" << std::endl;
m_Impl << "ObjectImpl<" << klass.Name << ">::ObjectImpl(void)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
for (const Field& field : klass.Fields) {
m_Impl << "\t" << "Set" << field.GetFriendlyName() << "(" << "GetDefault" << field.GetFriendlyName() << "(), true);" << std::endl;
/* destructor */
m_Header << "public:" << std::endl
- << "\t" << "~ObjectImpl<" << klass.Name << ">(void);" << std::endl;
+ << "\t" << "~ObjectImpl<" << klass.Name << ">(void);" << std::endl;
m_Impl << "ObjectImpl<" << klass.Name << ">::~ObjectImpl(void)" << std::endl
- << "{ }" << std::endl << std::endl;
+ << "{ }" << std::endl << std::endl;
/* SetField */
m_Header << "public:" << std::endl
- << "\t" << "virtual void SetField(int id, const Value& value, bool suppress_events = false, const Value& cookie = Empty) override;" << std::endl;
+ << "\t" << "virtual void SetField(int id, const Value& value, bool suppress_events = false, const Value& cookie = Empty) override;" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::SetField(int id, const Value& value, bool suppress_events, const Value& cookie)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Parent.empty())
m_Impl << "\t" << "int real_id = id - " << klass.Parent << "::TypeInstance->GetFieldCount(); " << std::endl
- << "\t" << "if (real_id < 0) { " << klass.Parent << "::SetField(id, value, suppress_events, cookie); return; }" << std::endl;
+ << "\t" << "if (real_id < 0) { " << klass.Parent << "::SetField(id, value, suppress_events, cookie); return; }" << std::endl;
m_Impl << "\t" << "switch (";
size_t num = 0;
for (const Field& field : klass.Fields) {
m_Impl << "\t\t" << "case " << num << ":" << std::endl
- << "\t\t\t" << "Set" << field.GetFriendlyName() << "(";
+ << "\t\t\t" << "Set" << field.GetFriendlyName() << "(";
if (field.Attributes & FAEnum)
m_Impl << "static_cast<" << field.Type.GetRealType() << ">(static_cast<int>(";
m_Impl << "))";
m_Impl << ", suppress_events, cookie);" << std::endl
- << "\t\t\t" << "break;" << std::endl;
+ << "\t\t\t" << "break;" << std::endl;
num++;
}
m_Impl << "\t\t" << "default:" << std::endl
- << "\t\t\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl
- << "\t" << "}" << std::endl;
+ << "\t\t\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl
+ << "\t" << "}" << std::endl;
m_Impl << "}" << std::endl << std::endl;
/* GetField */
m_Header << "public:" << std::endl
- << "\t" << "virtual Value GetField(int id) const override;" << std::endl;
+ << "\t" << "virtual Value GetField(int id) const override;" << std::endl;
m_Impl << "Value ObjectImpl<" << klass.Name << ">::GetField(int id) const" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Parent.empty())
m_Impl << "\t" << "int real_id = id - " << klass.Parent << "::TypeInstance->GetFieldCount(); " << std::endl
- << "\t" << "if (real_id < 0) { return " << klass.Parent << "::GetField(id); }" << std::endl;
+ << "\t" << "if (real_id < 0) { return " << klass.Parent << "::GetField(id); }" << std::endl;
m_Impl << "\t" << "switch (";
num = 0;
for (const Field& field : klass.Fields) {
m_Impl << "\t\t" << "case " << num << ":" << std::endl
- << "\t\t\t" << "return Get" << field.GetFriendlyName() << "();" << std::endl;
+ << "\t\t\t" << "return Get" << field.GetFriendlyName() << "();" << std::endl;
num++;
}
m_Impl << "\t\t" << "default:" << std::endl
- << "\t\t\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl
- << "\t" << "}" << std::endl;
+ << "\t\t\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl
+ << "\t" << "}" << std::endl;
m_Impl << "}" << std::endl << std::endl;
/* ValidateField */
m_Header << "public:" << std::endl
- << "\t" << "virtual void ValidateField(int id, const Value& value, const ValidationUtils& utils) override;" << std::endl;
+ << "\t" << "virtual void ValidateField(int id, const Value& value, const ValidationUtils& utils) override;" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::ValidateField(int id, const Value& value, const ValidationUtils& utils)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Parent.empty())
m_Impl << "\t" << "int real_id = id - " << klass.Parent << "::TypeInstance->GetFieldCount(); " << std::endl
- << "\t" << "if (real_id < 0) { " << klass.Parent << "::ValidateField(id, value, utils); return; }" << std::endl;
+ << "\t" << "if (real_id < 0) { " << klass.Parent << "::ValidateField(id, value, utils); return; }" << std::endl;
m_Impl << "\t" << "switch (";
num = 0;
for (const Field& field : klass.Fields) {
m_Impl << "\t\t" << "case " << num << ":" << std::endl
- << "\t\t\t" << "Validate" << field.GetFriendlyName() << "(";
+ << "\t\t\t" << "Validate" << field.GetFriendlyName() << "(";
if (field.Attributes & FAEnum)
m_Impl << "static_cast<" << field.Type.GetRealType() << ">(static_cast<int>(";
m_Impl << "))";
m_Impl << ", utils);" << std::endl
- << "\t\t\t" << "break;" << std::endl;
+ << "\t\t\t" << "break;" << std::endl;
num++;
}
m_Impl << "\t\t" << "default:" << std::endl
- << "\t\t\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl
- << "\t" << "}" << std::endl;
+ << "\t\t\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl
+ << "\t" << "}" << std::endl;
m_Impl << "}" << std::endl << std::endl;
/* NotifyField */
m_Header << "public:" << std::endl
- << "\t" << "void NotifyField(int id, const Value& cookie = Empty) override;" << std::endl;
+ << "\t" << "void NotifyField(int id, const Value& cookie = Empty) override;" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::NotifyField(int id, const Value& cookie)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Parent.empty())
m_Impl << "\t" << "int real_id = id - " << klass.Parent << "::TypeInstance->GetFieldCount(); " << std::endl
- << "\t" << "if (real_id < 0) { " << klass.Parent << "::NotifyField(id, cookie); return; }" << std::endl;
+ << "\t" << "if (real_id < 0) { " << klass.Parent << "::NotifyField(id, cookie); return; }" << std::endl;
m_Impl << "\t" << "switch (";
num = 0;
for (const Field& field : klass.Fields) {
m_Impl << "\t\t" << "case " << num << ":" << std::endl
- << "\t\t\t" << "Notify" << field.GetFriendlyName() << "(cookie);" << std::endl
- << "\t\t\t" << "break;" << std::endl;
+ << "\t\t\t" << "Notify" << field.GetFriendlyName() << "(cookie);" << std::endl
+ << "\t\t\t" << "break;" << std::endl;
num++;
}
m_Impl << "\t\t" << "default:" << std::endl
- << "\t\t\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl
- << "\t" << "}" << std::endl;
+ << "\t\t\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl
+ << "\t" << "}" << std::endl;
m_Impl << "}" << std::endl << std::endl;
/* NavigateField */
m_Header << "public:" << std::endl
- << "\t" << "virtual Object::Ptr NavigateField(int id) const override;" << std::endl;
+ << "\t" << "virtual Object::Ptr NavigateField(int id) const override;" << std::endl;
m_Impl << "Object::Ptr ObjectImpl<" << klass.Name << ">::NavigateField(int id) const" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!klass.Parent.empty())
m_Impl << "\t" << "int real_id = id - " << klass.Parent << "::TypeInstance->GetFieldCount(); " << std::endl
- << "\t" << "if (real_id < 0) { return " << klass.Parent << "::NavigateField(id); }" << std::endl;
+ << "\t" << "if (real_id < 0) { return " << klass.Parent << "::NavigateField(id); }" << std::endl;
bool haveNavigationFields = false;
for (const Field& field : klass.Fields) {
if (field.Attributes & FANavigation) {
m_Impl << "\t\t" << "case " << num << ":" << std::endl
- << "\t\t\t" << "return Navigate" << field.GetFriendlyName() << "();" << std::endl;
+ << "\t\t\t" << "return Navigate" << field.GetFriendlyName() << "();" << std::endl;
}
num++;
}
m_Impl << "\t\t" << "default:" << std::endl
- << "\t\t";
+ << "\t\t";
}
m_Impl << "\t" << "throw std::runtime_error(\"Invalid field ID.\");" << std::endl;
prot = "public";
m_Header << prot << ":" << std::endl
- << "\t";
+ << "\t";
if (field.Attributes & FAGetVirtual || field.PureGetAccessor)
m_Header << "virtual ";
m_Header << ";" << std::endl;
m_Impl << field.Type.GetRealType() << " ObjectImpl<" << klass.Name << ">::Get" << field.GetFriendlyName() << "(void) const" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (field.GetAccessor.empty() && !(field.Attributes & FANoStorage))
m_Impl << "\t" << "return m_" << field.GetFriendlyName() << ";" << std::endl;
prot = "public";
m_Header << prot << ":" << std::endl
- << "\t";
+ << "\t";
if (field.Attributes & FASetVirtual || field.PureSetAccessor)
m_Header << "virtual ";
m_Header << ";" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::Set" << field.GetFriendlyName() << "(" << field.Type.GetArgumentType() << " value, bool suppress_events, const Value& cookie)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (field.Type.IsName || !field.TrackAccessor.empty())
m_Impl << "\t" << "Value oldValue = Get" << field.GetFriendlyName() << "();" << std::endl;
if (field.Type.IsName || !field.TrackAccessor.empty()) {
if (field.Name != "active") {
m_Impl << "\t" << "ConfigObject *dobj = dynamic_cast<ConfigObject *>(this);" << std::endl
- << "\t" << "if (!dobj || dobj->IsActive())" << std::endl
- << "\t";
+ << "\t" << "if (!dobj || dobj->IsActive())" << std::endl
+ << "\t";
}
m_Impl << "\t" << "Track" << field.GetFriendlyName() << "(oldValue, value);" << std::endl;
}
m_Impl << "\t" << "if (!suppress_events)" << std::endl
- << "\t\t" << "Notify" << field.GetFriendlyName() << "(cookie);" << std::endl
- << "}" << std::endl << std::endl;
+ << "\t\t" << "Notify" << field.GetFriendlyName() << "(cookie);" << std::endl
+ << "}" << std::endl << std::endl;
}
}
m_Header << "\t" << "void Track" << field.GetFriendlyName() << "(" << field.Type.GetArgumentType() << " oldValue, " << field.Type.GetArgumentType() << " newValue);" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::Track" << field.GetFriendlyName() << "(" << field.Type.GetArgumentType() << " oldValue, " << field.Type.GetArgumentType() << " newValue)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (!field.TrackAccessor.empty())
m_Impl << "\t" << field.TrackAccessor << std::endl;
if (field.Type.TypeName != "String") {
if (field.Type.ArrayRank > 0) {
m_Impl << "\t" << "if (oldValue) {" << std::endl
- << "\t\t" << "ObjectLock olock(oldValue);" << std::endl
- << "\t\t" << "for (const String& ref : oldValue) {" << std::endl
- << "\t\t\t" << "DependencyGraph::RemoveDependency(this, ConfigObject::GetObject";
+ << "\t\t" << "ObjectLock olock(oldValue);" << std::endl
+ << "\t\t" << "for (const String& ref : oldValue) {" << std::endl
+ << "\t\t\t" << "DependencyGraph::RemoveDependency(this, ConfigObject::GetObject";
/* Ew */
if (field.Type.TypeName == "Zone" && m_Library == "base")
m_Impl << "<" << field.Type.TypeName << ">(";
m_Impl << "ref).get());" << std::endl
- << "\t\t" << "}" << std::endl
- << "\t" << "}" << std::endl
- << "\t" << "if (newValue) {" << std::endl
- << "\t\t" << "ObjectLock olock(newValue);" << std::endl
- << "\t\t" << "for (const String& ref : newValue) {" << std::endl
- << "\t\t\t" << "DependencyGraph::AddDependency(this, ConfigObject::GetObject";
+ << "\t\t" << "}" << std::endl
+ << "\t" << "}" << std::endl
+ << "\t" << "if (newValue) {" << std::endl
+ << "\t\t" << "ObjectLock olock(newValue);" << std::endl
+ << "\t\t" << "for (const String& ref : newValue) {" << std::endl
+ << "\t\t\t" << "DependencyGraph::AddDependency(this, ConfigObject::GetObject";
/* Ew */
if (field.Type.TypeName == "Zone" && m_Library == "base")
m_Impl << "<" << field.Type.TypeName << ">(";
m_Impl << "ref).get());" << std::endl
- << "\t\t" << "}" << std::endl
- << "\t" << "}" << std::endl;
+ << "\t\t" << "}" << std::endl
+ << "\t" << "}" << std::endl;
} else {
m_Impl << "\t" << "if (!oldValue.IsEmpty())" << std::endl
- << "\t\t" << "DependencyGraph::RemoveDependency(this, ConfigObject::GetObject";
+ << "\t\t" << "DependencyGraph::RemoveDependency(this, ConfigObject::GetObject";
/* Ew */
if (field.Type.TypeName == "Zone" && m_Library == "base")
m_Impl << "<" << field.Type.TypeName << ">(";
m_Impl << "oldValue).get());" << std::endl
- << "\t" << "if (!newValue.IsEmpty())" << std::endl
- << "\t\t" << "DependencyGraph::AddDependency(this, ConfigObject::GetObject";
+ << "\t" << "if (!newValue.IsEmpty())" << std::endl
+ << "\t\t" << "DependencyGraph::AddDependency(this, ConfigObject::GetObject";
/* Ew */
if (field.Type.TypeName == "Zone" && m_Library == "base")
continue;
m_Header << "public:" << std::endl
- << "\t" << "Object::Ptr Navigate" << field.GetFriendlyName() << "(void) const";
+ << "\t" << "Object::Ptr Navigate" << field.GetFriendlyName() << "(void) const";
if (field.PureNavigateAccessor) {
m_Header << " = 0;" << std::endl;
m_Header << ";" << std::endl;
m_Impl << "Object::Ptr ObjectImpl<" << klass.Name << ">::Navigate" << field.GetFriendlyName() << "(void) const" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (field.NavigateAccessor.empty())
m_Impl << "\t" << "return Get" << field.GetFriendlyName() << "();" << std::endl;
/* start/stop */
if (needs_tracking) {
m_Header << "protected:" << std::endl
- << "\tvirtual void Start(bool runtimeCreated = false) override;" << std::endl
- << "\tvirtual void Stop(bool runtimeRemoved = false) override;" << std::endl;
+ << "\tvirtual void Start(bool runtimeCreated = false) override;" << std::endl
+ << "\tvirtual void Stop(bool runtimeRemoved = false) override;" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::Start(bool runtimeCreated)" << std::endl
- << "{" << std::endl
- << "\t" << klass.Parent << "::Start(runtimeCreated);" << std::endl << std::endl;
+ << "{" << std::endl
+ << "\t" << klass.Parent << "::Start(runtimeCreated);" << std::endl << std::endl;
for (const Field& field : klass.Fields) {
if (!field.Type.IsName && field.TrackAccessor.empty())
}
m_Impl << "}" << std::endl << std::endl
- << "void ObjectImpl<" << klass.Name << ">::Stop(bool runtimeRemoved)" << std::endl
- << "{" << std::endl
- << "\t" << klass.Parent << "::Stop(runtimeRemoved);" << std::endl << std::endl;
+ << "void ObjectImpl<" << klass.Name << ">::Stop(bool runtimeRemoved)" << std::endl
+ << "{" << std::endl
+ << "\t" << klass.Parent << "::Stop(runtimeRemoved);" << std::endl << std::endl;
for (const Field& field : klass.Fields) {
if (!field.Type.IsName && field.TrackAccessor.empty())
prot = "public";
m_Header << prot << ":" << std::endl
- << "\t" << "virtual void Notify" << field.GetFriendlyName() << "(const Value& cookie = Empty);" << std::endl;
+ << "\t" << "virtual void Notify" << field.GetFriendlyName() << "(const Value& cookie = Empty);" << std::endl;
m_Impl << "void ObjectImpl<" << klass.Name << ">::Notify" << field.GetFriendlyName() << "(const Value& cookie)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (field.Name != "active") {
m_Impl << "\t" << "ConfigObject *dobj = dynamic_cast<ConfigObject *>(this);" << std::endl
- << "\t" << "if (!dobj || dobj->IsActive())" << std::endl
- << "\t";
+ << "\t" << "if (!dobj || dobj->IsActive())" << std::endl
+ << "\t";
}
m_Impl << "\t" << "On" << field.GetFriendlyName() << "Changed(static_cast<" << klass.Name << " *>(this), cookie);" << std::endl
- << "}" << std::endl << std::endl;
+ << "}" << std::endl << std::endl;
}
/* default */
std::string realType = field.Type.GetRealType();
m_Header << "private:" << std::endl
- << "\t" << "inline " << realType << " GetDefault" << field.GetFriendlyName() << "(void) const;" << std::endl;
+ << "\t" << "inline " << realType << " GetDefault" << field.GetFriendlyName() << "(void) const;" << std::endl;
m_Impl << realType << " ObjectImpl<" << klass.Name << ">::GetDefault" << field.GetFriendlyName() << "(void) const" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (field.DefaultAccessor.empty())
m_Impl << "\t" << "return " << realType << "();" << std::endl;
/* validators */
for (const Field& field : klass.Fields) {
m_Header << "protected:" << std::endl
- << "\t" << "virtual void Validate" << field.GetFriendlyName() << "(" << field.Type.GetArgumentType() << " value, const ValidationUtils& utils);" << std::endl;
+ << "\t" << "virtual void Validate" << field.GetFriendlyName() << "(" << field.Type.GetArgumentType() << " value, const ValidationUtils& utils);" << std::endl;
}
/* instance variables */
m_Impl << "const String& key, ";
m_Impl << fieldType.GetArgumentType() << " value, std::vector<String>& location, const ValidationUtils& utils)" << std::endl
- << "{" << std::endl;
+ << "{" << std::endl;
if (validatorType == ValidatorField) {
bool required = false;
if (rule.IsName) {
m_Impl << "\t\t" << "if (value.IsScalar()) {" << std::endl
- << "\t\t\t" << "if (utils.ValidateName(\"" << rule.Type << "\", value))" << std::endl
- << "\t\t\t\t" << "return;" << std::endl
- << "\t\t\t" << "else" << std::endl
- << "\t\t\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_pointer_cast<ConfigObject>(object), location, \"Object '\" + value + \"' of type '" << rule.Type << "' does not exist.\"));" << std::endl
- << "\t\t" << "}" << std::endl;
+ << "\t\t\t" << "if (utils.ValidateName(\"" << rule.Type << "\", value))" << std::endl
+ << "\t\t\t\t" << "return;" << std::endl
+ << "\t\t\t" << "else" << std::endl
+ << "\t\t\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_pointer_cast<ConfigObject>(object), location, \"Object '\" + value + \"' of type '" << rule.Type << "' does not exist.\"));" << std::endl
+ << "\t\t" << "}" << std::endl;
}
if (fieldType.GetRealType() == "Value") {
if (rule.Type == "String")
m_Impl << "\t\t" << "if (value.IsEmpty() || value.IsScalar())" << std::endl
- << "\t\t\t" << "return;" << std::endl;
+ << "\t\t\t" << "return;" << std::endl;
else if (rule.Type == "Number") {
m_Impl << "\t\t" << "try {" << std::endl
- << "\t\t\t" << "Convert::ToDouble(value);" << std::endl
- << "\t\t\t" << "return;" << std::endl
- << "\t\t" << "} catch (...) { }" << std::endl;
+ << "\t\t\t" << "Convert::ToDouble(value);" << std::endl
+ << "\t\t\t" << "return;" << std::endl
+ << "\t\t" << "} catch (...) { }" << std::endl;
}
}
m_Impl << "\t\t" << "const Dictionary::Ptr& dict = value;" << std::endl;
m_Impl << (type_check ? "\t" : "") << "\t\t" << "{" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t" << "ObjectLock olock(dict);" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t" << "for (const Dictionary::Pair& kv : dict) {" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t\t" << "const String& akey = kv.first;" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t\t" << "const Value& avalue = kv.second;" << std::endl;
+ << (type_check ? "\t" : "") << "\t\t\t" << "ObjectLock olock(dict);" << std::endl
+ << (type_check ? "\t" : "") << "\t\t\t" << "for (const Dictionary::Pair& kv : dict) {" << std::endl
+ << (type_check ? "\t" : "") << "\t\t\t\t" << "const String& akey = kv.first;" << std::endl
+ << (type_check ? "\t" : "") << "\t\t\t\t" << "const Value& avalue = kv.second;" << std::endl;
indent = true;
} else if (rule.Type == "Array") {
if (type_check)
m_Impl << "\t\t" << "const Array::Ptr& arr = value;" << std::endl;
m_Impl << (type_check ? "\t" : "") << "\t\t" << "Array::SizeType anum = 0;" << std::endl
- << (type_check ? "\t" : "") << "\t\t" << "{" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t" << "ObjectLock olock(arr);" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t" << "for (const Value& avalue : arr) {" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t\t" << "String akey = Convert::ToString(anum);" << std::endl;
+ << (type_check ? "\t" : "") << "\t\t" << "{" << std::endl
+ << (type_check ? "\t" : "") << "\t\t\t" << "ObjectLock olock(arr);" << std::endl
+ << (type_check ? "\t" : "") << "\t\t\t" << "for (const Value& avalue : arr) {" << std::endl
+ << (type_check ? "\t" : "") << "\t\t\t\t" << "String akey = Convert::ToString(anum);" << std::endl;
indent = true;
} else {
m_Impl << (type_check ? "\t" : "") << "\t\t" << "String akey = \"\";" << std::endl
- << (type_check ? "\t" : "") << "\t\t" << "const Value& avalue = value;" << std::endl;
+ << (type_check ? "\t" : "") << "\t\t" << "const Value& avalue = value;" << std::endl;
}
std::string subvalidator_prefix;
subvalidator_prefix = name;
m_Impl << (type_check ? "\t" : "") << (indent ? "\t\t" : "") << "\t\t" << "location.push_back(akey);" << std::endl
- << (type_check ? "\t" : "") << (indent ? "\t\t" : "") << "\t\t" << "TIValidate" << subvalidator_prefix << "_" << i << "(object, akey, avalue, location, utils);" << std::endl
- << (type_check ? "\t" : "") << (indent ? "\t\t" : "") << "\t\t" << "location.pop_back();" << std::endl;
+ << (type_check ? "\t" : "") << (indent ? "\t\t" : "") << "\t\t" << "TIValidate" << subvalidator_prefix << "_" << i << "(object, akey, avalue, location, utils);" << std::endl
+ << (type_check ? "\t" : "") << (indent ? "\t\t" : "") << "\t\t" << "location.pop_back();" << std::endl;
if (rule.Type == "Array")
m_Impl << (type_check ? "\t" : "") << "\t\t\t\t" << "anum++;" << std::endl;
if (rule.Type == "Dictionary" || rule.Type == "Array") {
m_Impl << (type_check ? "\t" : "") << "\t\t\t" << "}" << std::endl
- << (type_check ? "\t" : "") << "\t\t" << "}" << std::endl;
+ << (type_check ? "\t" : "") << "\t\t" << "}" << std::endl;
}
for (const Rule& srule : rule.Rules) {
if (rule.Type == "Dictionary") {
m_Impl << (type_check ? "\t" : "") << "\t\t" << "if (dict->Get(\"" << srule.Pattern << "\").IsEmpty())" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_pointer_cast<ConfigObject>(object), location, \"Required dictionary item '" << srule.Pattern << "' is not set.\"));" << std::endl;
+ << (type_check ? "\t" : "") << "\t\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_pointer_cast<ConfigObject>(object), location, \"Required dictionary item '" << srule.Pattern << "' is not set.\"));" << std::endl;
} else if (rule.Type == "Array") {
int index = -1;
std::stringstream idxbuf;
}
m_Impl << (type_check ? "\t" : "") << "\t\t" << "if (arr.GetLength() < " << (index + 1) << ")" << std::endl
- << (type_check ? "\t" : "") << "\t\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_cast<ConfigObject *>(this), location, \"Required index '" << index << "' is not set.\"));" << std::endl;
+ << (type_check ? "\t" : "") << "\t\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_cast<ConfigObject *>(this), location, \"Required index '" << index << "' is not set.\"));" << std::endl;
}
}
}
if (type_check || validatorType != ValidatorField) {
if (validatorType != ValidatorField) {
m_Impl << "\t" << "if (!known_attribute)" << std::endl
- << "\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_pointer_cast<ConfigObject>(object), location, \"Invalid attribute: \" + key));" << std::endl
- << "\t" << "else" << std::endl;
+ << "\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_pointer_cast<ConfigObject>(object), location, \"Invalid attribute: \" + key));" << std::endl
+ << "\t" << "else" << std::endl;
}
m_Impl << (validatorType != ValidatorField ? "\t" : "") << "\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_pointer_cast<ConfigObject>(object), location, \"Invalid type.\"));" << std::endl;
for (const auto& it : m_MissingValidators) {
m_Impl << "void ObjectImpl<" << it.first.first << ">::Validate" << it.first.second << "(" << it.second.Type.GetArgumentType() << " value, const ValidationUtils& utils)" << std::endl
- << "{" << std::endl
- << "\t" << "SimpleValidate" << it.first.second << "(value, utils);" << std::endl
- << "\t" << "std::vector<String> location;" << std::endl
- << "\t" << "location.push_back(\"" << it.second.Name << "\");" << std::endl
- << "\t" << "TIValidate" << it.first.first << it.first.second << "(this, value, location, utils);" << std::endl
- << "\t" << "location.pop_back();" << std::endl
- << "}" << std::endl << std::endl;
+ << "{" << std::endl
+ << "\t" << "SimpleValidate" << it.first.second << "(value, utils);" << std::endl
+ << "\t" << "std::vector<String> location;" << std::endl
+ << "\t" << "location.push_back(\"" << it.second.Name << "\");" << std::endl
+ << "\t" << "TIValidate" << it.first.first << it.first.second << "(this, value, location, utils);" << std::endl
+ << "\t" << "location.pop_back();" << std::endl
+ << "}" << std::endl << std::endl;
}
m_MissingValidators.clear();
{
for (const auto& it : m_MissingValidators) {
m_Impl << "void ObjectImpl<" << it.first.first << ">::Validate" << it.first.second << "(" << it.second.Type.GetArgumentType() << " value, const ValidationUtils& utils)" << std::endl
- << "{" << std::endl
- << "\t" << "SimpleValidate" << it.first.second << "(value, utils);" << std::endl
- << "}" << std::endl << std::endl;
+ << "{" << std::endl
+ << "\t" << "SimpleValidate" << it.first.second << "(value, utils);" << std::endl
+ << "}" << std::endl << std::endl;
}
m_MissingValidators.clear();
}
void ClassCompiler::CompileFile(const std::string& inputpath,
- const std::string& implpath, const std::string& headerpath)
+ const std::string& implpath, const std::string& headerpath)
{
std::ifstream input;
input.open(inputpath.c_str(), std::ifstream::in);
}
void ClassCompiler::CompileStream(const std::string& path, std::istream& input,
- std::ostream& oimpl, std::ostream& oheader)
+ std::ostream& oimpl, std::ostream& oheader)
{
input.exceptions(std::istream::badbit);
<< "#include <boost/signals2.hpp>" << std::endl << std::endl;
oimpl << "#include \"base/exception.hpp\"" << std::endl
- << "#include \"base/objectlock.hpp\"" << std::endl
- << "#include \"base/utility.hpp\"" << std::endl
- << "#include \"base/convert.hpp\"" << std::endl
- << "#include \"base/dependencygraph.hpp\"" << std::endl
- << "#include \"base/logger.hpp\"" << std::endl
- << "#include \"base/function.hpp\"" << std::endl
- << "#include \"base/configtype.hpp\"" << std::endl
- << "#include <boost/assign/list_of.hpp>" << std::endl
- << "#ifdef _MSC_VER" << std::endl
- << "#pragma warning( push )" << std::endl
- << "#pragma warning( disable : 4244 )" << std::endl
- << "#pragma warning( disable : 4800 )" << std::endl
- << "#endif /* _MSC_VER */" << std::endl << std::endl;
+ << "#include \"base/objectlock.hpp\"" << std::endl
+ << "#include \"base/utility.hpp\"" << std::endl
+ << "#include \"base/convert.hpp\"" << std::endl
+ << "#include \"base/dependencygraph.hpp\"" << std::endl
+ << "#include \"base/logger.hpp\"" << std::endl
+ << "#include \"base/function.hpp\"" << std::endl
+ << "#include \"base/configtype.hpp\"" << std::endl
+ << "#include <boost/assign/list_of.hpp>" << std::endl
+ << "#ifdef _MSC_VER" << std::endl
+ << "#pragma warning( push )" << std::endl
+ << "#pragma warning( disable : 4244 )" << std::endl
+ << "#pragma warning( disable : 4800 )" << std::endl
+ << "#endif /* _MSC_VER */" << std::endl << std::endl;
ClassCompiler ctx(path, input, oimpl, oheader);
void CodeGenValidatorSubrules(const std::string& name, const std::string& klass, const std::vector<Rule>& rules);
static void CompileFile(const std::string& inputpath, const std::string& implpath,
- const std::string& headerpath);
+ const std::string& headerpath);
static void CompileStream(const std::string& path, std::istream& input,
- std::ostream& oimpl, std::ostream& oheader);
+ std::ostream& oimpl, std::ostream& oheader);
static void OptimizeStructLayout(std::vector<Field>& fields);
}
fprintf(outfp, "/* This file has been automatically generated\n"
- " from the input file \"%s\". */\n\n", argv[1]);
+ " from the input file \"%s\". */\n\n", argv[1]);
fputs("#include \"config/configfragment.hpp\"\n\nnamespace {\n\nconst char *fragment = R\"CONFIG_FRAGMENT(", outfp);
while (!feof(infp)) {