void CheckMKClient::send(connection_data con) { try { NSC_DEBUG_MSG_STD("Connection details: " + con.to_string()); if (con.ssl.enabled) { #ifndef USE_SSL NSC_LOG_ERROR_STD(_T("SSL not avalible (compiled without USE_SSL)")); return response; #endif } socket_helpers::client::client<check_mk::client::protocol> client(con, boost::shared_ptr<client_handler>(new client_handler())); client.connect(); std::string dummy; check_mk::packet packet = client.process_request(dummy); boost::optional<scripts::command_definition<lua::lua_traits> > cmd = scripts_->find_command("check_mk", "c_callback"); if (cmd) { parse_data(cmd->information, cmd->function, packet); } else { NSC_LOG_ERROR_STD("No check_mk callback found!"); } //lua_runtime_->on_query() client.shutdown(); } catch (std::runtime_error &e) { NSC_LOG_ERROR_EXR("Failed to send", e); } catch (std::exception &e) { NSC_LOG_ERROR_EXR("Failed to send", e); } catch (...) { NSC_LOG_ERROR_EX("Failed to send"); } }
void SyslogClient::add_target(std::wstring key, std::wstring arg) { try { targets.add(get_settings_proxy(), target_path , key, arg); } catch (const std::exception &e) { NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key + _T(", ") + utf8::to_unicode(e.what())); } catch (...) { NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key); } }
bool Scheduler::handle_schedule(schedules::target_object item) { try { std::string response; nscapi::core_helper ch(get_core(), get_id()); if (!ch.simple_query(item->command.c_str(), item->arguments, response)) { NSC_LOG_ERROR("Failed to execute: " + item->command); if (item->channel.empty()) { NSC_LOG_ERROR_WA("No channel specified for ", item->get_alias()); return true; } nscapi::protobuf::functions::create_simple_submit_request(item->channel, item->command, NSCAPI::query_return_codes::returnUNKNOWN, "Command was not found: " + item->command, "", response); std::string result; get_core()->submit_message(item->channel, response, result); return true; } Plugin::QueryResponseMessage resp_msg; resp_msg.ParseFromString(response); Plugin::QueryResponseMessage resp_msg_send; resp_msg_send.mutable_header()->CopyFrom(resp_msg.header()); BOOST_FOREACH(const Plugin::QueryResponseMessage::Response &p, resp_msg.payload()) { if (nscapi::report::matches(item->report, nscapi::protobuf::functions::gbp_to_nagios_status(p.result()))) resp_msg_send.add_payload()->CopyFrom(p); } if (resp_msg_send.payload_size() > 0) { if (item->channel.empty()) { NSC_LOG_ERROR_STD("No channel specified for " + item->get_alias() + " mssage will not be sent."); return true; } nscapi::protobuf::functions::make_submit_from_query(response, item->channel, item->get_alias(), item->target_id, item->source_id); std::string result; if (!get_core()->submit_message(item->channel, response, result)) { NSC_LOG_ERROR_STD("Failed to submit: " + item->get_alias()); return true; } std::string error; if (!nscapi::protobuf::functions::parse_simple_submit_response(result, error)) { NSC_LOG_ERROR_STD("Failed to submit " + item->get_alias() + ": " + error); return true; } } else { NSC_DEBUG_MSG("Filter not matched for: " + item->get_alias() + " so nothing is reported"); } return true; } catch (nscapi::nscapi_exception &e) { NSC_LOG_ERROR_EXR("Failed to register command: ", e); return false; } catch (std::exception &e) { NSC_LOG_ERROR_EXR("Exception: ", e); return false; } catch (...) { NSC_LOG_ERROR_EX(item->get_alias()); return false; } }
void SyslogClient::add_command(std::wstring name, std::wstring args) { try { std::wstring key = commands.add_command(name, args); if (!key.empty()) register_command(key.c_str(), _T("NRPE relay for: ") + name); } catch (boost::program_options::validation_error &e) { NSC_LOG_ERROR_STD(_T("Could not add command ") + name + _T(": ") + utf8::to_unicode(e.what())); } catch (...) { NSC_LOG_ERROR_STD(_T("Could not add command ") + name); } }
bool LUAScript::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) { //std::wstring appRoot = file_helpers::folders::get_local_appdata_folder(SZAPPNAME); try { root_ = get_core()->getBasePath(); sh::settings_registry settings(get_settings_proxy()); settings.set_alias(alias, _T("lua")); settings.alias().add_path_to_settings() (_T("LUA SCRIPT SECTION"), _T("Section for the LUAScripts module.")) (_T("scripts"), sh::fun_values_path(boost::bind(&LUAScript::loadScript, this, _1, _2)), _T("LUA SCRIPTS SECTION"), _T("A list of scripts available to run from the LuaSCript module.")) ; settings.register_all(); settings.notify(); // if (!scriptDirectory_.empty()) { // addAllScriptsFrom(scriptDirectory_); // } BOOST_FOREACH(script_container &script, scripts_) { try { instances_.push_back(script_wrapper::lua_script::create_instance(get_core(), get_id(), registry, script.alias, script.script.string())); } catch (const lua_wrappers::LUAException &e) { NSC_LOG_ERROR_STD(_T("Could not load script ") + script.to_wstring() + _T(": ") + e.getMessage()); } catch (const std::exception &e) { NSC_LOG_ERROR_STD(_T("Could not load script ") + script.to_wstring() + _T(": ") + utf8::to_unicode(e.what())); } } // } catch (nrpe::server::nrpe_exception &e) { // NSC_LOG_ERROR_STD(_T("Exception caught: ") + e.what()); // return false; } catch (const std::exception &e) { NSC_LOG_ERROR_STD(_T("Exception caught: ") + utf8::to_unicode(e.what())); return false; } catch (...) { NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>")); return false; } // std::list<std::wstring>::const_iterator it; // for (it = commands.begin(); it != commands.end(); ++it) { // loadScript((*it)); // } return true; }
bool DistributedClient::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) { std::map<std::wstring,std::wstring> commands; try { sh::settings_registry settings(get_settings_proxy()); settings.set_alias(_T("distributed"), alias, _T("client")); target_path = settings.alias().get_settings_path(_T("targets")); settings.alias().add_path_to_settings() (_T("Distributed NSCP CLIENT SECTION"), _T("Section for NSCP active/passive check module.")) (_T("handlers"), sh::fun_values_path(boost::bind(&DistributedClient::add_command, this, _1, _2)), _T("CLIENT HANDLER SECTION"), _T("")) (_T("targets"), sh::fun_values_path(boost::bind(&DistributedClient::add_target, this, _1, _2)), _T("REMOTE TARGET DEFINITIONS"), _T("")) ; settings.alias().add_key_to_settings() (_T("channel"), sh::wstring_key(&channel_, _T("DNSCP")), _T("CHANNEL"), _T("The channel to listen to.")) ; settings.register_all(); settings.notify(); targets.add_missing(get_settings_proxy(), target_path, _T("default"), _T(""), true); get_core()->registerSubmissionListener(get_id(), channel_); register_command(_T("dnscp_query"), _T("Submit a query to a remote host via NSCP")); register_command(_T("dnscp_forward"), _T("Forward query to remote NSCP host")); register_command(_T("dnscp_submit"), _T("Submit a query to a remote host via NSCP")); register_command(_T("dnscp_exec"), _T("Execute remote command on a remote host via NSCP")); register_command(_T("dnscp_help"), _T("Help on using NSCP Client")); } catch (nscapi::nscapi_exception &e) { NSC_LOG_ERROR_STD(_T("NSClient API exception: ") + utf8::to_unicode(e.what())); return false; } catch (std::exception &e) { NSC_LOG_ERROR_STD(_T("Exception caught: ") + utf8::to_unicode(e.what())); return false; } catch (...) { NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>")); return false; } return true; }
bool NSCPServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) { sh::settings_registry settings(get_settings_proxy()); settings.set_alias("nscp", alias, "server"); settings.alias().add_path_to_settings() ("NSCP SERVER SECTION", "Section for NSCP (NSCPListener.dll) (check_nscp) protocol options.") ; settings.alias().add_key_to_settings() ("port", sh::string_key(&info_.port_, "5668"), "PORT NUMBER", "Port to use for NSCP.") ("allow arguments", sh::bool_fun_key<bool>(boost::bind(&handler_impl::set_allow_arguments, handler_, _1), false), "COMMAND ARGUMENT PROCESSING", "This option determines whether or not the we will allow clients to specify arguments to commands that are executed.") ; socket_helpers::settings_helper::add_core_server_opts(settings, info_); socket_helpers::settings_helper::add_ssl_server_opts(settings, info_, true); settings.register_all(); settings.notify(); #ifndef USE_SSL if (info_.use_ssl) { NSC_LOG_ERROR_STD(_T("SSL not avalible! (not compiled with openssl support)")); return false; } #endif boost::asio::io_service io_service_; if (mode == NSCAPI::normalStart) { NSC_LOG_ERROR_LISTS(info_.validate()); std::list<std::string> errors; info_.allowed_hosts.refresh(errors); NSC_LOG_ERROR_LISTS(errors); NSC_DEBUG_MSG_STD("Allowed hosts definition: " + info_.allowed_hosts.to_string()); server_.reset(new nscp::server::server(info_, handler_)); if (!server_) { NSC_LOG_ERROR_STD("Failed to create server instance!"); return false; } server_->start(); } return true; }
bool DistributedServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) { std::wstring host, suffix, server_mode; unsigned int thread_count; try { sh::settings_registry settings(get_settings_proxy()); settings.set_alias(_T("distributed"), alias, _T("server")); settings.alias().add_path_to_settings() (_T("DISTRIBUTED NSCP SERVER SECTION"), _T("Section for Distributed NSCP (DistributedServer) (check_nscp) protocol options.")) ; settings.alias().add_key_to_settings() (_T("host"), sh::wstring_key(&host, _T("tcp://*:5555")), _T("HOST TO BIND/CONNECT TO"), _T("The host to bind/connect to")) (_T("suffix"), sh::wstring_key(&suffix, _T("ncsp.dist")), _T("SUFFIX FOR INTERNAL CHANNELS"), _T("Has to be uniq on each server")) (_T("worker pool size"), sh::uint_key(&thread_count, 10), _T("WORKER POOL SIZE"), _T("Number of threads to spawn for the worker pool")) (_T("mode"), sh::wstring_key(&server_mode, _T("master")), _T("OPERATION MODE"), _T("Mode of operation can only be master now but will add more later on (such as slave)")) ; settings.register_all(); settings.notify(); if (mode == NSCAPI::normalStart) { context = new zmq::context_t(2); zeromq_queue::connection_info queue_info(to_string(host), to_string(suffix)); zeromq_queue::queue_manager queue; queue.start(context, threads, queue_info); zeromq_worker::connection_info worker_info(queue_info.get_backend(), to_string(suffix), thread_count); zeromq_worker::worker_manager workers; workers.start(context, threads, worker_info); } } catch (std::exception &e) { NSC_LOG_ERROR_STD(_T("Exception caught: ") + to_wstring(e.what())); return false; } catch (...) { NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>")); return false; } return true; }
nscp::packet NSCPClient::clp_handler_impl::send(connection_data con, nscp::packet &packet) { nscp::packet response; try { if (con.ssl.enabled) { #ifndef USE_SSL NSC_LOG_ERROR_STD("SSL not avalible (compiled without USE_SSL)"); return response; #endif } socket_helpers::client::client<nscp::client::protocol> client(con, boost::shared_ptr<client_handler>(new client_handler())); client.connect(); response = client.process_request(packet); client.shutdown(); return response; } catch (std::runtime_error &e) { NSC_LOG_ERROR_EXR("Failed to send", e); return response; } catch (std::exception &e) { NSC_LOG_ERROR_EXR("Failed to send", e); return response; } catch (...) { NSC_LOG_ERROR_EX("Failed to send"); return response; } }
void CheckExternalScripts::addAllScriptsFrom(std::string str_path) { std::string pattern = "*.*"; boost::filesystem::path path(str_path); if (!boost::filesystem::is_directory(path)) { if (path.has_relative_path()) path = get_base_path() / path; if (!boost::filesystem::is_directory(path)) { file_helpers::patterns::pattern_type split_path = file_helpers::patterns::split_pattern(path); if (!boost::filesystem::is_directory(split_path.first)) { NSC_LOG_ERROR_STD("Path was not found: " + split_path.first.string()); return; } path = split_path.first; pattern = split_path.second.string(); } } NSC_DEBUG_MSG("Using script path: " + path.string()); boost::regex re; try { std::string pre = file_helpers::patterns::glob_to_regexp(pattern); NSC_DEBUG_MSG("Using regexp: " + pre); re = pre; } catch (std::exception &e) { NSC_LOG_ERROR_EXR("Invalid pattern: " + pattern, e); return; } boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator itr(path); itr != end_itr; ++itr) { if (!is_directory(itr->status())) { std::string name = file_helpers::meta::get_filename(itr->path()); if (regex_match(name, re)) add_command(name, itr->path().string()); } } }
int DistributedClient::clp_handler_impl::exec(client::configuration::data_type data, const Plugin::ExecuteRequestMessage &request_message, std::string &reply) { const ::Plugin::Common_Header& request_header = request_message.header(); int ret = NSCAPI::returnOK; connection_data con = parse_header(request_header, data); Plugin::ExecuteResponseMessage response_message; nscapi::functions::make_return_header(response_message.mutable_header(), request_header); std::list<nscp::packet> chunks; chunks.push_back(nscp::factory::create_envelope_request(1)); chunks.push_back(nscp::factory::create_payload(nscp::data::exec_request, request_message.SerializeAsString(), 0)); chunks = instance->send(con, chunks); BOOST_FOREACH(nscp::packet &chunk, chunks) { if (nscp::checks::is_exec_response(chunk)) { nscapi::functions::append_response_payloads(response_message, chunk.payload); } else if (nscp::checks::is_error(chunk)) { std::string error = gather_and_log_errors(chunk.payload); nscapi::functions::append_simple_exec_response_payload(response_message.add_payload(), "", NSCAPI::returnUNKNOWN, error); ret = NSCAPI::returnUNKNOWN; } else { NSC_LOG_ERROR_STD(_T("Unsupported message type: ") + strEx::itos(chunk.signature.payload_type)); nscapi::functions::append_simple_exec_response_payload(response_message.add_payload(), "", NSCAPI::returnUNKNOWN, "Unsupported response type"); ret = NSCAPI::returnUNKNOWN; } } response_message.SerializeToString(&reply); return ret; }
std::wstring get_dll() const { try { return simple_registry::registry_key::get_string(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\") + file_ + (std::wstring)_T("\\") + get_source(), _T("EventMessageFile")); } catch (simple_registry::registry_exception &e) { NSC_LOG_ERROR_STD(_T("Could not extract DLL for eventsource: ") + get_source() + _T(": ") + e.what()); return _T(""); } }
void lua::lua_runtime::on_query(std::string command, script_information *information, lua::lua_traits::function_type function, bool simple, const Plugin::QueryRequestMessage::Request &request, Plugin::QueryResponseMessage::Response *response, const Plugin::QueryRequestMessage &request_message) { lua_wrapper lua(prep_function(information, function)); int args = 2; if (function.object_ref != 0) args = 3; if (simple) { std::list<std::string> argslist; for (int i=0;i<request.arguments_size();i++) argslist.push_back(request.arguments(i)); lua.push_string(command); lua.push_array(argslist); if (lua.pcall(args, 3, 0) != 0) return nscapi::protobuf::functions::set_response_bad(*response, "Failed to handle command: " + command + ": " + lua.pop_string()); NSCAPI::nagiosReturn ret = NSCAPI::returnUNKNOWN; if (lua.size() < 3) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_query_response_payload(response, command, NSCAPI::returnUNKNOWN, "Invalid return", ""); return; } std::string msg, perf; perf = lua.pop_string(); msg = lua.pop_string(); ret = lua.pop_code(); lua.gc(LUA_GCCOLLECT, 0); nscapi::protobuf::functions::append_simple_query_response_payload(response, command, ret, msg, perf); } else { lua.push_string(command); lua.push_raw_string(request.SerializeAsString()); lua.push_raw_string(request_message.SerializeAsString()); args++; if (lua.pcall(args, 1, 0) != 0) return nscapi::protobuf::functions::set_response_bad(*response, "Failed to handle command: " + command + ": " + lua.pop_string()); if (lua.size() < 1) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_query_response_payload(response, command, NSCAPI::returnUNKNOWN, "Invalid return data", ""); return; } Plugin::QueryResponseMessage local_response; std::string data = lua.pop_raw_string(); response->ParseFromString(data); lua.gc(LUA_GCCOLLECT, 0); } }
std::string gather_and_log_errors(std::string &payload) { NSCPIPC::ErrorMessage message; message.ParseFromString(payload); std::string ret; for (int i=0;i<message.error_size();i++) { ret += message.error(i).message(); NSC_LOG_ERROR_STD(_T("Error: ") + utf8::cvt<std::wstring>(message.error(i).message())); } return ret; }
bool DistributedServer::unloadModule() { try { delete context; context = NULL; threads.join_all(); } catch (...) { NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN>")); return false; } return true; }
check_mk::packet handler_impl::process() { boost::optional<scripts::command_definition<lua::lua_traits> > cmd = scripts_->find_command("check_mk", "s_callback"); if (!cmd) { NSC_LOG_ERROR_STD("No check_mk callback found!"); return check_mk::packet(); } lua::lua_wrapper instance(lua::lua_runtime::prep_function(cmd->information, cmd->function)); int args = 1; if (cmd->function.object_ref != 0) args = 2; check_mk::check_mk_packet_wrapper* obj = Luna<check_mk::check_mk_packet_wrapper>::createNew(instance); if (instance.pcall(args, LUA_MULTRET, 0) != 0) { NSC_LOG_ERROR_STD("Failed to process check_mk result: " + instance.pop_string()); return check_mk::packet(); } check_mk::packet packet = obj->packet; instance.gc(LUA_GCCOLLECT, 0); return packet; }
bool NSClientServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) { sh::settings_registry settings(get_settings_proxy()); settings.set_alias("NSClient", alias, "server"); settings.alias().add_path_to_settings() ("NSCLIENT SERVER SECTION", "Section for NSClient (NSClientServer.dll) (check_nt) protocol options.") ; settings.alias().add_key_to_settings() ("performance data", sh::bool_fun_key<bool>(boost::bind(&NSClientServer::set_perf_data, this, _1), true), "PERFORMANCE DATA", "Send performance data back to Nagios (set this to 0 to remove all performance data).") ; socket_helpers::settings_helper::add_port_server_opts(settings, info_, "12489"); socket_helpers::settings_helper::add_ssl_server_opts(settings, info_, false); socket_helpers::settings_helper::add_core_server_opts(settings, info_); settings.alias().add_parent("/settings/default").add_key_to_settings() ("password", sh::string_fun_key<std::string>(boost::bind(&NSClientServer::set_password, this, _1), ""), "PASSWORD", "Password used to authenticate against server") ; settings.register_all(); settings.notify(); #ifndef USE_SSL if (info_.use_ssl) { NSC_LOG_ERROR_STD(_T("SSL not avalible! (not compiled with openssl support)")); } #endif NSC_LOG_ERROR_LISTS(info_.validate()); std::list<std::string> errors; info_.allowed_hosts.refresh(errors); BOOST_FOREACH(const std::string &e, errors) { NSC_LOG_ERROR_STD(e); }
bool NSCAServer::unloadModule() { try { if (server_) { server_->stop(); server_.reset(); } } catch (...) { NSC_LOG_ERROR_STD("Exception caught: <UNKNOWN>"); return false; } return true; }
NSCAPI::nagiosReturn lua::lua_wrapper::string_to_code(std::string str) { if ((str == "critical")||(str == "crit")||(str == "error")) { return NSCAPI::returnCRIT; } else if ((str == "warning")||(str == "warn")) { return NSCAPI::returnWARN; } else if (str == "ok") { return NSCAPI::returnOK; } else if (str == "unknown") { return NSCAPI::returnUNKNOWN; } NSC_LOG_ERROR_STD("Invalid code: " + str); return NSCAPI::returnUNKNOWN; }
void CheckExternalScripts::query_fallback(const Plugin::QueryRequestMessage::Request &request, Plugin::QueryResponseMessage::Response *response, const Plugin::QueryRequestMessage &) { if (!provider_) { NSC_LOG_ERROR_STD("No provider found: " + request.command()); nscapi::protobuf::functions::set_response_bad(*response, "No command or alias found matching: " + request.command()); return; } commands::command_object_instance command_def = provider_->find_command(request.command()); std::list<std::string> args; for (int i = 0; i < request.arguments_size(); ++i) { args.push_back(request.arguments(i)); } if (command_def) { handle_command(*command_def, args, response); return; } alias::command_object_instance alias_def = aliases_.find_object(request.command()); if (alias_def) { handle_alias(*alias_def, args, response); return; } NSC_LOG_ERROR_STD("No command or alias found matching: " + request.command()); nscapi::protobuf::functions::set_response_bad(*response, "No command or alias found matching: " + request.command()); }
NSCAPI::nagiosReturn CheckMKClient::parse_data(lua::script_information *information, lua::lua_traits::function_type c, const check_mk::packet &packet) { lua::lua_wrapper instance(lua::lua_runtime::prep_function(information, c)); int args = 1; if (c.object_ref != 0) args = 2; check_mk::check_mk_packet_wrapper* obj = Luna<check_mk::check_mk_packet_wrapper>::createNew(instance); obj->packet = packet; if (instance.pcall(args, LUA_MULTRET, 0) != 0) { NSC_LOG_ERROR_STD("Failed to process check_mk result: " + instance.pop_string()); return NSCAPI::returnUNKNOWN; } instance.gc(LUA_GCCOLLECT, 0); return NSCAPI::returnUNKNOWN; }
void send(const connection_data target, const collectd::collectd_builder::packet_list &packets) { NSC_DEBUG_MSG("Sending " + str::xtos(packets.size()) + " packets to: " + target.to_string()); BOOST_FOREACH(const collectd::packet &p, packets) { try { boost::asio::io_service io_service; boost::asio::ip::address target_address = boost::asio::ip::address::from_string(target.get_address()); boost::asio::ip::udp::resolver resolver(io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::host_name(), ""); boost::asio::ip::udp::resolver::iterator endpoint_iterator = resolver.resolve(query); boost::asio::ip::udp::resolver::iterator end; bool is_multicast = false; if (target_address.is_v4()) { is_multicast = target_address.to_v4().is_multicast(); } #if BOOST_VERSION >= 105300 else if (target_address.is_v6()) { is_multicast = target_address.to_v6().is_multicast(); } #endif if (is_multicast) { while (endpoint_iterator != end) { std::string ss = endpoint_iterator->endpoint().address().to_string(); if (target_address.is_v4() && endpoint_iterator->endpoint().address().is_v4()) { std::cout << endpoint_iterator->endpoint().address().to_string() << std::endl; udp_sender s(io_service, endpoint_iterator->endpoint(), target_address, target.get_int_port()); s.send_data(p.get_buffer()); io_service.run(); } endpoint_iterator++; } } else { udp_sender s(io_service, target_address, target.get_int_port()); s.send_data(p.get_buffer()); io_service.run(); } } catch (std::exception& e) { NSC_LOG_ERROR_STD(utf8::utf8_from_native(e.what())); } } }
void lua::lua_runtime::exec_main(script_information *information, const std::vector<std::string> &opts, Plugin::ExecuteResponseMessage::Response *response) { lua_wrapper lua(prep_function(information, "main")); lua.push_array(opts); if (lua.pcall(1, 2, 0) != 0) return nscapi::protobuf::functions::set_response_bad(*response, "Failed to handle command main: " + lua.pop_string()); NSCAPI::nagiosReturn ret = NSCAPI::returnUNKNOWN; if (lua.size() < 2) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_exec_response_payload(response, "", NSCAPI::returnUNKNOWN, "Invalid return"); return; } std::string msg; msg = lua.pop_string(); ret = lua.pop_code(); lua.gc(LUA_GCCOLLECT, 0); nscapi::protobuf::functions::append_simple_exec_response_payload(response, "", ret, msg); }
void CheckExternalScripts::addAllScriptsFrom(std::string str_path) { boost::filesystem::path path(str_path); if (path.has_relative_path()) path = get_base_path() / path; file_helpers::patterns::pattern_type split_path = file_helpers::patterns::split_pattern(path); if (!boost::filesystem::is_directory(split_path.first)) NSC_LOG_ERROR_STD("Path was not found: " + split_path.first.string()); boost::regex pattern(split_path.second.string()); boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end for ( boost::filesystem::directory_iterator itr( split_path.first ); itr != end_itr; ++itr ) { if ( !is_directory(itr->status()) ) { std::string name = file_helpers::meta::get_filename(itr->path()); if (regex_match(name, pattern)) add_command(name, (split_path.first / name).string()); } } }
NSCAPI::nagiosReturn lua::lua_wrapper::get_code(int pos) { std::string str; if (pos == -1) pos = lua_gettop(L); if (pos == 0) return NSCAPI::returnUNKNOWN; switch (lua_type(L, pos)) { case LUA_TNUMBER: return static_cast<int>(lua_tonumber(L, pos)); case LUA_TSTRING: return string_to_code(lua_tostring(L, pos)); case LUA_TBOOLEAN: return lua_toboolean(L, pos)?NSCAPI::returnOK:NSCAPI::returnCRIT; } NSC_LOG_ERROR_STD("Incorrect type: should be error, ok, warning or unknown: " + strEx::s::xtos(lua_type(L, pos))); return NSCAPI::returnUNKNOWN; }
void CheckExternalScripts::query_fallback(const Plugin::QueryRequestMessage::Request &request, Plugin::QueryResponseMessage::Response *response, const Plugin::QueryRequestMessage &) { //nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_query_request(char_command, request); commands::optional_command_object command_def = commands_.find_object(request.command()); std::list<std::string> args; for (int i=0;i<request.arguments_size();++i) { args.push_back(request.arguments(i)); } if (command_def) { handle_command(*command_def, args, response); return; } alias::optional_command_object alias_def = aliases_.find_object(request.command()); if (alias_def) { handle_alias(*alias_def, args, response); return; } NSC_LOG_ERROR_STD("No command or alias found matching: " + request.command()); nscapi::protobuf::functions::set_response_bad(*response, "No command or alias found matching: " + request.command()); }
bool CheckLogFile::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) { thread_.reset(new real_time_thread); sh::settings_registry settings(get_settings_proxy()); settings.set_alias(alias, "logfile"); thread_->filters_path_ = settings.alias().get_settings_path("real-time/checks"); settings.alias().add_path_to_settings() ("LOG FILE SECTION", "Section for log file checker") ("real-time", "CONFIGURE REALTIME CHECKING", "A set of options to configure the real time checks") ("real-time/checks", sh::fun_values_path(boost::bind(&real_time_thread::add_realtime_filter, thread_, get_settings_proxy(), _1, _2)), "REALTIME FILTERS", "A set of filters to use in real-time mode", "REALTIME FILTER DEFENTION", "For more configuration options add a dedicated section" ) ; settings.alias().add_key_to_settings("real-time") ("enabled", sh::bool_fun_key<bool>(boost::bind(&real_time_thread::set_enabled, thread_, _1), false), "REAL TIME CHECKING", "Spawns a background thread which waits for file changes.") ; settings.register_all(); settings.notify(); filters::filter_config_handler::add_samples(get_settings_proxy(), thread_->filters_path_); if (mode == NSCAPI::normalStart) { if (!thread_->start()) NSC_LOG_ERROR_STD("Failed to start collection thread"); } return true; }
int CheckMKClient::clp_handler_impl::exec(client::configuration::data_type data, const Plugin::ExecuteRequestMessage &, Plugin::ExecuteResponseMessage &response_message) { NSC_LOG_ERROR_STD("check_mk does not support submit patterns"); nscapi::protobuf::functions::set_response_good(*response_message.add_payload(), "check_mk does not support exec pattern"); return NSCAPI::isSuccess; }
check_nt::packet handler_impl::handle(check_nt::packet p) { std::wstring buffer = p.get_payload(); NSC_DEBUG_MSG_STD(_T("Data: ") + buffer); std::wstring::size_type pos = buffer.find_first_of(_T("\n\r")); if (pos != std::wstring::npos) { std::wstring::size_type pos2 = buffer.find_first_not_of(_T("\n\r"), pos); if (pos2 != std::wstring::npos) { std::wstring rest = buffer.substr(pos2); NSC_DEBUG_MSG_STD(_T("Ignoring data: ") + rest); } buffer = buffer.substr(0, pos); } strEx::token pwd = strEx::getToken(buffer, '&'); if (!isPasswordOk(pwd.first)) { NSC_LOG_ERROR_STD(_T("Invalid password (") + pwd.first + _T(").")); return check_nt::packet("ERROR: Invalid password."); } if (pwd.second.empty()) return check_nt::packet("ERROR: No command specified."); strEx::token cmd = strEx::getToken(pwd.second, '&'); if (cmd.first.empty()) return check_nt::packet("ERROR: No command specified."); int c = boost::lexical_cast<int>(cmd.first.c_str()); NSC_DEBUG_MSG_STD(_T("Data: ") + cmd.second); std::list<std::wstring> args; // prefix various commands switch (c) { case REQ_CPULOAD: cmd.first = _T("checkCPU"); split_to_list(args, cmd.second); args.push_back(_T("nsclient")); break; case REQ_UPTIME: cmd.first = _T("checkUpTime"); args.push_back(_T("nsclient")); break; case REQ_USEDDISKSPACE: cmd.first = _T("CheckDriveSize"); split_to_list(args, cmd.second); args.push_back(_T("nsclient")); break; case REQ_CLIENTVERSION: { //std::wstring v = SETTINGS_GET_STRING(nsclient::VERSION); //if (v == _T("auto")) std::wstring v = nscapi::plugin_singleton->get_core()->getApplicationName() + _T(" ") + nscapi::plugin_singleton->get_core()->getApplicationVersionString(); return strEx::wstring_to_string(v); } case REQ_SERVICESTATE: cmd.first = _T("checkServiceState"); split_to_list(args, cmd.second); args.push_back(_T("nsclient")); break; case REQ_PROCSTATE: cmd.first = _T("checkProcState"); split_to_list(args, cmd.second); args.push_back(_T("nsclient")); break; case REQ_MEMUSE: cmd.first = _T("checkMem"); args.push_back(_T("nsclient")); break; case REQ_COUNTER: cmd.first = _T("checkCounter"); args.push_back(_T("Counter=") + cmd.second); args.push_back(_T("nsclient")); break; case REQ_FILEAGE: cmd.first = _T("getFileAge"); args.push_back(_T("path=") + cmd.second); break; case REQ_INSTANCES: cmd.first = _T("listCounterInstances"); args.push_back(cmd.second); break; default: split_to_list(args, cmd.second); } std::wstring message, perf; NSCAPI::nagiosReturn ret = nscapi::core_helper::simple_query(cmd.first.c_str(), args, message, perf); if (!nscapi::plugin_helper::isNagiosReturnCode(ret)) { if (message.empty()) return check_nt::packet("ERROR: Could not complete the request check log file for more information."); return check_nt::packet("ERROR: " + strEx::wstring_to_string(message)); } switch (c) { case REQ_UPTIME: // Some check_nt commands has no return code syntax case REQ_MEMUSE: case REQ_CPULOAD: case REQ_CLIENTVERSION: case REQ_USEDDISKSPACE: case REQ_COUNTER: case REQ_FILEAGE: return check_nt::packet(message); case REQ_SERVICESTATE: // Some check_nt commands return the return code (coded as a string) case REQ_PROCSTATE: return check_nt::packet(strEx::itos(nscapi::plugin_helper::nagios2int(ret)) + _T("& ") + message); default: // "New" check_nscp also returns performance data if (perf.empty()) return check_nt::packet(nscapi::plugin_helper::translateReturn(ret) + _T("&") + message); return check_nt::packet(nscapi::plugin_helper::translateReturn(ret) + _T("&") + message + _T("&") + perf); } return check_nt::packet("FOO"); }
bool SimpleFileWriter::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) { std::string primary_key; std::string channel; try { sh::settings_registry settings(get_settings_proxy()); settings.set_alias(alias, "writers/file"); settings.alias().add_path_to_settings() ("FILE WRITER", "Section for simple file writer module (SimpleFileWriter.dll).") ; settings.alias().add_key_to_settings() ("syntax", sh::string_key(&primary_key, "${alias-or-command} ${result} ${message}"), "MESSAGE SYNTAX", "The syntax of the message to write to the line.\nCan be any arbitrary string as well as include any of the following special keywords:" "${command} = The command name, ${host} the host, ${channel} the recieving channel, ${alias} the alias for the command, ${alias-or-command} = alias if set otherweise command, ${message} = the message data (no escape), ${result} = The result status (number).") ("file", sh::path_key(&filename_, "output.txt"), "FILE TO WRITE TO", "The filename to write output to.") ("channel", sh::string_key(&channel, "FILE"), "CHANNEL", "The channel to listen to.") ; settings.register_all(); settings.notify(); nscapi::core_helper::core_proxy core(get_core(), get_id()); core.register_channel(channel); parsers::simple_expression parser; parsers::simple_expression::result_type result; if (!parser.parse(primary_key, result)) { NSC_LOG_ERROR_STD("Failed to parse primary key: " + primary_key) } BOOST_FOREACH(parsers::simple_expression::entry &e, result) { if (!e.is_variable) { index_lookup_.push_back(simple_string_functor(e.name)); } else if (e.name == "command") { index_lookup_.push_back(payload_command_functor()); } else if (e.name == "host") { index_lookup_.push_back(header_host_functor()); } else if (e.name == "channel") { index_lookup_.push_back(channel_functor()); } else if (e.name == "alias") { index_lookup_.push_back(payload_alias_functor()); } else if (e.name == "alias-or-command") { index_lookup_.push_back(payload_alias_or_command_functor()); } else if (e.name == "message") { index_lookup_.push_back(payload_message_functor()); } else if (e.name == "result") { index_lookup_.push_back(payload_result_functor()); } else { NSC_LOG_ERROR_STD("Invalid index: " + e.name); } } } catch (nscapi::nscapi_exception &e) { NSC_LOG_ERROR_EXR("Failed to register command: ", e); return false; } catch (std::exception &e) { NSC_LOG_ERROR_EXR("load", e); return false; } catch (...) { NSC_LOG_ERROR_EX("load"); return false; } return true; }