Changeset 9b9be81 in nscp
- Timestamp:
- 09/27/11 22:25:27 (20 months ago)
- Branches:
- master, 0.4.0, 0.4.1, 0.4.2
- Children:
- 234a037
- Parents:
- a629015
- Files:
-
- 41 edited
-
changelog (modified) (1 diff)
-
include/NSCAPI.h (modified) (1 diff)
-
include/client/command_line_parser.cpp (modified) (1 diff)
-
include/nsca/nsca_enrypt.hpp (modified) (8 diffs)
-
include/nsca/nsca_socket.hpp (modified) (5 diffs)
-
include/nsca/server/connection.cpp (modified) (4 diffs)
-
include/nsca/server/connection.hpp (modified) (2 diffs)
-
include/nsca/server/handler.hpp (modified) (1 diff)
-
include/nsca/server/parser.hpp (modified) (2 diffs)
-
include/nscapi/functions.hpp (modified) (5 diffs)
-
include/nscapi/nscapi_core_wrapper.cpp (modified) (2 diffs)
-
include/nscapi/nscapi_core_wrapper.hpp (modified) (2 diffs)
-
include/nscapi/nscapi_plugin_wrapper.cpp (modified) (1 diff)
-
include/nscapi/nscapi_plugin_wrapper.hpp (modified) (1 diff)
-
include/settings/Settings.h (modified) (3 diffs)
-
include/settings/client/settings_client.hpp (modified) (1 diff)
-
libs/protobuf/plugin.proto (modified) (3 diffs)
-
modules/CheckExternalScripts/CheckExternalScripts.cpp (modified) (2 diffs)
-
modules/CheckExternalScripts/CheckExternalScripts.h (modified) (1 diff)
-
modules/DistributedServer/DistributedServer.cpp (modified) (1 diff)
-
modules/NSCAClient/CMakeLists.txt (modified) (3 diffs)
-
modules/NSCAClient/NSCAClient.cpp (modified) (3 diffs)
-
modules/NSCAClient/NSCAClient.h (modified) (1 diff)
-
modules/NSCAServer/CMakeLists.txt (modified) (1 diff)
-
modules/NSCAServer/NSCAServer.cpp (modified) (2 diffs)
-
modules/NSCAServer/handler_impl.cpp (modified) (1 diff)
-
modules/NSCAServer/handler_impl.hpp (modified) (3 diffs)
-
modules/NSCPClient/NSCPClient.cpp (modified) (1 diff)
-
modules/PythonScript/PythonScript.cpp (modified) (6 diffs)
-
modules/PythonScript/script_wrapper.cpp (modified) (12 diffs)
-
modules/PythonScript/script_wrapper.hpp (modified) (3 diffs)
-
scripts/python/lib/test_helper.py (modified) (3 diffs)
-
scripts/python/test_nsca.py (modified) (5 diffs)
-
service/NSCPlugin.cpp (modified) (3 diffs)
-
service/NSCPlugin.h (modified) (1 diff)
-
service/NSClient++.cpp (modified) (4 diffs)
-
service/NSClient++.h (modified) (1 diff)
-
service/cli_parser.hpp (modified) (3 diffs)
-
service/core_api.cpp (modified) (4 diffs)
-
service/core_api.h (modified) (1 diff)
-
service/settings_client.hpp (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
-
changelog
ra629015 r9b9be81 6 6 * Fix RtlStringFromGUID problem on NT4 7 7 8 2011-09-27 MickeM 9 * Fixed many many issues all over the place as I tried to make things working for my pressention at nwc. 10 8 11 2011-09-24 MickeM 9 12 * Started on NSCA unit-tests in python -
include/NSCAPI.h
ra629015 r9b9be81 173 173 typedef NSCAPI::errorReturn (*lpNSAPIRegisterSubmissionListener)(unsigned int plugin_id, const wchar_t* channel); 174 174 typedef NSCAPI::errorReturn (*lpNSAPIRegisterRoutingListener)(unsigned int plugin_id, const wchar_t* channel); 175 typedef NSCAPI::errorReturn (*lpNSAPIReload)(const wchar_t* module); 175 176 176 177 } -
include/client/command_line_parser.cpp
ra629015 r9b9be81 250 250 modify_header(config, message.mutable_header(), config.data->recipient); 251 251 std::list<std::string> errors = config.handler->submit(config.data, message.mutable_header(), message.SerializeAsString(), response); 252 if (response.empty()) { 253 std::wstring msg; 254 BOOST_FOREACH(std::string &e, errors) { 255 msg += utf8::cvt<std::wstring>(e); 256 } 257 nscapi::functions::create_simple_submit_response(_T(""), _T(""), errors.empty()?NSCAPI::hasFailed:NSCAPI::isSuccess, msg, response); 258 } 252 259 BOOST_FOREACH(std::string &e, errors) { 253 260 //config.handler->error(e); -
include/nsca/nsca_enrypt.hpp
ra629015 r9b9be81 20 20 #include <cryptopp/osrng.h> 21 21 #endif 22 23 #include <strEx.h> 22 24 23 25 #define TRANSMITTED_IV_SIZE 128 /* size of IV to transmit - must be as big as largest IV needed for any crypto algorithm */ … … 70 72 struct helpers { 71 73 static int encryption_to_int(std::string encryption) { 74 if (encryption.size() > 0 && std::isdigit(encryption[0])) { 75 int enc = strEx::stoi(encryption); 76 if (enc == ENCRYPT_XOR 77 #ifdef HAVE_LIBCRYPTOPP 78 || enc == ENCRYPT_DES || enc == ENCRYPT_3DES || enc == ENCRYPT_CAST128 || enc == ENCRYPT_XTEA || enc == ENCRYPT_3WAY || enc == ENCRYPT_BLOWFISH || enc == ENCRYPT_TWOFISH || enc == ENCRYPT_RC2 || enc == ENCRYPT_RIJNDAEL128 || enc == ENCRYPT_SERPENT || enc == ENCRYPT_GOST 79 #endif 80 ) 81 return enc; 82 return ENCRYPT_NONE; 83 } 72 84 if (encryption == "xor") 73 85 return ENCRYPT_XOR; … … 98 110 return ENCRYPT_NONE; 99 111 } 112 static std::string encryption_to_string(int encryption) { 113 if (encryption == ENCRYPT_XOR) 114 return "xor"; 115 #ifdef HAVE_LIBCRYPTOPP 116 if (encryption == ENCRYPT_DES) 117 return "des"; 118 if (encryption == ENCRYPT_3DES) 119 return "3des"; 120 if (encryption == ENCRYPT_CAST128) 121 return "cast128"; 122 if (encryption == ENCRYPT_XTEA) 123 return "xtea"; 124 if (encryption == ENCRYPT_3WAY) 125 return "3way"; 126 if (encryption == ENCRYPT_BLOWFISH) 127 return "blowfish"; 128 if (encryption == ENCRYPT_TWOFISH) 129 return "twofish"; 130 if (encryption == ENCRYPT_RC2) 131 return "rc2"; 132 if (encryption == ENCRYPT_RIJNDAEL128) 133 return "aes"; 134 if (encryption == ENCRYPT_SERPENT) 135 return "serpent"; 136 if (encryption == ENCRYPT_GOST) 137 return "gost"; 138 #endif 139 if (encryption == ENCRYPT_NONE) 140 return "none"; 141 return "unknown"; 142 } 143 100 144 101 145 }; … … 112 156 private: 113 157 typedef CryptoPP::CFB_Mode_ExternalCipher::Encryption TEncryption; 158 typedef CryptoPP::CFB_Mode_ExternalCipher::Decryption TDecryption; 114 159 typedef typename TMethod::Encryption TCipher; 115 160 TEncryption crypto_; 161 TDecryption decrypto_; 116 162 TCipher cipher_; 117 163 int keysize_; … … 161 207 cipher_.SetKey(key, keysize); 162 208 crypto_.SetCipherWithIV(cipher_, iv, 1); 209 decrypto_.SetCipherWithIV(cipher_, iv, 1); 163 210 } catch (...) { 164 211 throw encryption_exception("Unknown exception when trying to setup crypto"); … … 183 230 } 184 231 void decrypt(unsigned char *buffer, int buffer_size) { 185 throw encryption_exception("Decryption not supported"); 232 try { 233 for(int x=0;x<buffer_size;x++) 234 decrypto_.ProcessData(&buffer[x], &buffer[x], 1); 235 } catch (...) { 236 throw encryption_exception("Unknown exception when trying to setup crypto"); 237 } 186 238 } 187 239 std::string getName() { … … 240 292 } 241 293 void decrypt(std::string &buffer) { 242 throw encryption_exception("Decryption not supported"); 294 /* rotate over IV we received from the server... */ 295 unsigned int buf_len = buffer.size(); 296 unsigned int iv_len = iv_.size(); 297 unsigned int pwd_len = password_.size(); 298 for (int y=0,x=0,z=0;y<buf_len;y++,x++,z++) { 299 /* keep rotating over Password */ 300 if (z >= pwd_len) 301 z = 0; 302 buffer[y] ^= password_[z]; 303 /* keep rotating over IV */ 304 if (x >= iv_len) 305 x = 0; 306 buffer[y] ^= iv_[x]; 307 } 243 308 } 244 309 std::string getName() { 245 return "XOR (not safe)";310 return "XOR"; 246 311 } 247 312 }; … … 368 433 core_->encrypt(buffer); 369 434 } 435 /* encrypt a buffer */ 436 void decrypt_buffer(std::string &buffer) { 437 if (core_ == NULL) 438 throw encryption_exception("No encryption core!"); 439 core_->decrypt(buffer); 440 } 370 441 std::string get_rand_buffer(int length) { 371 442 std::string buffer; buffer.resize(length); -
include/nsca/nsca_socket.hpp
ra629015 r9b9be81 57 57 58 58 virtual void send_nsca(const nsca::packet &packet, const boost::posix_time::seconds timeout) { 59 NSC_DEBUG_MSG(_T("About to send: ") + utf8::cvt<std::wstring>(packet.to_string()));60 59 if (!get_socket().is_open()) { 61 60 NSC_DEBUG_MSG(_T("is closed...")); … … 65 64 packet.get_buffer(buffer); 66 65 crypt_inst.encrypt_buffer(buffer); 67 NSC_LOG_ERROR_STD(_T("About to write: ") + strEx::itos(buffer.size()));68 66 write_with_timeout(buffer, timeout); 69 67 } 70 68 virtual bool recv_iv(std::string password, int encryption_method, boost::posix_time::seconds timeout) { 71 NSC_DEBUG_MSG(_T("Socket..."));72 69 if (!get_socket().is_open()) { 73 70 NSC_DEBUG_MSG(_T("is closed...")); … … 76 73 unsigned int len = nsca::length::iv::get_packet_length(); 77 74 std::vector<char> buf(len); 78 NSC_DEBUG_MSG(_T("About t read IV: ") + strEx::itos(len));79 75 if (!read_with_timeout(buf, timeout)) { 80 76 NSC_LOG_ERROR_STD(_T("Failed to read IV from server.")); … … 82 78 } 83 79 std::string str_buf(buf.begin(), buf.end()); 84 NSC_DEBUG_MSG(_T("Encrypting using : ") + strEx::itos(encryption_method));80 NSC_DEBUG_MSG(_T("Encrypting using when sending: ") + utf8::cvt<std::wstring>(nsca::nsca_encrypt::helpers::encryption_to_string(encryption_method)) + _T(" and ") + utf8::cvt<std::wstring>(password)); 85 81 crypt_inst.encrypt_init(password, encryption_method, str_buf); 86 82 return true; … … 92 88 socket_helpers::io::write_with_timeout(*socket_, get_socket(), boost::asio::buffer(buf), timeout); 93 89 } 94 /*95 virtual void read_with_timeout(std::string &buf, boost::posix_time::seconds timeout) {96 socketHelpers::io::read_with_timeout(*socket_, get_socket(), boost::asio::mutable_buffer(buf), timeout);97 }98 virtual void write_with_timeout(std::string &buf, boost::posix_time::seconds timeout) {99 socketHelpers::io::write_with_timeout(*socket_, get_socket(), boost::asio::buffer(buf), timeout);100 }101 */102 90 }; 103 91 } -
include/nsca/server/connection.cpp
ra629015 r9b9be81 30 30 handler_->log_debug(__FILE__, __LINE__, _T("starting data connection...")); 31 31 std::vector<boost::asio::const_buffer> buffers; 32 nsca::iv_packet packet(nsca_encrypt::generate_transmitted_iv()); 32 33 std::string iv = nsca::nsca_encrypt::generate_transmitted_iv(); 34 handler_->log_debug(__FILE__, __LINE__, _T("Encrypting using when receieving: ") + utf8::cvt<std::wstring>(nsca::nsca_encrypt::helpers::encryption_to_string(handler_->get_encryption())) + _T(" and ") + utf8::cvt<std::wstring>(handler_->get_password())); 35 encryption_instance_.encrypt_init(handler_->get_password(), handler_->get_encryption(), iv); 36 37 nsca::iv_packet packet(iv); 33 38 buffers.push_back(buf(packet.get_buffer())); 34 handler_->log_debug(__FILE__, __LINE__, _T("About to write: ") + strEx::itos(packet.get_buffer().size()));35 39 start_write_request(buffers, 30); 36 40 } … … 68 72 void connection::handle_read_request(const boost::system::error_code& e, std::size_t bytes_transferred) { 69 73 if (!e) { 70 handler_->log_error(__FILE__, __LINE__, _T("Got data (server): ") + strEx::itos(bytes_transferred));71 74 bool result; 72 75 buffer_type::iterator begin = buffer_.begin(); … … 82 85 nsca::packet response; 83 86 try { 84 // TODO decrypt data here... 85 //NSC_DEBUG_MSG(_T("Encrypting using: ") + strEx::itos(encryption_method)); 86 nsca::packet request = parser_.parse(); 87 nsca::packet request = parser_.parse(encryption_instance_); 87 88 handler_->handle(request); 88 89 } catch (nsca::nsca_exception &e) { 90 handler_->log_error(__FILE__, __LINE__, str::to_wstring(e.what())); 91 } catch (const std::exception &e) { 89 92 handler_->log_error(__FILE__, __LINE__, str::to_wstring(e.what())); 90 93 } catch (...) { … … 92 95 } 93 96 cancel_timer(); 94 handler_->log_error(__FILE__, __LINE__, _T("Done reading packet (server), shutting down..."));95 97 // Initiate graceful connection closure. 96 98 boost::system::error_code ignored_ec; -
include/nsca/server/connection.hpp
ra629015 r9b9be81 6 6 #include <boost/shared_ptr.hpp> 7 7 #include <boost/enable_shared_from_this.hpp> 8 9 #include <nsca/nsca_enrypt.hpp> 8 10 9 11 #include "handler.hpp" … … 72 74 boost::asio::ip::tcp::socket socket_; 73 75 76 nsca::nsca_encrypt encryption_instance_; 77 74 78 }; 75 79 -
include/nsca/server/handler.hpp
ra629015 r9b9be81 20 20 virtual void set_channel(std::wstring channel) = 0; 21 21 virtual std::wstring get_channel() = 0; 22 22 virtual void set_encryption(std::string encryption) = 0; 23 virtual int get_encryption() = 0; 24 virtual std::string get_password() = 0; 25 virtual void set_password(std::string pwd) = 0; 23 26 }; 24 27 }// namespace server -
include/nsca/server/parser.hpp
ra629015 r9b9be81 5 5 6 6 #include <nsca/nsca_packet.hpp> 7 #include <nsca/nsca_enrypt.hpp> 7 8 8 9 #include "handler.hpp" … … 28 29 } 29 30 30 nsca::packet parse( ) {31 nsca::packet parse(nsca::nsca_encrypt &encryption) { 31 32 nsca::packet packet(payload_length_); 33 //std::string buffer = encryption.get_rand_buffer(packet.get_packet_length()); 34 //packet.get_buffer(buffer); 35 encryption.decrypt_buffer(buffer_); 32 36 packet.parse_data(buffer_.c_str(), buffer_.size()); 33 37 buffer_.clear(); -
include/nscapi/functions.hpp
ra629015 r9b9be81 61 61 return NSCAPI::returnUNKNOWN; 62 62 } 63 static Plugin::Common::Status::StatusType status_to_gpb(int ret) { 64 if (ret == NSCAPI::isSuccess) 65 return Plugin::Common_Status_StatusType_OK; 66 return Plugin::Common_Status_StatusType_PROBLEM; 67 } 68 static int gbp_to_status(Plugin::Common::Status::StatusType ret) { 69 if (ret == Plugin::Common_Status_StatusType_OK) 70 return NSCAPI::isSuccess; 71 return NSCAPI::hasFailed; 72 } 63 73 static Plugin::LogEntry::Entry::Level log_to_gpb(NSCAPI::messageTypes ret) { 64 74 if (ret == NSCAPI::critical) … … 236 246 message.SerializeToString(&buffer); 237 247 } 238 static void create_simple_submit_response(std::wstring channel, NSCAPI::nagiosReturn ret, std::wstring msg, std::string &buffer) {248 static void create_simple_submit_response(std::wstring channel, std::wstring command, NSCAPI::nagiosReturn ret, std::wstring msg, std::string &buffer) { 239 249 Plugin::SubmitResponseMessage message; 240 250 create_simple_header(message.mutable_header()); … … 242 252 243 253 Plugin::SubmitResponseMessage::Response *payload = message.add_payload(); 244 payload->set_message(to_string(msg)); 245 //payload->set_result(nagios_status_to_gpb(ret)); 254 payload->set_command(utf8::cvt<std::string>(command)); 255 payload->mutable_status()->set_message(to_string(msg)); 256 payload->mutable_status()->set_status(status_to_gpb(ret)); 246 257 message.SerializeToString(&buffer); 247 258 } 248 static NSCAPI::errorReturn parse_simple_submit_request(const std::string &request, std::wstring & command, std::wstring &msg, std::wstring &perf) {259 static NSCAPI::errorReturn parse_simple_submit_request(const std::string &request, std::wstring &source, std::wstring &command, std::wstring &msg, std::wstring &perf) { 249 260 Plugin::SubmitRequestMessage message; 250 261 message.ParseFromString(request); … … 254 265 } 255 266 Plugin::QueryResponseMessage::Response payload = message.payload().Get(0); 267 source = utf8::cvt<std::wstring>(payload.source()); 256 268 command = utf8::cvt<std::wstring>(payload.command()); 257 269 msg = utf8::cvt<std::wstring>(payload.message()); 258 270 perf = utf8::cvt<std::wstring>(build_performance_data(payload)); 259 return -1;271 return gbp_to_nagios_status(payload.result()); 260 272 } 261 273 static NSCAPI::errorReturn parse_simple_submit_request_payload(const Plugin::QueryResponseMessage::Response &payload, std::wstring &command, std::wstring &msg, std::wstring &perf) { … … 273 285 } 274 286 ::Plugin::SubmitResponseMessage::Response payload = message.payload().Get(0); 275 response = to_wstring(payload.message()); 276 return -1; 277 } 287 response = to_wstring(payload.mutable_status()->message()); 288 return gbp_to_status(payload.mutable_status()->status()); 289 } 290 /* 291 static void create_simple_submit_response(std::wstring msg, int status, std::string &buffer) { 292 Plugin::SubmitResponseMessage message; 293 create_simple_header(message.mutable_header()); 294 295 Plugin::SubmitResponseMessage::Response *payload = message.add_payload(); 296 payload->mutable_status()->set_message(to_string(msg)); 297 payload->mutable_status()->set_status(status_to_gpb(status)); 298 299 message.SerializeToString(&buffer); 300 }*/ 278 301 279 302 static void create_simple_query_request(std::wstring command, std::list<std::wstring> arguments, std::string &buffer) { -
include/nscapi/nscapi_core_wrapper.cpp
ra629015 r9b9be81 140 140 DestroyBuffer(&buffer); 141 141 return ret; 142 } 143 144 NSCAPI::errorReturn nscapi::core_wrapper::reload(std::wstring module) { 145 146 if (!fNSAPIReload) 147 throw nscapi::nscapi_exception(_T("NSCore has not been initiated...")); 148 return fNSAPIReload(module.c_str()); 142 149 } 143 150 … … 640 647 fNSAPIReadSettings = (nscapi::core_api::lpNSAPIReadSettings)f(_T("NSAPIReadSettings")); 641 648 fNSAPIRehash = (nscapi::core_api::lpNSAPIRehash)f(_T("NSAPIRehash")); 649 fNSAPIReload = (nscapi::core_api::lpNSAPIReload)f(_T("NSAPIReload")); 642 650 643 651 fNSAPIDescribeCommand = (nscapi::core_api::lpNSAPIDescribeCommand)f(_T("NSAPIDescribeCommand")); -
include/nscapi/nscapi_core_wrapper.hpp
ra629015 r9b9be81 52 52 nscapi::core_api::lpNSAPIDestroyBuffer fNSAPIDestroyBuffer; 53 53 nscapi::core_api::lpNSAPINotify fNSAPINotify; 54 nscapi::core_api::lpNSAPIReload fNSAPIReload; 54 55 nscapi::core_api::lpNSAPICheckLogMessages fNSAPICheckLogMessages; 55 56 nscapi::core_api::lpNSAPIEncrypt fNSAPIEncrypt; … … 144 145 NSCAPI::errorReturn submit_message(const wchar_t* channel, const char *request, const unsigned int request_len, char **response, unsigned int *response_len); 145 146 NSCAPI::errorReturn submit_message(std::wstring channel, std::string request, std::string &response); 147 NSCAPI::errorReturn reload(std::wstring module); 146 148 void StopService(void); 147 149 void Exit(void); -
include/nscapi/nscapi_plugin_wrapper.cpp
ra629015 r9b9be81 110 110 NSCAPI::nagiosReturn nscapi::impl::simple_submission_handler::handleRAWNotification(const wchar_t* channel, std::string request, std::string &response) { 111 111 try { 112 std::wstring command, msg, perf;113 int code = nscapi::functions::parse_simple_submit_request(request, command, msg, perf);114 NSCAPI::nagiosReturn ret = handleSimpleNotification(channel, command, code, msg, perf);112 std::wstring source, command, msg, perf; 113 int code = nscapi::functions::parse_simple_submit_request(request, source, command, msg, perf); 114 NSCAPI::nagiosReturn ret = handleSimpleNotification(channel, source, command, code, msg, perf); 115 115 if (ret == NSCAPI::returnIgnored) 116 116 return NSCAPI::returnIgnored; 117 nscapi::functions::create_simple_submit_response(channel, ret, _T(""), response);117 nscapi::functions::create_simple_submit_response(channel, command, ret, _T(""), response); 118 118 } catch (std::exception &e) { 119 119 nscapi::plugin_singleton->get_core()->Message(NSCAPI::error, __FILE__, __LINE__, utf8::cvt<std::wstring>("Failed to parse data from: " + strEx::strip_hex(request) + ": " + e.what())); -
include/nscapi/nscapi_plugin_wrapper.hpp
ra629015 r9b9be81 123 123 public: 124 124 NSCAPI::nagiosReturn handleRAWNotification(const wchar_t* channel, std::string request, std::string &response); 125 virtual NSCAPI::nagiosReturn handleSimpleNotification(const std::wstring channel, const std::wstring command, NSCAPI::nagiosReturn code, std::wstring msg, std::wstring perf) = 0;125 virtual NSCAPI::nagiosReturn handleSimpleNotification(const std::wstring channel, const std::wstring source, const std::wstring command, NSCAPI::nagiosReturn code, std::wstring msg, std::wstring perf) = 0; 126 126 127 127 }; -
include/settings/Settings.h
r7515d00 r9b9be81 35 35 36 36 namespace Settings { 37 class SettingsException {37 class SettingsException : public std::exception { 38 38 std::wstring error_; 39 39 public: … … 43 43 /// 44 44 /// @author mickem 45 SettingsException(std::wstring error) : error_(error) {} 45 SettingsException(std::wstring error) : error_(utf8::cvt<std::wstring>(error)) {} 46 SettingsException(std::string error) : error_(error) {} 47 48 ~SettingsException() throw() {} 46 49 47 50 ////////////////////////////////////////////////////////////////////////// … … 50 53 /// 51 54 /// @author mickem 52 std::wstring getError() const { return error_; } 53 std::wstring getMessage() const { return error_; } 55 const char* what() const throw() { return error_.c_str(); } 54 56 }; 55 57 class KeyNotFoundException : public SettingsException { -
include/settings/client/settings_client.hpp
r7515d00 r9b9be81 582 582 core_->register_path(v->path_name, v->description.title, v->description.description, v->description.advanced); 583 583 } 584 } 585 void clear() { 586 keys_.clear(); 587 paths_.clear(); 584 588 } 585 589 -
libs/protobuf/plugin.proto
ra629015 r9b9be81 137 137 message Request { 138 138 optional int32 id = 1; 139 optional string target = 7; 139 140 required string command = 2; 140 141 optional string alias = 3; … … 152 153 153 154 optional int32 id = 1; 155 optional string source = 7; 154 156 required string command = 2; 155 157 optional string alias = 3; … … 239 241 required string command = 2; 240 242 required Common.Status status = 3; 241 optional string message = 4;242 243 repeated Common.Attachment attachments = 17; 243 244 }; -
modules/CheckExternalScripts/CheckExternalScripts.cpp
ra78a985 r9b9be81 83 83 _T("EXTERNAL SCRIPT SCRIPT SECTION"), _T("A list of scripts available to run from the CheckExternalScripts module. Syntax is: <command>=<script> <arguments>")) 84 84 85 (_T("wrappings"), sh::wstring_map_path(&wrappings_) 86 , _T("EXTERNAL SCRIPT WRAPPINGS SECTION"), _T("A list of templates for wrapped scripts")) 87 85 88 (_T("alias"), sh::fun_values_path(boost::bind(&CheckExternalScripts::add_alias, this, _1, _2)), 86 89 _T("EXTERNAL SCRIPT ALIAS SECTION"), _T("A list of aliases available. An alias is an internal command that has been \"wrapped\" (to add arguments). Be careful so you don't create loops (ie check_loop=check_a, check_a=check_loop)")) 87 90 88 (_T("wrappings"), sh::wstring_map_path(&wrappings_)89 , _T("EXTERNAL SCRIPT WRAPPINGS SECTION"), _T(""))90 91 (_T("wrapped scripts"), sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)),92 _T("EXTERNAL SCRIPT WRAPPED SCRIPTS SECTION"), _T(""))93 91 ; 94 92 … … 107 105 ; 108 106 107 settings.register_all(); 108 settings.notify(); 109 settings.clear(); 110 111 settings.alias().add_path_to_settings() 112 113 (_T("wrapped scripts"), sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)), 114 _T("EXTERNAL SCRIPT WRAPPED SCRIPTS SECTION"), _T("A list of wrappped scripts (ie. using the template mechanism)")) 115 116 ; 109 117 settings.register_all(); 110 118 settings.notify(); -
modules/CheckExternalScripts/CheckExternalScripts.h
ra44cb15 r9b9be81 138 138 strEx::replace(tpl, _T("%ARGS%"), tok.second); 139 139 140 NSC_DEBUG_MSG(_T("Adding wrapped script: ") + key); 141 NSC_DEBUG_MSG(_T("Adding wrapped script: ") + tpl); 140 142 add_command(key,tpl); 141 143 } -
modules/DistributedServer/DistributedServer.cpp
r2b2e9b8 r9b9be81 71 71 settings.notify(); 72 72 73 context = new zmq::context_t(2); 73 if (mode == NSCAPI::normalStart) { 74 context = new zmq::context_t(2); 74 75 75 zeromq_queue::connection_info queue_info(to_string(host), to_string(suffix));76 zeromq_queue::queue_manager queue;77 queue.start(context, threads, queue_info);76 zeromq_queue::connection_info queue_info(to_string(host), to_string(suffix)); 77 zeromq_queue::queue_manager queue; 78 queue.start(context, threads, queue_info); 78 79 79 zeromq_worker::connection_info worker_info(queue_info.get_backend(), to_string(suffix), thread_count); 80 zeromq_worker::worker_manager workers; 81 workers.start(context, threads, worker_info); 80 zeromq_worker::connection_info worker_info(queue_info.get_backend(), to_string(suffix), thread_count); 81 zeromq_worker::worker_manager workers; 82 workers.start(context, threads, worker_info); 83 } 82 84 83 85 } catch (std::exception &e) { -
modules/NSCAClient/CMakeLists.txt
ra629015 r9b9be81 16 16 17 17 IF(HAVE_CRYPTOPP) 18 SET(EXTRA_LIBS ${EXTRA_LIBS} cryptopp_static) 19 SET(EXTRA_DEFINES ${EXTRA_DEFINES} -DHAVE_LIBCRYPTOPP) 18 SET(CRYPTOPP_LIB cryptopp_static) 19 ADD_DEFINITIONS(-DHAVE_LIBCRYPTOPP) 20 INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR}) 20 21 ELSE(HAVE_CRYPTOPP) 21 22 message(STATUS "WARNING: No libCrypto++ in NSCA Module") … … 23 24 24 25 ADD_DEFINITIONS(${NSCP_GLOBAL_DEFINES}) 25 ADD_DEFINITIONS(${EXTRA_DEFINES})26 26 27 27 IF(WIN32) … … 43 43 44 44 add_library(${TARGET} MODULE ${SRCS}) 45 INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})46 45 47 46 target_link_libraries(${TARGET} 48 47 ${Boost_FILESYSTEM_LIBRARY} 49 48 ${NSCP_DEF_PLUGIN_LIB} 50 ${OPENSSL_LIBRARIES} 51 ${EXTRA_LIBS} 49 ${CRYPTOPP_LIB} 52 50 ) 53 51 INCLUDE(${BUILD_CMAKE_FOLDER}/module.cmake) 52 SOURCE_GROUP("Server" REGULAR_EXPRESSION .*include/nsca/.*) -
modules/NSCAClient/NSCAClient.cpp
ra629015 r9b9be81 114 114 settings.notify(); 115 115 116 NSC_DEBUG_MSG(_T("==> Registring listsner for: ") + channel_ + _T(" for ") + to_wstring(get_id()));117 116 get_core()->registerSubmissionListener(get_id(), channel_); 118 117 … … 211 210 } 212 211 return NSCAPI::isSuccess; 213 /*214 boost::asio::io_service io_service;215 nsca::socket socket(io_service);216 socket.connect(nscahost_, nscaport_);217 nsca::packet packet(hostname_, payload_length_, time_delta_);218 packet.code = code;219 packet.service = utf8::cvt<std::string>(command);220 packet.result = utf8::cvt<std::string>(msg) + "|" + utf8::cvt<std::string>(perf);221 socket.recv_iv(password_, encryption_method_, boost::posix_time::seconds(timeout_));222 socket.send_nsca(packet, boost::posix_time::seconds(timeout_));223 return NSCAPI::isSuccess;224 */225 212 } catch (nsca::nsca_encrypt::encryption_exception &e) { 226 213 NSC_LOG_ERROR_STD(_T("Failed to encrypt data: ") + str::to_wstring(e.what())); … … 270 257 std::list<std::string> result; 271 258 try { 272 NSC_DEBUG_MSG(_T(">>>") + str::to_wstring(strEx::format_buffer(request)));273 259 Plugin::SubmitRequestMessage message; 274 260 message.ParseFromString(request); 275 NSC_DEBUG_MSG(_T("<<<") + str::to_wstring(strEx::format_buffer(message.SerializeAsString())));276 261 std::list<nsca::packet> list; 277 262 278 263 std::wstring command, msg, perf; 279 264 nscapi::functions::destination_container recipient; // = data->host_default_recipient; 280 //recipient.address = data->host; // "default host"281 // this should be set before calling...282 /*283 if (recipient.data.find("password") == recipient.data.end())284 recipient.data["password"] = "default password";285 if (recipient.data.find("encryption") == recipient.data.end())286 recipient.data["encryption"] = "default encryption";287 if (recipient.data.find("payload length") != recipient.data.end())288 local_data.payload_length = strEx::stoi(recipient.data["payload length"]);289 if (recipient.data.find("time offset") != recipient.data.end())290 local_data.time_delta = strEx::stol_as_time_sec(to_wstring(recipient.data["time offset"]), 1);291 */292 265 nscapi::functions::parse_destination(*header, header->recipient_id(), recipient, true); 293 266 nscapi::functions::destination_container source; 294 //source.host = hostname_;295 267 nscapi::functions::parse_destination(*header, header->source_id(), source); 296 268 -
modules/NSCAClient/NSCAClient.h
ra629015 r9b9be81 59 59 int port; 60 60 unsigned int get_encryption() { 61 if (encryption.size() > 1 && std::isalnum(encryption[0]))62 return strEx::stoi(encryption);63 61 return nsca::nsca_encrypt::helpers::encryption_to_int(encryption); 64 65 62 } 66 63 }; -
modules/NSCAServer/CMakeLists.txt
ra629015 r9b9be81 46 46 ENDIF(WIN32) 47 47 48 48 49 add_library(${TARGET} MODULE ${SRCS}) 49 50 -
modules/NSCAServer/NSCAServer.cpp
ra629015 r9b9be81 56 56 _T("PERFORMANCE DATA"), _T("Send performance data back to nagios (set this to 0 to remove all performance data).")) 57 57 58 (_T("encryption"), sh::string_fun_key<std::string>(boost::bind(&nsca::server::handler::set_encryption, info_.request_handler, _1), "aes"), 59 _T("ENCRYPTION"), _T("Encryption to use")) 60 61 (_T("password"), sh::string_fun_key<std::string>(boost::bind(&nsca::server::handler::set_password, info_.request_handler, _1), ""), 62 _T("PASSWORD"), _T("Password to use")) 63 64 58 65 ; 59 66 … … 85 92 settings.register_all(); 86 93 settings.notify(); 87 88 94 89 95 if (info_.request_handler->get_payload_length() != 512) -
modules/NSCAServer/handler_impl.cpp
ra629015 r9b9be81 7 7 void handler_impl::handle(nsca::packet p) { 8 8 std::wstring response; 9 std::wstring msg = utf8::cvt<std::wstring>(p.result); 9 std::string::size_type pos = p.result.find('|'); 10 if (pos != std::string::npos) { 11 std::wstring msg = utf8::cvt<std::wstring>(p.result.substr(0, pos)); 12 std::wstring perf = utf8::cvt<std::wstring>(p.result.substr(++pos)); 13 GET_CORE()->submit_simple_message(channel_, utf8::cvt<std::wstring>(p.service), p.code, msg, perf, response); 14 } else { 15 std::wstring empty; 16 GET_CORE()->submit_simple_message(channel_, utf8::cvt<std::wstring>(p.service), p.code, utf8::cvt<std::wstring>(p.result), empty, response); 17 18 } 10 19 std::wstring perf = _T(""); // @todo fix this! 11 20 12 GET_CORE()->submit_simple_message(channel_, utf8::cvt<std::wstring>(p.service), p.code, msg, perf, response);13 21 NSC_DEBUG_MSG(_T("Got response: ") + response); 14 22 } -
modules/NSCAServer/handler_impl.hpp
ra629015 r9b9be81 4 4 5 5 #include <nsca/nsca_packet.hpp> 6 #include <nsca/nsca_enrypt.hpp> 6 7 #include <nsca/server/handler.hpp> 7 8 … … 14 15 bool noPerfData_; 15 16 std::wstring channel_; 17 int encryption_; 18 std::string password_; 16 19 public: 17 20 handler_impl(unsigned int payload_length) : payload_length_(payload_length), noPerfData_(false), allowNasty_(false), allowArgs_(false) {} … … 28 31 std::wstring get_channel() { 29 32 return channel_; 33 } 34 void set_encryption(std::string enc) { 35 encryption_ = nsca::nsca_encrypt::helpers::encryption_to_int(enc); 36 } 37 int get_encryption() { 38 return encryption_; 39 } 40 std::string get_password() { 41 return password_; 42 } 43 void set_password(std::string pwd) { 44 password_ = pwd; 30 45 } 31 46 -
modules/NSCPClient/NSCPClient.cpp
ra629015 r9b9be81 81 81 settings.notify(); 82 82 83 NSC_LOG_ERROR_STD(_T("Targets: ") + targets.to_wstring());84 85 83 } catch (...) { 86 84 NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>")); -
modules/PythonScript/PythonScript.cpp
ra629015 r9b9be81 47 47 using namespace boost::python; 48 48 49 template<class T> 50 void caller(auto_ptr<T> obj) 51 { 52 new_owner_function(obj.get()); 53 obj.release(); 54 } 49 55 50 56 51 57 BOOST_PYTHON_MODULE(NSCP) 52 58 { 59 PyEval_InitThreads(); 53 60 class_<script_wrapper::settings_wrapper, boost::shared_ptr<script_wrapper::settings_wrapper> >("Settings", no_init) 54 61 .def("get",&script_wrapper::settings_wrapper::create) … … 90 97 .def("simple_submit", &script_wrapper::command_wrapper::simple_submit) 91 98 .def("submit", &script_wrapper::command_wrapper::submit) 99 .def("reload", &script_wrapper::command_wrapper::reload) 92 100 ; 93 101 … … 99 107 ; 100 108 def("log", script_wrapper::log_msg); 109 def("log_err", script_wrapper::log_error); 110 def("log_deb", script_wrapper::log_debug); 111 def("log_error", script_wrapper::log_error); 112 def("log_debug", script_wrapper::log_debug); 101 113 // def("get_module_alias", script_wrapper::get_module_alias); 102 114 // def("get_script_alias", script_wrapper::get_script_alias); … … 206 218 std::list<boost::filesystem::wpath> checks; 207 219 checks.push_back(file); 220 checks.push_back((file + _T(".py"))); 208 221 checks.push_back(root_ / _T("scripts") / _T("python") / file); 222 checks.push_back(root_ / _T("scripts") / _T("python") / (file + _T(".py"))); 209 223 checks.push_back(root_ / _T("scripts") / file); 210 checks.push_back(root_ / _T(" python") / file);224 checks.push_back(root_ / _T("scripts") / (file + _T(".py"))); 211 225 checks.push_back(root_ / file); 212 226 BOOST_FOREACH(boost::filesystem::wpath c, checks) { … … 308 322 NSCAPI::nagiosReturn PythonScript::commandRAWLineExec(const wchar_t* char_command, const std::string &request, std::string &response) { 309 323 std::wstring command = char_command; 310 if (command == _T("execute-and-load-python") ) {324 if (command == _T("execute-and-load-python") || command == _T("execute-python") || command == _T("run")) { 311 325 nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_exec_request(char_command, request); 312 326 return execute_and_load_python(data.args); … … 355 369 std::string chnl = utf8::cvt<std::string>(channel); 356 370 if (inst->has_message_handler(chnl)) { 357 return inst->handle_message(chnl, request, response); 371 NSCAPI::nagiosReturn ret = inst->handle_message(chnl, request, response); 372 if (ret != NSCAPI::returnIgnored) 373 return ret; 358 374 } 359 375 if (inst->has_simple_message_handler(chnl)) { 360 std::wstring cmd, msg, perf;361 int code = nscapi::functions::parse_simple_submit_request(request, cmd, msg, perf);362 int ret = inst->handle_simple_message(chnl, to_string( cmd), code, msg, perf);363 nscapi::functions:: parse_simple_submit_response(response, _T(""));376 std::wstring src, cmd, msg, perf; 377 int code = nscapi::functions::parse_simple_submit_request(request, src, cmd, msg, perf); 378 int ret = inst->handle_simple_message(chnl, to_string(src), to_string(cmd), code, msg, perf); 379 nscapi::functions::create_simple_submit_response(channel, cmd, ret, _T(""), response); 364 380 return ret; 365 381 } -
modules/PythonScript/script_wrapper.cpp
ra629015 r9b9be81 4 4 #include "script_wrapper.hpp" 5 5 #include "PythonScript.h" 6 #include <nscapi/functions.hpp> 6 7 7 8 using namespace boost::python; 9 namespace py = boost::python; 8 10 9 11 boost::shared_ptr<script_wrapper::functions> script_wrapper::functions::instance; … … 13 15 14 16 void script_wrapper::log_msg(std::wstring x) { 17 NSC_LOG_MESSAGE(utf8::cvt<std::wstring>(x)); 18 } 19 void script_wrapper::log_error(std::wstring x) { 15 20 NSC_LOG_ERROR_STD(utf8::cvt<std::wstring>(x)); 21 } 22 void script_wrapper::log_debug(std::wstring x) { 23 NSC_DEBUG_MSG(utf8::cvt<std::wstring>(x)); 16 24 } 17 25 /* … … 32 40 NSC_LOG_ERROR_STD(_T("Failed to parse error: ") + utf8::cvt<std::wstring>(e.what())); 33 41 PyErr_Clear(); 42 } catch (...) { 43 NSC_LOG_ERROR_STD(_T("Failed to parse python error")); 44 PyErr_Clear(); 34 45 } 35 46 } … … 125 136 } 126 137 127 boost::python::list l;138 py::list l; 128 139 BOOST_FOREACH(std::wstring a, arguments) { 129 140 l.append(utf8::cvt<std::string>(a)); … … 239 250 } 240 251 241 int script_wrapper::function_wrapper::handle_message(const std::string channel, const std::string command, std::string &message) const {252 int script_wrapper::function_wrapper::handle_message(const std::string channel, const std::string &request, std::string &response) const { 242 253 try { 243 254 functions::function_map_type::iterator it = functions::get()->normal_handler.find(channel); … … 246 257 return NSCAPI::returnIgnored; 247 258 } 248 object ret = boost::python::call<object>(boost::python::object(it->second).ptr(), channel, command, message); 249 if (ret.ptr() == Py_None) { 250 return NSCAPI::returnUNKNOWN; 251 } 252 return extract<int>(ret); 259 PyGILState_STATE gstate = PyGILState_Ensure(); 260 tuple ret = boost::python::call<tuple>(boost::python::object(it->second).ptr(), channel, request); 261 if (ret.ptr() == Py_None) { 262 return NSCAPI::returnIgnored; 263 } 264 int ret_code = NSCAPI::returnIgnored; 265 if (len(ret) > 0) 266 ret_code = extract<bool>(ret[0])?NSCAPI::isSuccess:NSCAPI::returnIgnored; 267 if (len(ret) > 1) 268 response = extract<std::string>(ret[1]); 269 PyGILState_Release( gstate ); 270 return ret_code; 253 271 } catch( error_already_set e) { 254 272 log_exception(); … … 282 300 } 283 301 284 int script_wrapper::function_wrapper::handle_simple_message(const std::string channel, const std::string command, int code, std::wstring &msg, std::wstring &perf) const {302 int script_wrapper::function_wrapper::handle_simple_message(const std::string channel, const std::string source, const std::string command, int code, std::wstring &msg, std::wstring &perf) const { 285 303 try { 286 304 functions::function_map_type::iterator it = functions::get()->simple_handler.find(channel); … … 289 307 return NSCAPI::returnIgnored; 290 308 } 291 object ret = boost::python::call<object>(boost::python::object(it->second).ptr(), channel, command, nagios_return_to_py(code), utf8::cvt<std::string>(msg), utf8::cvt<std::string>(perf)); 292 if (ret.ptr() == Py_None) { 293 return NSCAPI::returnUNKNOWN; 294 } 295 return extract<int>(ret); 309 PyGILState_STATE gstate = PyGILState_Ensure(); 310 object ret = boost::python::call<object>(boost::python::object(it->second).ptr(), channel, source, command, nagios_return_to_py(code), utf8::cvt<std::string>(msg), utf8::cvt<std::string>(perf)); 311 int ret_code = NSCAPI::returnIgnored; 312 if (ret.ptr() == Py_None) { 313 ret_code = NSCAPI::isSuccess; 314 } else { 315 ret_code = extract<bool>(ret)?NSCAPI::isSuccess:NSCAPI::returnIgnored; 316 } 317 PyGILState_Release( gstate ); 318 return ret_code; 296 319 } catch( error_already_set e) { 297 320 log_exception(); 298 return NSCAPI:: returnUNKNOWN;321 return NSCAPI::hasFailed; 299 322 } 300 323 } … … 327 350 328 351 329 std::list<std::wstring> script_wrapper::convert( list lst) {352 std::list<std::wstring> script_wrapper::convert(py::list lst) { 330 353 std::list<std::wstring> ret; 331 354 for (int i = 0;i<len(lst);i++) … … 333 356 return ret; 334 357 } 335 list script_wrapper::convert(std::list<std::wstring> lst) {336 list ret;358 py::list script_wrapper::convert(std::list<std::wstring> lst) { 359 py::list ret; 337 360 BOOST_FOREACH(std::wstring s, lst) { 338 361 ret.append(utf8::cvt<std::string>(s)); … … 359 382 std::wstring wchannel = utf8::cvt<std::wstring>(channel); 360 383 std::string response; 361 int ret = core->submit_message(wchannel, request, response); 362 return make_tuple(ret,response); 363 } 364 365 366 tuple script_wrapper::command_wrapper::simple_query(std::string command, list args) { 384 int ret; 385 Py_BEGIN_ALLOW_THREADS 386 ret = core->submit_message(wchannel, request, response); 387 Py_END_ALLOW_THREADS 388 std::wstring err; 389 nscapi::functions::parse_simple_submit_response(response, err); 390 return make_tuple(ret==NSCAPI::isSuccess,err); 391 } 392 393 bool script_wrapper::command_wrapper::reload(std::string module) { 394 std::wstring wmodule = utf8::cvt<std::wstring>(module); 395 int ret = core->reload(wmodule); 396 return ret==NSCAPI::isSuccess; 397 } 398 399 400 tuple script_wrapper::command_wrapper::simple_query(std::string command, py::list args) { 367 401 std::wstring msg, perf; 368 402 int ret = core->simple_query(utf8::cvt<std::wstring>(command), convert(args), msg, perf); … … 375 409 } 376 410 377 object script_wrapper::command_wrapper::simple_exec(std::string command, list args) {411 object script_wrapper::command_wrapper::simple_exec(std::string command, py::list args) { 378 412 try { 379 413 std::list<std::wstring> result; -
modules/PythonScript/script_wrapper.hpp
ra629015 r9b9be81 18 18 void log_exception(); 19 19 void log_msg(std::wstring x); 20 void log_debug(std::wstring x); 21 void log_error(std::wstring x); 20 22 //std::string get_alias(); 21 23 … … 83 85 84 86 85 int handle_simple_message(const std::string channel, const std::string w cmd, int code, std::wstring &msg, std::wstring &perf) const;86 int handle_message(const std::string channel, const std::string wcmd, std::string &message) const;87 int handle_simple_message(const std::string channel, const std::string wsrc, const std::string wcmd, int code, std::wstring &msg, std::wstring &perf) const; 88 int handle_message(const std::string channel, const std::string &request, std::string &response) const; 87 89 bool has_message_handler(const std::string command); 88 90 bool has_simple_message_handler(const std::string command); … … 113 115 tuple simple_submit(std::string channel, std::string command, status code, std::string message, std::string perf); 114 116 tuple submit(std::string channel, std::string request); 117 bool reload(std::string module); 115 118 }; 116 119 -
scripts/python/lib/test_helper.py
ra629015 r9b9be81 1 from NSCP import Settings, Registry, Core, log, status1 from NSCP import Settings, Registry, Core, log, log_error, status 2 2 3 3 class Callable: … … 41 41 return (fail_count, 9) 42 42 43 def run_test(plugin_id, prefix, cls): 44 instance = cls.getInstance() 45 instance.setup(plugin_id, prefix) 46 ret = instance.run_test() 47 instance.teardown() 48 log('Tested %s (%s of %s)'%(instance.desc(), ret[0], ret[1])) 49 return ret 43 class TestResult: 44 class Entry: 45 status = False 46 desc = 'Unassigned result' 47 level = 0 48 error = None 49 def __init__(self, status, desc, error): 50 self.status = status 51 self.desc = desc 52 self.error = error 50 53 51 class TestResult: 52 fail_count = 0 53 count = 0 54 def log(self): 55 if self.status: 56 log('%s%s'%(''.rjust(self.level, ' '), self)) 57 else: 58 log_error('%s%s'%(''.rjust(self.level, ' '), self)) 59 60 def is_ok(self): 61 return self.status 62 63 def indent(self): 64 self.level = self.level + 1 65 66 def __str__(self): 67 if self.status: 68 return 'OK: %s'%self.desc 69 else: 70 return 'ERROR: %s (%s)'%(self.desc, self.error) 71 72 results = [] 54 73 55 74 def __init__(self): 56 None75 self.results = [] 57 76 58 def add_message(self, status, message): 59 if status: 60 log('OK: %s'%message) 61 self.add(0, 1) 62 else: 63 log('TEST FAILED: %s'%message) 64 self.add(1, 1) 77 def add_message(self, status, message, error = None): 78 e = TestResult.Entry(status, message, error) 79 e.log() 80 self.add_entry(e) 81 82 def assert_equals(self, s1, s2, msg): 83 self.add_message(s1 == s2, msg, '%s != %s'%(s1, s2)) 84 85 def add_entry(self, e): 86 self.results.append(e) 65 87 66 def add(self, failed, total = None): 67 if total == None: 68 (failed, total) = failed 69 self.fail_count += failed 70 self.count += total 88 def add(self, result): 89 for e in result.results: 90 e.indent() 91 self.results.extend(result.results) 71 92 72 93 def log(self): 73 if self.fail_count > 0: 74 log("ERROR: %d/%d test(s) failed"%(self.fail_count,self.count)) 94 okcount = 0 95 count = len(self.results) 96 for e in self.results: 97 e.log() 98 if e.is_ok(): 99 okcount = okcount + 1 100 if okcount == count: 101 log("OK: %d test(s) successfull"%count) 75 102 else: 76 log(" OK: %d test(s) successfull"%self.count)77 return (self.fail_count, self.count)103 log("ERROR: %d/%d test(s) failed"%(count-okcount, count)) 104 return self 78 105 106 def __str__(self): 107 s = '' 108 for e in self.results: 109 s += '%s, '%e 110 return s 111 79 112 def return_nagios(self): 113 okcount = 0 114 count = len(self.results) 80 115 self.log() 81 if self.fail_count == 0:82 return (status.OK, 'All tests ok: %d'%self.count)116 if okcount == count: 117 return (status.OK, "OK: %d test(s) successfull"%count) 83 118 else: 84 return (status.CRITICAL, 'Tests failed %d of %d'%(self.fail_count, self.count)) 85 86 87 def log_test_result(status, message): 88 if status: 89 log('OK: %s'%message) 90 return (0, 1) 91 else: 92 log('TEST FAILED: %s'%message) 93 return (1, 1) 119 return (status.CRITICAL, "ERROR: %d/%d test(s) failed"%(count-okcount, count)) 120 94 121 95 122 def log_result(result): … … 100 127 return (result.fail_count, result.count) 101 128 129 130 def run_test(plugin_id, prefix, cls): 131 result = TestResult() 132 instance = cls.getInstance() 133 instance.setup(plugin_id, prefix) 134 result.add(instance.run_test()) 135 instance.teardown() 136 return result 137 102 138 def run_tests(plugin_id, prefix, list): 103 all_failed = 0 104 all_count = 0 139 result = TestResult() 105 140 for c in list: 106 (failed, count) = run_test(plugin_id, prefix, c) 107 all_failed += failed 108 all_count += count 109 return (all_failed, all_count) 141 result.add(run_test(plugin_id, prefix, c)) 142 return result 110 143 111 144 def test_usage_sample(arguments): -
scripts/python/test_nsca.py
ra629015 r9b9be81 1 1 from NSCP import Settings, Registry, Core, log, status 2 from test_helper import Callable, run_tests, log_test_result, log_result,TestResult2 from test_helper import Callable, run_tests, TestResult 3 3 import plugin_pb2 4 4 from types import * … … 28 28 reg = None 29 29 got_response = False 30 last_source = None 31 last_command = None 32 last_status = None 33 last_message = None 34 last_perfdata = None 35 got_simple_response = None 30 36 31 37 class SingletonHelper: … … 44 50 self.key = '_%stest_command'%prefix 45 51 self.reg = Registry.get(plugin_id) 46 self.reg.simple_subscription('nsca_test_inbox', NSCAServerTest.inbox_handler) 52 self.reg.simple_subscription('nsca_test_inbox', NSCAServerTest.simple_inbox_handler) 53 self.reg.subscription('nsca_test_inbox', NSCAServerTest.inbox_handler) 47 54 48 def inbox_handler(channel, command, code, message, perf):55 def simple_inbox_handler(channel, source, command, code, message, perf): 49 56 instance = NSCAServerTest.getInstance() 50 instance.inbox_handler_wrapped(channel, command, code, message, perf) 57 return instance.simple_inbox_handler_wrapped(channel, source, command, code, message, perf) 58 simple_inbox_handler = Callable(simple_inbox_handler) 59 60 def inbox_handler(channel, request): 61 instance = NSCAServerTest.getInstance() 62 return instance.inbox_handler_wrapped(channel, request) 51 63 inbox_handler = Callable(inbox_handler) 52 64 53 def inbox_handler_wrapped(self, channel, command, code, message, perf): 54 log('Got message %s on %s'%(command, channel)) 65 def simple_inbox_handler_wrapped(self, channel, source, command, status, message, perf): 66 log('Got simple message %s on %s'%(command, channel)) 67 self.got_simple_response = True 68 self.last_source = source 69 self.last_command = command 70 self.last_status = status 71 self.last_message = message 72 self.last_perfdata = perf 73 return True 74 75 def inbox_handler_wrapped(self, channel, request): 55 76 self.got_response = True 77 return (False, '') 56 78 57 79 def teardown(self): 58 80 None 59 81 60 def submit_payload(self ):82 def submit_payload(self, encryption, source, command, status, msg, perf): 61 83 message = plugin_pb2.SubmitRequestMessage() 62 84 63 85 message.header.version = plugin_pb2.Common.VERSION_1 64 86 message.header.recipient_id = "test_rp" 65 message.channel = ' TESTNSCA'87 message.channel = 'nsca_test_outbox' 66 88 host = message.header.hosts.add() 67 89 host.address = "127.0.0.1:15667" 68 90 host.id = "test_rp" 91 enc = host.metadata.add() 92 enc.key = "encryption" 93 enc.value = encryption 94 enc = host.metadata.add() 95 enc.key = "password" 96 enc.value = 'pwd-%s'%encryption 69 97 70 98 payload = message.payload.add() 71 payload.result = status.UNKNOWN 72 payload.command = 'hello_world' 73 payload.message = 'test' 99 payload.result = status 100 payload.command = command 101 payload.message = msg 102 payload.source = source 74 103 self.got_response = False 75 (state, result) = core.submit('TESTNSCA', message.SerializeToString()) 76 log("Status: %s"%status) 77 return self.got_response 104 self.got_simple_response = False 105 (result_code, err) = core.submit('nsca_test_outbox', message.SerializeToString()) 106 result = TestResult() 107 result.add_message(len(err) == 0, 'Testing to send message using %s'%encryption, err) 108 result.add_message(self.got_simple_response, 'Testing to recieve simple message using %s'%encryption) 109 #result.assert_equals(self.last_source, source, 'Verify that source is sent through') 110 result.assert_equals(self.last_command, command, 'Verify that command is sent through') 111 result.assert_equals(self.last_message, msg, 'Verify that message is sent through') 112 result.assert_equals(self.last_perfdata, perf, 'Verify that performance data is sent through') 113 result.add_message(self.got_response, 'Testing to recieve message') 114 return result 115 116 def test_one_full(self, encryption, state, key): 117 return self.submit_payload(encryption, '%ssrc%s'%(key, key), '%scmd%s'%(key, key), state, '%smsg%s'%(key, key), '') 118 119 def test_one(self, crypto): 120 conf = Settings.get() 121 conf.set_string('/settings/NSCA/test_nsca_server', 'encryption', '%s'%crypto) 122 conf.set_string('/settings/NSCA/test_nsca_server', 'password', 'pwd-%s'%crypto) 123 core.reload('test_nsca_server') 124 result = TestResult() 125 result.add(self.test_one_full(crypto, status.UNKNOWN, 'unknown')) 126 result.add(self.test_one_full(crypto, status.OK, 'ok')) 127 result.add(self.test_one_full(crypto, status.WARNING, 'warn')) 128 result.add(self.test_one_full(crypto, status.CRITICAL, 'crit')) 129 return result 78 130 79 131 def run_test(self): 80 132 result = TestResult() 81 133 result.add_message(isOpen('localhost', 15667), 'Checking that port is open') 82 result.add_message(self.submit_payload(), 'Submitting payload to target') 134 # seems broken: "xor", "3way" 135 for c in ["des", "cast128", "xtea", "blowfish", "twofish", "rc2", "aes", "serpent", "gost", "none"]: 136 result.add(self.test_one(c)) 83 137 84 return result .log()138 return result 85 139 86 140 def test(arguments): … … 97 151 log(' | To use this please run nsclient++ in "test mode" like so: |') 98 152 log(' | nscp --test |') 99 log(' | Then start the pytest_test command by typing it and press enter like so:|')100 log(' | pytest_test|')153 log(' | Then start the test_nsca command by typing it and press enter like so: |') 154 log(' | test_nsca |') 101 155 log(' | Lastly exit by typing exit like so: |') 102 156 log(' | exit |') … … 105 159 conf.set_string('/modules', 'test_nsca_server', 'NSCAServer') 106 160 conf.set_string('/modules', 'test_nsca_client', 'NSCAClient') 161 conf.set_string('/modules', 'pytest', 'PythonScript') 162 107 163 conf.set_string('/settings/pytest/scripts', 'test_nsca', 'test_nsca.py') 108 164 109 165 conf.set_string('/settings/NSCA/test_nsca_server', 'port', '15667') 110 166 conf.set_string('/settings/NSCA/test_nsca_server', 'inbox', 'nsca_test_inbox') 167 conf.set_string('/settings/NSCA/test_nsca_server', 'encryption', '1') 111 168 112 169 conf.set_string('/settings/NSCA/test_nsca_client/targets', 'nsca_test_local', 'nsca://127.0.0.1:15667') 170 conf.set_string('/settings/NSCA/test_nsca_client', 'channel', 'nsca_test_outbox') 113 171 114 172 conf.save() -
service/NSCPlugin.cpp
ra629015 r9b9be81 60 60 if (isLoaded()) { 61 61 try { 62 unload(); 62 unload_plugin(); 63 unload_dll(); 63 64 } catch (NSPluginException &e) { 64 65 // ... … … 311 312 * @throws NSPluginException if the module is not loaded and/or cannot be unloaded (plug in remains loaded if so). 312 313 */ 313 void NSCPlugin::unload () {314 void NSCPlugin::unload_plugin() { 314 315 if (!isLoaded()) 315 316 return; … … 322 323 throw NSPluginException(module_, _T("Unhandled exception in fUnLoadModule.")); 323 324 } 325 } 326 void NSCPlugin::unload_dll() { 327 if (isLoaded()) 328 return; 324 329 module_.unload_library(); 325 330 } -
service/NSCPlugin.h
ra629015 r9b9be81 143 143 void deleteBuffer(char**buffer); 144 144 void handleMessage(const char* data, unsigned int len); 145 void unload(void); 145 void unload_dll(void); 146 void unload_plugin(void); 146 147 std::wstring getCongifurationMeta(); 147 148 int commandLineExec(const wchar_t* command, std::string &request, std::string &reply); -
service/NSClient++.cpp
ra629015 r9b9be81 855 855 if (unloadLoggers || !p->hasMessageHandler()) { 856 856 LOG_DEBUG_CORE_STD(_T("Unloading plugin: ") + p->getModule() + _T("...")); 857 p->unload ();857 p->unload_plugin(); 858 858 } else { 859 859 LOG_DEBUG_CORE_STD(_T("Skipping log plugin: ") + p->getModule() + _T("...")); … … 891 891 } 892 892 893 NSCAPI::errorReturn NSClientT::reload(const wchar_t *module) { 894 { 895 std::wstring m = module; 896 boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10)); 897 if (!writeLock.owns_lock()) { 898 LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (007a).")); 899 return NSCAPI::hasFailed; 900 } 901 902 BOOST_FOREACH(plugin_type &p, plugins_) { 903 if (p->get_alias() == m) { 904 LOG_DEBUG_CORE_STD(_T("Found module: ") + m + _T(", reloading...")); 905 p->unload_plugin(); 906 p->load_plugin(NSCAPI::normalStart); 907 return NSCAPI::isSuccess; 908 } 909 } 910 } 911 return NSCAPI::hasFailed; 912 } 913 893 914 void NSClientT::loadPlugins(NSCAPI::moduleLoadMode mode) { 894 915 bool hasBroken = false; … … 960 981 if (plugin->has_routing_handler()) 961 982 routers_.add_plugin(plugin); 962 //settings_manager::get_core()->register_key(_T("/modules"), plugin->getModule(), settings::settings_core::key_string, plugin->getName(), plugin->getDescription(), _T(""), false);983 settings_manager::get_core()->register_key(_T("/modules"), plugin->getModule(), settings::settings_core::key_string, plugin->getName(), plugin->getDescription(), _T(""), false); 963 984 // TODO add comments elsewhere to the settings store for all loaded modules... 964 985 } … … 1037 1058 } 1038 1059 } else */{ 1039 boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));1040 if (!readLock.owns_lock()) {1041 LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (008)."));1042 return NSCAPI::returnUNKNOWN;1043 }1044 1060 try { 1045 1061 nsclient::commands::plugin_type plugin = commands_.get(cmd); -
service/NSClient++.h
ra629015 r9b9be81 175 175 NSCAPI::errorReturn register_submission_listener(unsigned int plugin_id, const wchar_t* channel); 176 176 NSCAPI::errorReturn register_routing_listener(unsigned int plugin_id, const wchar_t* channel); 177 178 NSCAPI::errorReturn reload(const wchar_t *module); 177 179 178 180 struct service_controller { -
service/cli_parser.hpp
rfb7e36a r9b9be81 57 57 ("path", po::value<std::wstring>()->default_value(_T("")), "Path of key to work with.") 58 58 ("key", po::value<std::wstring>()->default_value(_T("")), "Key to work with.") 59 ("set", po::value<std::wstring>() , "Set a key and path to a given value.")59 ("set", po::value<std::wstring>()->implicit_value(_T("")), "Set a key and path to a given value.") 60 60 ("switch", po::value<std::wstring>(), "Set default context to use (similar to migrate but does NOT copy values)") 61 61 ("show", "Set a value given a key and path.") … … 129 129 130 130 if (vm.count("settings")) { 131 mainClient.set_console_log();132 131 return parse_settings(argc-1, &argv[1]); 133 132 } … … 176 175 po::store(po::parse_command_line(argc, argv, all), vm); 177 176 po::notify(vm); 177 178 if (debug) 179 mainClient.set_console_log(); 178 180 179 181 if (process_common_options()) -
service/core_api.cpp
ra629015 r9b9be81 250 250 try { 251 251 settings_manager::get_settings()->set_string(section, key, value); 252 } catch (const std::exception &e) { 253 LOG_ERROR_STD(_T("Failed to setString: ") + key + _T(": ") + utf8::cvt<std::wstring>(e.what())); 254 return NSCAPI::hasFailed; 252 255 } catch (...) { 253 256 LOG_ERROR_STD(_T("Failed to setString: ") + key); … … 398 401 399 402 403 NSCAPI::errorReturn NSAPIReload(const wchar_t *module) { 404 try { 405 return mainClient.reload(module); 406 } catch (...) { 407 LOG_ERROR_STD(_T("Failed to reload: ") + module); 408 return NSCAPI::hasFailed; 409 } 410 return NSCAPI::isSuccess; 411 } 412 400 413 NSCAPI::errorReturn NSAPISettingsSave(void) { 401 414 try { … … 410 423 return NSCAPI::isSuccess; 411 424 } 425 412 426 413 427 … … 482 496 if (wcscasecmp(buffer, _T("NSAPIRegisterRoutingListener")) == 0) 483 497 return reinterpret_cast<LPVOID>(&NSAPIRegisterRoutingListener); 498 if (wcscasecmp(buffer, _T("NSAPIReload")) == 0) 499 return reinterpret_cast<LPVOID>(&NSAPIReload); 484 500 485 501 LOG_ERROR_STD(_T("Function not found: ") + buffer); -
service/core_api.h
ra629015 r9b9be81 65 65 NSCAPI::errorReturn NSAPIRegisterSubmissionListener(unsigned int plugin_id, const wchar_t* channel); 66 66 NSCAPI::errorReturn NSAPIRegisterRoutingListener(unsigned int plugin_id, const wchar_t* channel); 67 NSCAPI::errorReturn NSAPIReload(const wchar_t*); -
service/settings_client.hpp
rfb7e36a r9b9be81 12 12 13 13 public: 14 settings_client(NSClient* core) : core_(core) {}14 settings_client(NSClient* core) : core_(core), default_(false) {} 15 15 16 16 std::wstring get_source() { … … 29 29 return; 30 30 } 31 if (default_) 31 if (default_) { 32 std::wcout << _T("Adding default values") << std::endl; 32 33 settings_manager::get_core()->update_defaults(); 34 } 33 35 } 34 36
Note: See TracChangeset
for help on using the changeset viewer.








