Changeset 74e060a in nscp
- Timestamp:
- 03/19/12 07:46:22 (14 months ago)
- Branches:
- master, 0.4.0, 0.4.1, 0.4.2
- Children:
- 822454f
- Parents:
- c88cf98
- Files:
-
- 21 edited
-
changelog (modified) (1 diff)
-
helpers/installer-dlls/main_dll/main_dll.cpp (modified) (4 diffs)
-
helpers/installer-dlls/main_dll/main_dll.def (modified) (1 diff)
-
helpers/installers/installer/Product.wxs (modified) (4 diffs)
-
include/nscapi/settings_object.hpp (modified) (1 diff)
-
include/pdh/collectors.hpp (modified) (1 diff)
-
include/pdh/counters.hpp (modified) (1 diff)
-
libs/dotnet-plugin-api/CMakeLists.txt (modified) (2 diffs)
-
modules/CheckEventLog/CheckEventLog.cpp (modified) (11 diffs)
-
modules/CheckEventLog/CheckEventLog.h (modified) (4 diffs)
-
modules/CheckEventLog/eventlog_record.hpp (modified) (4 diffs)
-
modules/CheckEventLog/filter.cpp (modified) (4 diffs)
-
modules/CheckEventLog/filter.hpp (modified) (1 diff)
-
modules/DotnetPlugins/CMakeLists.txt (modified) (2 diffs)
-
modules/GraphiteClient/GraphiteClient.cpp (modified) (16 diffs)
-
modules/GraphiteClient/GraphiteClient.def (modified) (1 diff)
-
modules/GraphiteClient/GraphiteClient.h (modified) (7 diffs)
-
modules/GraphiteClient/module.cmake (modified) (1 diff)
-
scripts/python/test_eventlog.py (modified) (5 diffs)
-
version.hpp (modified) (1 diff)
-
version.txt (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
changelog
rc88cf98 r74e060a 4 4 * Fixa dependonservice LanManWorkStation (old win) 5 5 * Fix RtlStringFromGUID problem on NT4 6 7 2012-03-19 MickeM 8 * Fixed issue in installer and "Make file writable" by everyone now uses Users SID. 9 * Fixed issue in installer and "Default plugins" now correctly sets them to 1. 10 11 2012-03-18 MickeM 12 * Removed dependency on tcpip from the service and the installer 13 * Added new command to EventLog CheckEventlogCached which checks result caught by the real-time process. 14 CheckEventLogCACHE warn=gt:1 crit=gt:5 15 Requires a configured real-time checker to work. 16 * Added a series of keywords to EventLog check to facilitate better checking 17 * Added a set of aliases to make EventLog behave more like Wdinwos Eventlog viewer. 18 * Added a lot of unit test cases to the Eventlog checker. 19 * Fixed issue with default schedule beeing added as an item and not a template 6 20 7 21 2012-03-11 MickeM -
helpers/installer-dlls/main_dll/main_dll.cpp
rc88cf98 r74e060a 1 #define _WIN32_WINNT 0x0500 1 2 #include <windows.h> 2 3 #include <msi.h> … … 10 11 #include <file_helpers.hpp> 11 12 #include "installer_helper.hpp" 13 #include <Sddl.h> 12 14 #include "../../settings_manager/settings_manager_impl.h" 13 15 … … 305 307 306 308 if (h.propertyTouched(_T("CONF_CHECKS"))) { 309 modval = h.getPropery(_T("CONF_CHECKS")); 307 310 write_key(data, 1, modpath, _T("CheckSystem"), modval); 308 311 write_key(data, 1, modpath, _T("CheckDisk"), modval); … … 459 462 return ERROR_SUCCESS; 460 463 }; 464 465 466 extern "C" UINT __stdcall TranslateSid (MSIHANDLE hInstall) { 467 TCHAR szSid[MAX_PATH] = {0}; 468 TCHAR szSidProperty[MAX_PATH] = {0}; 469 TCHAR szName[MAX_PATH] = {0}; 470 DWORD size = MAX_PATH; 471 UINT ret = 0; 472 ret = MsiGetProperty (hInstall, _T("TRANSLATE_SID"), szSid, &size); 473 474 if(ret != ERROR_SUCCESS) { 475 return 4444; 476 } 477 478 size = MAX_PATH; 479 ret = MsiGetProperty (hInstall, _T("TRANSLATE_SID_PROPERTY"), szSidProperty, &size); 480 481 if(ret != ERROR_SUCCESS) { 482 return 4445; 483 } 484 485 PSID pSID = NULL; 486 487 if(!ConvertStringSidToSid(szSid, &pSID)) { 488 return 4446; 489 } 490 491 size = MAX_PATH; 492 TCHAR szRefDomain[MAX_PATH] = {0}; 493 SID_NAME_USE nameUse; 494 DWORD refSize = MAX_PATH; 495 if(!LookupAccountSid(NULL, pSID, szName, &size, szRefDomain, &refSize, &nameUse)) { 496 if(pSID != NULL) { 497 LocalFree(pSID); 498 } 499 return 4447; 500 } 501 502 ret = MsiSetProperty (hInstall, szSidProperty, szName); 503 if(!ConvertStringSidToSid(szSid, &pSID)) { 504 if(pSID != NULL) { 505 LocalFree(pSID); 506 } 507 return 4448; 508 } 509 510 if(pSID != NULL) { 511 LocalFree(pSID); 512 } 513 return ERROR_SUCCESS; 514 } 515 -
helpers/installer-dlls/main_dll/main_dll.def
rb7d17f8 r74e060a 6 6 ExecWriteConfig 7 7 NeedUninstall 8 TranslateSid -
helpers/installers/installer/Product.wxs
rc88cf98 r74e060a 50 50 Description="Monitoring agent for nagios (and others) used to respond to status queries" 51 51 Arguments="service --run --name [SERVICE_NAME]"> 52 <!-- 52 53 <ServiceDependency Id="Tcpip" /> 54 --> 53 55 </ServiceInstall> 54 56 <ServiceControl Id="StartSWCNSCP" Name="[SERVICE_NAME]" Start="install" Stop="both" Wait="yes" Remove="uninstall" /> … … 81 83 <Component Id="SampleConfigUser" Guid="AA636DB0-A0B9-4dd2-B74C-$(var.Postfix.GUID)" Win64="$(var.Win64)"> 82 84 <File Id="NSClientINIUser" Name="nsclient.ini" DiskId="1" Source="$(var.Path.ini)/nsclient.dist" Vital="no" PatchIgnore="yes"> 83 <Permission User=" Everyone" GenericRead="yes" Read="yes" GenericWrite="yes" Write="yes"/>85 <Permission User="[USERGROUP_USERS]" GenericRead="yes" Read="yes" GenericWrite="yes" Write="yes"/> 84 86 </File> 85 87 <RemoveFile Id="PurgeConfigFilesUser" Name="*.ini" On="uninstall" /> … … 300 302 <CustomAction Id="GenConfig" BinaryKey="WixCA" DllEntry="CAQuietExec" Impersonate="no" Return="ignore" Execute="deferred"/> 301 303 302 <Binary Id='InstallerHelper' SourceFile='$(var.Helpers)/main_dll.dll' /> 304 <CustomAction Id="SetUserGroupUsers" Property="TRANSLATE_SID" Value="S-1-5-32-545" Return="check" /> 305 <CustomAction Id="SetUserGroupUsersProp" Property="TRANSLATE_SID_PROPERTY" Value="USERGROUP_USERS" Return="check" /> 306 <CustomAction Id="TranslateUserGroupUsers" BinaryKey="InstallerHelper" DllEntry="TranslateSid"/> 307 308 <Binary Id='InstallerHelper' SourceFile='$(var.Helpers)/main_dll.dll' /> 303 309 304 310 <InstallExecuteSequence> … … 308 314 <Custom Action="GenConfig.Command" After="ScheduleWriteConfig">NOT REMOVE AND INSTALL_SAMPLE_CONFIG = 1</Custom> 309 315 <Custom Action="GenConfig" After="GenConfig.Command">NOT REMOVE AND INSTALL_SAMPLE_CONFIG = 1</Custom> 310 </InstallExecuteSequence> 316 317 <Custom Action="SetUserGroupUsers" After="LaunchConditions">NOT Installed</Custom> 318 <Custom Action="SetUserGroupUsersProp" After="SetUserGroupUsers">NOT Installed</Custom> 319 <Custom Action="TranslateUserGroupUsers" After="SetUserGroupUsersProp">NOT Installed</Custom> 320 321 </InstallExecuteSequence> 311 322 312 323 <InstallUISequence> -
include/nscapi/settings_object.hpp
rc74d7b6 r74e060a 65 65 optional_object tmp = find_object(object.parent); 66 66 if (!tmp) { 67 parent = add(proxy, path, object.parent, _T("")); 68 add_template(parent); 67 parent = add(proxy, path, object.parent, _T(""), true); 69 68 } else { 70 69 parent = *tmp; -
include/pdh/collectors.hpp
rc5ec0c8 r74e060a 299 299 DWORD extra_format; 300 300 RoundINTPDHBufferListenerImpl() : buffer(NULL), length(0), current(0), hasValue_(false), parent_(NULL), extra_format(0) {} 301 RoundINTPDHBufferListenerImpl(int length_) : buffer(NULL), length(0), current(0), hasValue_(false), parent_(NULL) {301 RoundINTPDHBufferListenerImpl(int length_) : buffer(NULL), length(0), current(0), hasValue_(false), parent_(NULL), extra_format(0) { 302 302 resize(length_); 303 303 } -
include/pdh/counters.hpp
r5e12ba6 r74e060a 107 107 if (!listener_) 108 108 return; 109 PDH::PDHError status = PDH::PDHFactory::get_impl()->PdhGetFormattedCounterValue(hCounter_, listener_->getFormat(), NULL, &data_); 109 DWORD format = listener_->getFormat(); 110 PDH::PDHError status = PDH::PDHFactory::get_impl()->PdhGetFormattedCounterValue(hCounter_, format, NULL, &data_); 110 111 if (status.is_error()) { 111 throw PDHException(name_, _T("PdhGetFormattedCounterValue failed "), status);112 throw PDHException(name_, _T("PdhGetFormattedCounterValue failed {format: ") + strEx::itos(format) + _T("}"), status); 112 113 } 113 114 listener_->collect(*this); -
libs/dotnet-plugin-api/CMakeLists.txt
ree52cdd r74e060a 14 14 STRING(REPLACE "/EHsc" "/EHa" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) 15 15 STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) 16 STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS_RELWITHDEBINFO ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}) 17 STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS_MINSIZEREL ${CMAKE_CXX_FLAGS_MINSIZEREL}) 16 18 STRING(REPLACE "/MTd" "/MDd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) 17 19 STRING(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) … … 22 24 MESSAGE(STATUS "---> DOT NET FLAGS: ${CMAKE_CXX_FLAGS_DEBUG}") 23 25 MESSAGE(STATUS "---> DOT NET FLAGS: ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}") 26 MESSAGE(STATUS "---> DOT NET FLAGS: ${CMAKE_CXX_FLAGS_MINSIZEREL}") 24 27 25 28 ADD_LIBRARY(NSCPDOTNET MODULE ${SRCS}) -
modules/CheckEventLog/CheckEventLog.cpp
ree52cdd r74e060a 160 160 NSC_LOG_ERROR(_T("Failed to submit evenhtlog result: ") + response); 161 161 } 162 163 if (cache_) { 164 boost::unique_lock<boost::timed_mutex> lock(cache_mutex_, boost::get_system_time() + boost::posix_time::seconds(5)); 165 if (!lock.owns_lock()) { 166 NSC_LOG_ERROR(_T("ERROR: Could not get CheckEventLogCache mutex.")); 167 return; 168 } 169 hit_cache_.push_back(message); 170 } 171 } 172 bool real_time_thread::check_cache(unsigned long &count, std::wstring &messages) { 173 if (!cache_) { 174 messages = _T("ERROR: Cache is not enabled!"); 175 NSC_LOG_ERROR(messages); 176 return false; 177 } 178 boost::unique_lock<boost::timed_mutex> lock(cache_mutex_, boost::get_system_time() + boost::posix_time::seconds(5)); 179 if (!lock.owns_lock()) { 180 messages = _T("ERROR: Could not get CheckEventLogCache mutex."); 181 NSC_LOG_ERROR(messages); 182 return false; 183 } 184 BOOST_FOREACH(const std::wstring &s, hit_cache_) { 185 if (!messages.empty()) 186 messages += _T(", "); 187 messages += s; 188 } 189 count = hit_cache_.size(); 190 hit_cache_.clear(); 191 return true; 192 } 193 void real_time_thread::debug_miss(const EventLogRecord &record) { 194 std::wstring message = record.render(true, info.syntax, DATE_FORMAT, info.dwLang); 195 NSC_DEBUG_MSG_STD(_T("No filter matched: ") + message); 162 196 } 163 197 164 198 void real_time_thread::thread_proc() { 165 if (filters_.size() != 1) { 166 NSC_LOG_ERROR_STD(_T("Invalid filter size (for now)...")); 167 return; 168 } 169 170 eventlog_filter::filter_argument fargs = eventlog_filter::factories::create_argument(info.syntax, DATE_FORMAT); 171 fargs->filter = *filters_.begin(); 172 fargs->debug = true; 173 eventlog_filter::filter_engine engine = eventlog_filter::factories::create_engine(fargs); 174 175 176 177 if (!engine) { 178 NSC_LOG_ERROR_STD(_T("No filter subsystem available")); 179 return; 180 } 181 182 if (!engine->boot()) { 183 NSC_LOG_ERROR_STD(_T("Error booting filters")); 184 return; 185 } 186 187 std::wstring message; 188 if (!engine->validate(message)) { 189 NSC_LOG_ERROR_STD(_T("Error validating session: ") + message); 190 return; 191 } 199 200 std::list<eventlog_filter::filter_engine> filters; 201 BOOST_FOREACH(std::wstring filter, filters_) { 202 eventlog_filter::filter_argument fargs = eventlog_filter::factories::create_argument(info.syntax, DATE_FORMAT); 203 fargs->filter = filter; 204 fargs->debug = true; 205 eventlog_filter::filter_engine engine = eventlog_filter::factories::create_engine(fargs); 206 207 if (!engine) { 208 NSC_LOG_ERROR_STD(_T("Invalid filter: ") + filter); 209 continue; 210 } 211 212 if (!engine->boot()) { 213 NSC_LOG_ERROR_STD(_T("Error booting filter: ") + filter); 214 continue; 215 } 216 217 std::wstring message; 218 if (!engine->validate(message)) { 219 NSC_LOG_ERROR_STD(_T("Error validating filter: ") + message); 220 continue; 221 } 222 filters.push_back(engine); 223 } 224 192 225 193 226 … … 240 273 EventLogRecord elr(el->get_name(), pevlr, ltime); 241 274 boost::shared_ptr<eventlog_filter::filter_obj> arg = boost::shared_ptr<eventlog_filter::filter_obj>(new eventlog_filter::filter_obj(elr)); 242 243 if (engine->match(arg)) { 244 process_record(elr); 245 } else if (fargs->debug) { 246 // TODO: Decrease timeout here so we get "ok" every x seconds even if we have ok results... 247 NSC_DEBUG_MSG(_T("Ignored record: ") + elr.render(true, fargs->syntax)); 275 bool matched = false; 276 277 BOOST_FOREACH(eventlog_filter::filter_engine engine, filters) { 278 if (engine->match(arg)) { 279 process_record(elr); 280 matched = true; 281 } 248 282 } 283 if (debug_ && !matched) 284 debug_miss(elr); 285 249 286 pevlr = el->read_record_with_buffer(); 250 287 } … … 293 330 try { 294 331 register_command(_T("CheckEventLog"), _T("Check for errors in the event logger!")); 295 register_command(_T("check_event_log"), _T("Check for errors in the event logger!"));296 332 register_command(_T("check_eventlog"), _T("Check for errors in the event logger!")); 333 register_command(_T("checkeventlogcache"), _T("Check for errors in the event logger!")); 334 register_command(_T("check_eventlog_cache"), _T("Check for errors in the event logger!")); 297 335 298 336 sh::settings_registry settings(get_settings_proxy()); 299 337 settings.set_alias(alias, _T("eventlog")); 338 300 339 301 340 settings.alias().add_path_to_settings() … … 304 343 (_T("real-time"), _T("CONFIGURE REALTIME CHECKING"), _T("A set of options to configure the real time checks")) 305 344 306 (_T("real-time/filters"), sh::fun_values_path(boost::bind(&real_time_thread::add_realtime_filter, thread_, _1, _2)),345 (_T("real-time/filters"), sh::fun_values_path(boost::bind(&real_time_thread::add_realtime_filter, &thread_, _1, _2)), 307 346 _T("REALTIME FILTERS"), _T("A set of filters to use in real-time mode")) 308 347 ; … … 348 387 (_T("log"), sh::string_fun_key<std::wstring>(boost::bind(&real_time_thread::set_eventlog, &thread_, _1), _T("application")), 349 388 _T("LOGS TO CHECK"), _T("Coma separated list of logs to check")) 389 390 (_T("debug"), sh::bool_key(&thread_.debug_, false), 391 _T("DEBUG"), _T("Log missed records (usefull to detect issues with filters) not usefull in production as it is a bit of a resource hog.")) 392 393 (_T("enable active"), sh::bool_key(&thread_.cache_, false), 394 _T("ENABLE ACTIVE MONITORING"), _T("This will store all matches so you can use real-time filters from active monitoring (use CheckEventlogCache).")) 350 395 351 396 ; … … 416 461 } 417 462 }; 463 typedef checkHolders::CheckContainer<checkHolders::MaxMinBoundsULongInteger> EventLogQuery1Container; 464 typedef checkHolders::CheckContainer<checkHolders::ExactBoundsULongInteger> EventLogQuery2Container; 465 466 NSCAPI::nagiosReturn CheckEventLog::checkCache(std::list<std::wstring> &arguments, std::wstring &message, std::wstring &perf) { 467 468 EventLogQuery1Container query1; 469 EventLogQuery2Container query2; 470 bool bPerfData = true; 471 unsigned int truncate = 0; 472 NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK; 473 474 try { 475 MAP_OPTIONS_BEGIN(arguments) 476 MAP_OPTIONS_NUMERIC_ALL(query1, _T("")) 477 MAP_OPTIONS_EXACT_NUMERIC_ALL(query2, _T("")) 478 MAP_OPTIONS_STR2INT(_T("truncate"), truncate) 479 MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData) 480 MAP_OPTIONS_MISSING(message, _T("Unknown argument: ")) 481 MAP_OPTIONS_END() 482 } catch (checkHolders::parse_exception e) { 483 message = e.getMessage(); 484 return NSCAPI::returnUNKNOWN; 485 } catch (...) { 486 message = _T("Invalid command line!"); 487 return NSCAPI::returnUNKNOWN; 488 } 489 490 unsigned long count = 0; 491 if (!thread_.check_cache(count, message)) { 492 return NSCAPI::returnUNKNOWN; 493 } 494 495 if (!bPerfData) { 496 query1.perfData = false; 497 query2.perfData = false; 498 } 499 if (query1.alias.empty()) 500 query1.alias = _T("eventlog"); 501 if (query2.alias.empty()) 502 query2.alias = _T("eventlog"); 503 if (query1.hasBounds()) 504 query1.runCheck(count, returnCode, message, perf); 505 else if (query2.hasBounds()) 506 query2.runCheck(count, returnCode, message, perf); 507 else { 508 message = _T("No bounds specified!"); 509 return NSCAPI::returnUNKNOWN; 510 } 511 if ((truncate > 0) && (message.length() > (truncate-4))) 512 message = message.substr(0, truncate-4) + _T("..."); 513 if (message.empty()) 514 message = _T("Eventlog check ok"); 515 return returnCode; 516 } 418 517 419 518 NSCAPI::nagiosReturn CheckEventLog::handleCommand(const std::wstring &target, const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &message, std::wstring &perf) { 420 if (command != _T("checkeventlog")) 519 if (command == _T("checkeventlogcache") || command == _T("check_eventlog_cache")) 520 return checkCache(arguments, message, perf); 521 if (command != _T("checkeventlog") && command != _T("check_eventlog")) 421 522 return NSCAPI::returnIgnored; 422 523 simple_timer time; 423 typedef checkHolders::CheckContainer<checkHolders::MaxMinBoundsULongInteger> EventLogQuery1Container;424 typedef checkHolders::CheckContainer<checkHolders::ExactBoundsULongInteger> EventLogQuery2Container;425 524 426 525 NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK; … … 633 732 634 733 bool help = false; 635 std::wstring type, category,severity, source_name;734 std::wstring type, severity, source_name; 636 735 std::vector<std::wstring> strings; 637 WORD wEventID ;736 WORD wEventID = 0, category = 0, customer = 0; 638 737 WORD facility = 0; 639 738 po::options_description desc("Allowed options"); … … 642 741 ("source,s", po::wvalue<std::wstring>(&source_name)->default_value(_T("Application Error")), "source to use") 643 742 ("type,t", po::wvalue<std::wstring>(&type), "Event type") 644 ("facility,f", po::value<WORD>(&facility), "Facility") 743 ("level,l", po::wvalue<std::wstring>(&type), "Event level (type)") 744 ("facility,f", po::value<WORD>(&facility), "Facility/Qualifier") 745 ("qualifier,q", po::value<WORD>(&facility), "Facility/Qualifier") 645 746 ("severity", po::wvalue<std::wstring>(&severity), "Event severity") 646 ("category,c", po::wvalue<std::wstring>(&category), "Event category") 747 ("category,c", po::value<WORD>(&category), "Event category") 748 ("customer", po::value<WORD>(&customer), "Customer bit 0,1") 647 749 ("arguments,a", po::wvalue<std::vector<std::wstring> >(&strings), "Message arguments (strings)") 648 750 ("eventlog-arguments", po::wvalue<std::vector<std::wstring> >(&strings), "Message arguments (strings)") … … 667 769 WORD dwType = EventLogRecord::translateType(type); 668 770 WORD wSeverity = EventLogRecord::translateSeverity(severity); 669 WORD dwCategory = EventLogRecord::translateType(category); 670 DWORD tID = (wEventID&0xffff) | (wSeverity<<30) | (facility<<16); 771 DWORD tID = (wEventID&0xffff) | ((facility&0xfff)<<16) | ((customer&0x1)<<29) | ((wSeverity&0x3)<<30); 671 772 672 773 int size = 0; … … 680 781 } 681 782 682 if (!ReportEvent(source, dwType, dwCategory, tID, NULL, strings.size(), 0, string_data, NULL)) {783 if (!ReportEvent(source, dwType, category, tID, NULL, strings.size(), 0, string_data, NULL)) { 683 784 message = _T("Could not report the event"); 684 785 return NSCAPI::hasFailed; … … 691 792 NSC_LOG_ERROR_STD(_T("Failed to parse command line: ") + utf8::cvt<std::wstring>(e.what())); 692 793 } 693 694 695 794 return NSCAPI::returnIgnored; 696 795 } -
modules/CheckEventLog/CheckEventLog.h
r58f0e80 r74e060a 53 53 HANDLE stop_event_; 54 54 std::list<std::wstring> lists_; 55 std::list<std::wstring> hit_cache_; 56 boost::timed_mutex cache_mutex_; 55 57 56 real_time_thread() : enabled_(false), start_age_(0), max_age_(0) { 58 bool cache_; 59 bool debug_; 60 61 real_time_thread() : enabled_(false), start_age_(0), max_age_(0), debug_(false), cache_(false) { 57 62 set_start_age(_T("30m")); 58 63 set_max_age(_T("5m")); … … 77 82 void set_language(std::string lang); 78 83 void set_filter(std::wstring flt) { 79 if (!flt.empty()) 80 add_realtime_filter(_T("filter"), flt); 84 add_realtime_filter(_T("filter"), flt); 81 85 } 82 86 bool has_filters() { … … 86 90 bool stop(); 87 91 92 bool check_cache(unsigned long &count, std::wstring &messages); 93 88 94 void thread_proc(); 89 95 // void process_events(eventlog_filter::filter_engine engine, eventlog_wrapper &eventlog); 90 96 void process_no_events(); 91 97 void process_record(const EventLogRecord &record); 98 void debug_miss(const EventLogRecord &record); 92 99 // void process_event(eventlog_filter::filter_engine engine, const EVENTLOGRECORD* record); 93 100 }; … … 125 132 bool hasMessageHandler(); 126 133 NSCAPI::nagiosReturn handleCommand(const std::wstring &target, const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &message, std::wstring &perf); 134 NSCAPI::nagiosReturn checkCache(std::list<std::wstring> &arguments, std::wstring &message, std::wstring &perf); 127 135 NSCAPI::nagiosReturn commandRAWLineExec(const wchar_t* char_command, const std::string &request, std::string &response); 128 136 NSCAPI::nagiosReturn insert_eventlog(std::vector<std::wstring> arguments, std::wstring &message); -
modules/CheckEventLog/eventlog_record.hpp
r72eea1f r74e060a 24 24 return pevlr_->TimeWritten; 25 25 } 26 inline WORD category() const { 27 return pevlr_->EventCategory; 28 } 26 29 inline std::wstring get_source() const { 27 30 return reinterpret_cast<const WCHAR*>(reinterpret_cast<const BYTE*>(pevlr_) + sizeof(EVENTLOGRECORD)); … … 35 38 } 36 39 inline DWORD severity() const { 37 return (pevlr_->EventID>>30); 40 return (pevlr_->EventID>>30) & 0x3; 41 } 42 inline DWORD facility() const { 43 return (pevlr_->EventID>>16) & 0xfff; 44 } 45 inline WORD customer() const { 46 return (pevlr_->EventID>>29) & 0x1; 47 } 48 inline DWORD raw_id() const { 49 return pevlr_->EventID; 38 50 } 39 51 … … 274 286 return get_time(pevlr_->TimeWritten); 275 287 } 288 inline std::wstring get_log() { 289 return file_; 290 } 276 291 277 292 std::wstring render(bool propper, std::wstring syntax, std::wstring date_format = DATE_FORMAT, DWORD langId = 0) const { … … 290 305 strEx::replace(syntax, _T("%written-raw%"), strEx::itos(pevlr_->TimeWritten)); 291 306 strEx::replace(syntax, _T("%type%"), translateType(eventType())); 307 strEx::replace(syntax, _T("%category%"), strEx::itos(pevlr_->EventCategory)); 308 strEx::replace(syntax, _T("%facility%"), strEx::itos(facility())); 309 strEx::replace(syntax, _T("%qualifier%"), strEx::itos(facility())); 310 strEx::replace(syntax, _T("%customer%"), strEx::itos(customer())); 311 strEx::replace(syntax, _T("%rawid%"), strEx::itos(raw_id())); 292 312 strEx::replace(syntax, _T("%severity%"), translateSeverity(severity())); 293 313 strEx::replace(syntax, _T("%strings%"), enumStrings()); 314 strEx::replace(syntax, _T("%log%"), file_); 315 strEx::replace(syntax, _T("%file%"), file_); 294 316 strEx::replace(syntax, _T("%id%"), strEx::itos(eventID())); 295 317 strEx::replace(syntax, _T("%user%"), userSID()); -
modules/CheckEventLog/filter.cpp
r72eea1f r74e060a 48 48 (_T("id"), (type_int)) 49 49 (_T("source"), (type_string)) 50 (_T("file"), (type_string)) 51 (_T("log"), (type_string)) 50 52 (_T("type"), (type_custom_type)) 53 (_T("level"), (type_custom_type)) 51 54 (_T("severity"), (type_custom_severity)) 55 (_T("category"), (type_int)) 56 (_T("qualifier"), (type_int)) 57 (_T("facility"), (type_int)) 58 (_T("customer"), (type_int)) 59 (_T("rawid"), (type_int)) 52 60 (_T("message"), (type_string)) 53 61 (_T("strings"), (type_string)) … … 83 91 else if (key == _T("computer")) 84 92 ret = &filter_obj::get_computer; 93 else if (key == _T("log")) 94 ret = &filter_obj::get_log; 95 else if (key == _T("file")) 96 ret = &filter_obj::get_log; 85 97 else 86 98 NSC_DEBUG_MSG_STD(_T("Failed to bind (string): ") + key); … … 93 105 else if (key == _T("type")) 94 106 ret = &filter_obj::get_el_type; 107 else if (key == _T("level")) 108 ret = &filter_obj::get_el_type; 95 109 else if (key == _T("severity")) 96 110 ret = &filter_obj::get_severity; … … 99 113 else if (key == _T("written")) 100 114 ret = &filter_obj::get_written; 115 else if (key == _T("category")) 116 ret = &filter_obj::get_category; 117 else if (key == _T("qualifier")) 118 ret = &filter_obj::get_facility; 119 else if (key == _T("facility")) 120 ret = &filter_obj::get_facility; 121 else if (key == _T("customer")) 122 ret = &filter_obj::get_customer; 123 else if (key == _T("rawid")) 124 ret = &filter_obj::get_raw_id; 101 125 else 102 126 NSC_DEBUG_MSG_STD(_T("Failed to bind (int): ") + key); -
modules/CheckEventLog/filter.hpp
r72eea1f r74e060a 50 50 return record.enumStrings(); 51 51 } 52 std::wstring get_log() { 53 return record.get_log(); 54 } 52 55 long long get_written() { 53 56 return record.written(); 57 } 58 long long get_category() { 59 return record.category(); 60 } 61 long long get_facility() { 62 return record.facility(); 63 } 64 long long get_customer() { 65 return record.customer(); 66 } 67 long long get_raw_id() { 68 return record.raw_id(); 54 69 } 55 70 long long get_generated() { -
modules/DotnetPlugins/CMakeLists.txt
ree52cdd r74e060a 33 33 STRING(REPLACE "/EHsc" "/EHa" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) 34 34 STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) 35 STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS_RELWITHDEBINFO ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}) 36 STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS_MINSIZEREL ${CMAKE_CXX_FLAGS_MINSIZEREL}) 35 37 STRING(REPLACE "/MTd" "/MDd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) 36 38 STRING(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) … … 38 40 STRING(REPLACE "/GZ" "" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) 39 41 SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /clr /FU ${BUILD_TARGET_EXE_PATH}/NSCPDOTNET.dll") 42 40 43 ADD_LIBRARY(${TARGET} MODULE ${SRCS}) 41 44 -
modules/GraphiteClient/GraphiteClient.cpp
r330af36 r74e060a 20 20 ***************************************************************************/ 21 21 #include "stdafx.h" 22 #include " NSCAClient.h"22 #include "GraphiteClient.h" 23 23 24 24 #include <utils.h> 25 25 #include <strEx.h> 26 26 27 #include <nsca/nsca_enrypt.hpp>28 #include <nsca/nsca_packet.hpp>29 #include <nsca/nsca_socket.hpp>30 31 27 #include <settings/client/settings_client.hpp> 28 #include <nscapi/nscapi_protobuf_functions.hpp> 32 29 33 30 namespace sh = nscapi::settings_helper; 34 31 32 const std::wstring GraphiteClient::command_prefix = _T("graphite"); 35 33 /** 36 34 * Default c-tor 37 35 * @return 38 36 */ 39 NSCAAgent::NSCAAgent() {}37 GraphiteClient::GraphiteClient() {} 40 38 41 39 /** … … 43 41 * @return 44 42 */ 45 NSCAAgent::~NSCAAgent() {}43 GraphiteClient::~GraphiteClient() {} 46 44 47 45 /** … … 50 48 * @return true 51 49 */ 52 bool NSCAAgent::loadModule() {50 bool GraphiteClient::loadModule() { 53 51 return false; 54 52 } 55 /* 56 DEFINE_SETTING_S(REPORT_MODE, NSCA_SERVER_SECTION, "report", "all"); 57 DESCRIBE_SETTING(REPORT_MODE, "REPORT MODE", "What to report to the server (any of the following: all, critical, warning, unknown, ok)"); 58 */ 59 60 bool NSCAAgent::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) { 61 62 63 std::wstring encryption, password, nscahost; 64 std::string delay; 65 unsigned int timeout = 30, payload_length = 512, nscaport = 5666; 53 54 bool GraphiteClient::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) { 55 66 56 try { 57 67 58 sh::settings_registry settings(get_settings_proxy()); 68 settings.set_alias(_T(" NSCA"), alias, _T("client"));59 settings.set_alias(_T("graphite"), alias, _T("client")); 69 60 target_path = settings.alias().get_settings_path(_T("targets")); 70 61 71 62 settings.alias().add_path_to_settings() 72 (_T(" NSCA CLIENT SECTION"), _T("Section for NSCApassive check module."))73 74 (_T("handlers"), sh::fun_values_path(boost::bind(& NSCAAgent::add_command, this, _1, _2)),63 (_T("GRAPHITE CLIENT SECTION"), _T("Section for graphite passive check module.")) 64 65 (_T("handlers"), sh::fun_values_path(boost::bind(&GraphiteClient::add_command, this, _1, _2)), 75 66 _T("CLIENT HANDLER SECTION"), _T("")) 76 67 77 (_T("targets"), sh::fun_values_path(boost::bind(& NSCAAgent::add_target, this, _1, _2)),68 (_T("targets"), sh::fun_values_path(boost::bind(&GraphiteClient::add_target, this, _1, _2)), 78 69 _T("REMOTE TARGET DEFINITIONS"), _T("")) 79 70 ; 80 71 81 72 settings.alias().add_key_to_settings() 82 (_T("hostname"), sh::string_key(&hostname_),83 _T("HOSTNAME"), _T("The host name of this host if set to blank (default) the windows name of the computer will be used."))84 85 73 (_T("channel"), sh::wstring_key(&channel_, _T("NSCA")), 86 74 _T("CHANNEL"), _T("The channel to listen to.")) 87 88 (_T("delay"), sh::string_fun_key<std::wstring>(boost::bind(&NSCAAgent::set_delay, this, _1), _T("0")),89 _T("DELAY"), _T(""))90 75 ; 91 76 … … 94 79 ; 95 80 96 settings.alias().add_key_to_settings(_T("targets/default"))97 98 (_T("timeout"), sh::uint_key(&timeout, 30),99 _T("TIMEOUT"), _T("Timeout when reading packets on incoming sockets. If the data has not arrived withint this time we will bail out."))100 101 (_T("host"), sh::wstring_key(&nscahost),102 _T("NSCA HOST"), _T("The NSCA server to report results to."))103 104 (_T("port"), sh::uint_key(&nscaport, 5667),105 _T("NSCA PORT"), _T("The NSCA server port"))106 107 (_T("encryption"), sh::wstring_key(&encryption, _T("aes")),108 _T("ENCRYPTION METHOD"), _T("Number corresponding to the various encryption algorithms (see the wiki). Has to be the same as the server or it wont work at all."))109 110 (_T("password"), sh::wstring_key(&password),111 _T("PASSWORD"), _T("The password to use. Again has to be the same as the server or it wont work at all."))112 113 (_T("payload length"), sh::uint_key(&payload_length, 512),114 _T("PAYLOAD LENGTH"), _T("Length of payload to/from the NSCA agent. This is a hard specific value so you have to \"configure\" (read recompile) your NSCA agent to use the same value for it to work."))115 116 (_T("time offset"), sh::string_key(&delay, "0"),117 _T("TIME OFFSET"), _T("Time offset."))118 ;119 120 81 settings.register_all(); 121 82 settings.notify(); 122 83 84 targets.add_missing(get_settings_proxy(), target_path, _T("default"), _T(""), true); 85 86 123 87 get_core()->registerSubmissionListener(get_id(), channel_); 124 88 125 if (!targets.has_target(_T("default"))) { 126 add_target(_T("default"), _T("default")); 127 targets.rebuild(); 128 } 129 nscapi::target_handler::optarget t = targets.find_target(_T("default")); 130 if (t) { 131 if (!t->has_option("encryption")) 132 t->options[_T("encryption")] = encryption; 133 if (!t->has_option("timeout")) 134 t->options[_T("timeout")] = strEx::itos(timeout); 135 if (!t->has_option("payload length")) 136 t->options[_T("payload length")] = strEx::itos(payload_length); 137 if (!t->has_option("time offset")) 138 t->options[_T("time offset")] = utf8::cvt<std::wstring>(delay); 139 if (!t->has_option("password")) 140 t->options[_T("password")] = password; 141 if (!t->address.empty()) 142 t->address = _T("nsca://") + nscahost + _T(":") + strEx::itos(nscaport); 143 targets.add(*t); 144 } else { 145 NSC_LOG_ERROR(_T("Default target not found!")); 146 } 89 register_command(_T("nsca_query"), _T("Check remote NRPE host")); 90 register_command(_T("nsca_submit"), _T("Submit (via query) remote NRPE host")); 91 register_command(_T("nsca_forward"), _T("Forward query to remote NRPE host")); 92 register_command(_T("nsca_exec"), _T("Execute (via query) remote NRPE host")); 93 register_command(_T("nsca_help"), _T("Help on using NRPE Client")); 94 147 95 148 96 } catch (nscapi::nscapi_exception &e) { … … 159 107 } 160 108 161 std::wstring NSCAAgent::getCryptos() {162 std::wstring ret = _T("{");163 for (int i=0;i<LAST_ENCRYPTION_ID;i++) {164 if (nsca::nsca_encrypt::hasEncryption(i)) {165 std::wstring name;166 try {167 nsca::nsca_encrypt::any_encryption *core = nsca::nsca_encrypt::get_encryption_core(i);168 if (core == NULL)169 name = _T("Broken<NULL>");170 else171 name = utf8::to_unicode(core->getName());172 } catch (nsca::nsca_encrypt::encryption_exception &e) {173 name = utf8::to_unicode(e.what());174 }175 if (ret.size() > 1)176 ret += _T(", ");177 ret += strEx::itos(i) + _T("=") + name;178 }179 }180 return ret + _T("}");181 }182 183 109 std::string get_command(std::string alias, std::string command = "") { 184 110 if (!alias.empty()) … … 193 119 // 194 120 195 void NSCAAgent::add_target(std::wstring key, std::wstring arg) {121 void GraphiteClient::add_target(std::wstring key, std::wstring arg) { 196 122 try { 197 123 targets.add(get_settings_proxy(), target_path , key, arg); 124 } catch (const std::exception &e) { 125 NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key + _T(", ") + utf8::to_unicode(e.what())); 198 126 } catch (...) { 199 127 NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key); … … 201 129 } 202 130 203 void NSCAAgent::add_command(std::wstring name, std::wstring args) {131 void GraphiteClient::add_command(std::wstring name, std::wstring args) { 204 132 try { 205 133 std::wstring key = commands.add_command(name, args); … … 218 146 * @return true if successfully, false if not (if not things might be bad) 219 147 */ 220 bool NSCAAgent::unloadModule() {148 bool GraphiteClient::unloadModule() { 221 149 return true; 222 150 } 223 151 224 NSCAPI::nagiosReturn NSCAAgent::handleRAWCommand(const wchar_t* char_command, const std::string &request, std::string &result) { 225 nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_query_request(char_command, request); 226 std::wstring cmd = client::command_line_parser::parse_command(data.command, _T("syslog")); 152 NSCAPI::nagiosReturn GraphiteClient::handleRAWCommand(const wchar_t* char_command, const std::string &request, std::string &result) { 153 std::wstring cmd = client::command_line_parser::parse_command(char_command, command_prefix); 154 155 Plugin::QueryRequestMessage message; 156 message.ParseFromString(request); 157 227 158 client::configuration config; 228 setup(config );229 if (!client::command_line_parser::is_command(cmd)) 230 return client::command_line_parser::do_execute_command_as_query(config, cmd, data.args, result);231 return commands.exec_simple(config, data.target, char_command, data.args, result); 232 } 233 234 NSCAPI::nagiosReturn NSCAAgent::commandRAWLineExec(const wchar_t* char_command, const std::string &request, std::string &result) { 235 nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_exec_request(char_command, request); 236 std::wstring cmd = client::command_line_parser::parse_command(char_command, _T("syslog"));237 if (!client::command_line_parser::is_command(cmd))238 return NSCAPI::returnIgnored; 159 setup(config, message.header()); 160 161 return commands.process_query(cmd, config, message, result); 162 } 163 164 NSCAPI::nagiosReturn GraphiteClient::commandRAWLineExec(const wchar_t* char_command, const std::string &request, std::string &result) { 165 std::wstring cmd = client::command_line_parser::parse_command(char_command, command_prefix); 166 167 Plugin::ExecuteRequestMessage message; 168 message.ParseFromString(request); 169 239 170 client::configuration config; 240 setup(config); 241 return client::command_line_parser::do_execute_command_as_exec(config, cmd, data.args, result); 242 } 243 244 NSCAPI::nagiosReturn NSCAAgent::handleRAWNotification(const wchar_t* channel, std::string request, std::string &result) { 171 setup(config, message.header()); 172 173 return commands.process_exec(cmd, config, message, result); 174 } 175 176 NSCAPI::nagiosReturn GraphiteClient::handleRAWNotification(const wchar_t* channel, std::string request, std::string &result) { 177 Plugin::SubmitRequestMessage message; 178 message.ParseFromString(request); 179 245 180 client::configuration config; 246 setup(config); 247 return client::command_line_parser::do_relay_submit(config, request, result); 181 setup(config, message.header()); 182 183 return client::command_line_parser::do_relay_submit(config, message, result); 248 184 } 249 185 … … 252 188 // 253 189 254 void NSCAAgent::add_local_options(po::options_description &desc, client::configuration::data_type data) {190 void GraphiteClient::add_local_options(po::options_description &desc, client::configuration::data_type data) { 255 191 desc.add_options() 256 192 ("encryption,e", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "encryption", _1)), … … 271 207 } 272 208 273 void NSCAAgent::setup(client::configuration &config) {274 boost::shared_ptr<clp_handler_impl> handler = boost::shared_ptr<clp_handler_impl>(new clp_handler_impl(this));209 void GraphiteClient::setup(client::configuration &config, const ::Plugin::Common_Header& header) { 210 boost::shared_ptr<clp_handler_impl> handler(new clp_handler_impl(this)); 275 211 add_local_options(config.local, config.data); 276 212 277 net::wurl url; 278 url.protocol = _T("nsca"); 279 url.port = 5667; 280 nscapi::target_handler::optarget opt = targets.find_target(_T("default")); 213 config.data->recipient.id = header.recipient_id(); 214 std::wstring recipient = utf8::cvt<std::wstring>(config.data->recipient.id); 215 if (!targets.has_object(recipient)) { 216 NSC_LOG_ERROR(_T("Target not found (using default): ") + recipient); 217 recipient = _T("default"); 218 } 219 nscapi::targets::optional_target_object opt = targets.find_object(recipient); 220 281 221 if (opt) { 282 nscapi::target_handler::target t = *opt; 283 url.host = t.host; 284 if (t.has_option("port")) { 285 try { 286 url.port = strEx::stoi(t.options[_T("port")]); 287 } catch (...) {} 222 nscapi::targets::target_object t = *opt; 223 nscapi::functions::destination_container def = t.to_destination_container(); 224 config.data->recipient.apply(def); 288 225 } 289 std::string keys[] = {"encryption", "timeout", "payload length", "password", "time offset"};290 BOOST_FOREACH(std::string s, keys) {291 config.data->recipient.data[s] = utf8::cvt<std::string>(t.options[utf8::cvt<std::wstring>(s)]);292 }293 }294 config.data->recipient.id = "default";295 config.data->recipient.address = utf8::cvt<std::string>(url.to_string());296 226 config.data->host_self.id = "self"; 297 config.data->host_self. host = hostname_;227 config.data->host_self.address.host = hostname_; 298 228 299 229 config.target_lookup = handler; … … 301 231 } 302 232 303 NSCAAgent::connection_data NSCAAgent::parse_header(const ::Plugin::Common_Header &header) {233 GraphiteClient::connection_data GraphiteClient::parse_header(const ::Plugin::Common_Header &header, client::configuration::data_type data) { 304 234 nscapi::functions::destination_container recipient, sender; 305 235 nscapi::functions::parse_destination(header, header.recipient_id(), recipient, true); 306 236 nscapi::functions::parse_destination(header, header.sender_id(), sender, true); 307 return connection_data(recipient, sender);237 return connection_data(recipient, data->recipient, sender); 308 238 } 309 239 … … 312 242 // 313 243 314 int NSCAAgent::clp_handler_impl::query(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply) { 315 Plugin::QueryRequestMessage request_message; 316 request_message.ParseFromString(request); 317 connection_data con = parse_header(*header); 244 int GraphiteClient::clp_handler_impl::query(client::configuration::data_type data, const Plugin::QueryRequestMessage &request_message, std::string &reply) { 245 const ::Plugin::Common_Header& request_header = request_message.header(); 246 connection_data con = parse_header(request_header, data); 318 247 319 248 Plugin::QueryResponseMessage response_message; 320 nscapi::functions::make_return_header(response_message.mutable_header(), *header);321 322 std::list< nsca::packet> list;249 nscapi::functions::make_return_header(response_message.mutable_header(), request_header); 250 251 std::list<g_data> list; 323 252 for (int i=0;i < request_message.payload_size(); ++i) { 324 nsca::packet packet(con.sender_hostname, con.buffer_length, con.time_delta); 325 nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_query_request(request_message.payload(i)); 326 packet.code = 0; 327 packet.result = utf8::cvt<std::string>(data.command); 328 list.push_back(packet); 253 g_data d; 254 d.path = "aaa"; 255 d.value = "123"; 256 list.push_back(d); 329 257 } 330 258 … … 336 264 } 337 265 338 int NSCAAgent::clp_handler_impl::submit(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply) { 339 Plugin::SubmitRequestMessage message; 340 message.ParseFromString(request); 341 connection_data con = parse_header(*header); 342 std::wstring channel = utf8::cvt<std::wstring>(message.channel()); 266 int GraphiteClient::clp_handler_impl::submit(client::configuration::data_type data, const Plugin::SubmitRequestMessage &request_message, std::string &reply) { 267 const ::Plugin::Common_Header& request_header = request_message.header(); 268 connection_data con = parse_header(request_header, data); 269 std::wstring channel = utf8::cvt<std::wstring>(request_message.channel()); 343 270 344 271 Plugin::SubmitResponseMessage response_message; 345 nscapi::functions::make_return_header(response_message.mutable_header(), *header); 346 347 std::list<nsca::packet> list; 348 349 for (int i=0;i < message.payload_size(); ++i) { 350 nsca::packet packet(con.sender_hostname, con.buffer_length, con.time_delta); 351 std::wstring alias, msg; 352 packet.code = nscapi::functions::parse_simple_submit_request_payload(message.payload(i), alias, msg); 353 if (alias != _T("host_check")) 354 packet.service = utf8::cvt<std::string>(alias); 355 packet.result = utf8::cvt<std::string>(msg); 356 list.push_back(packet); 272 nscapi::functions::make_return_header(response_message.mutable_header(), request_header); 273 274 std::list<g_data> list; 275 for (int i=0;i < request_message.payload_size(); ++i) { 276 g_data d; 277 d.path = "aaa"; 278 d.value = "123"; 279 list.push_back(d); 357 280 } 358 281 … … 363 286 } 364 287 365 int NSCAAgent::clp_handler_impl::exec(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply) { 366 Plugin::ExecuteRequestMessage request_message; 367 request_message.ParseFromString(request); 368 connection_data con = parse_header(*header); 288 int GraphiteClient::clp_handler_impl::exec(client::configuration::data_type data, const Plugin::ExecuteRequestMessage &request_message, std::string &reply) { 289 const ::Plugin::Common_Header& request_header = request_message.header(); 290 connection_data con = parse_header(request_header, data); 369 291 370 292 Plugin::ExecuteResponseMessage response_message; 371 nscapi::functions::make_return_header(response_message.mutable_header(), *header);372 373 std::list< nsca::packet> list;293 nscapi::functions::make_return_header(response_message.mutable_header(), request_header); 294 295 std::list<g_data> list; 374 296 for (int i=0;i < request_message.payload_size(); ++i) { 375 nsca::packet packet(con.sender_hostname, con.buffer_length, con.time_delta); 376 nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_exec_request_payload(request_message.payload(i)); 377 packet.code = 0; 378 if (data.command != _T("host_check")) 379 packet.service = utf8::cvt<std::string>(data.command); 380 //packet.result = data.; 381 list.push_back(packet); 297 g_data d; 298 d.path = "aaa"; 299 d.value = "123"; 300 list.push_back(d); 382 301 } 383 302 boost::tuple<int,std::wstring> ret = instance->send(con, list); … … 391 310 // 392 311 393 boost::tuple<int,std::wstring> NSCAAgent::send(connection_data data, const std::list<nsca::packet> packets) {312 boost::tuple<int,std::wstring> GraphiteClient::send(connection_data data, const std::list<g_data> payload) { 394 313 try { 395 314 NSC_DEBUG_MSG_STD(_T("Connection details: ") + data.to_wstring()); 315 396 316 boost::asio::io_service io_service; 397 nsca::socket socket(io_service); 398 socket.connect(data.host, data.port); 399 if (!socket.recv_iv(data.password, data.get_encryption(), boost::posix_time::seconds(data.timeout<5?30:data.timeout))) { 400 NSC_LOG_ERROR_STD(_T("Failed to read iv")); 401 return NSCAPI::hasFailed; 317 boost::asio::ip::tcp::resolver resolver(io_service); 318 boost::asio::ip::tcp::resolver::query query(data.host, data.port); 319 boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); 320 boost::asio::ip::tcp::resolver::iterator end; 321 322 boost::asio::ip::tcp::socket socket(io_service); 323 boost::system::error_code error = boost::asio::error::host_not_found; 324 while(error && endpoint_iterator != end) { 325 socket.close(); 326 socket.connect(*endpoint_iterator++, error); 402 327 } 403 NSC_DEBUG_MSG_STD(_T("Got IV sending data: ") + strEx::itos(packets.size())); 404 BOOST_FOREACH(const nsca::packet &packet, packets) { 405 NSC_DEBUG_MSG_STD(_T("Sending: ") + utf8::cvt<std::wstring>(packet.to_string())); 406 socket.send_nsca(packet, boost::posix_time::seconds(data.timeout)); 328 if(error) 329 throw boost::system::system_error(error); 330 331 boost::posix_time::ptime time_t_epoch(boost::gregorian::date(1970,1,1)); 332 boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); 333 boost::posix_time::time_duration diff = now - time_t_epoch; 334 int x = diff.total_milliseconds(); 335 336 BOOST_FOREACH(const g_data &d, payload) { 337 std::string msg = d.path + " " +d.value + " " + boost::lexical_cast<std::string>(x) + "\n"; 338 NSC_DEBUG_MSG_STD(_T("Sending: ") + utf8::cvt<std::wstring>(msg)); 339 socket.send(boost::asio::buffer(msg)); 407 340 } 341 //socket.shutdown(); 408 342 return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("")); 409 } catch (nsca::nsca_encrypt::encryption_exception &e) { 410 NSC_LOG_ERROR_STD(_T("NSCA Error: ") + utf8::to_unicode(e.what())); 411 return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("NSCA error: ") + utf8::to_unicode(e.what())); 412 } catch (std::runtime_error &e) { 343 } catch (const std::runtime_error &e) { 413 344 NSC_LOG_ERROR_STD(_T("Socket error: ") + utf8::to_unicode(e.what())); 414 345 return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Socket error: ") + utf8::to_unicode(e.what())); 415 } catch ( std::exception &e) {346 } catch (const std::exception &e) { 416 347 NSC_LOG_ERROR_STD(_T("Error: ") + utf8::to_unicode(e.what())); 417 348 return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Error: ") + utf8::to_unicode(e.what())); 418 349 } catch (...) { 350 NSC_LOG_ERROR_STD(_T("Unknown exception when sending NSCA data: ")); 419 351 return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Unknown error -- REPORT THIS!")); 420 352 } … … 422 354 423 355 NSC_WRAP_DLL(); 424 NSC_WRAPPERS_MAIN_DEF( NSCAAgent);356 NSC_WRAPPERS_MAIN_DEF(GraphiteClient); 425 357 NSC_WRAPPERS_IGNORE_MSG_DEF(); 426 358 NSC_WRAPPERS_HANDLE_CMD_DEF(); -
modules/GraphiteClient/GraphiteClient.def
r330af36 r74e060a 1 LIBRARY NSCAClient1 LIBRARY GraphiteClient 2 2 3 3 EXPORTS -
modules/GraphiteClient/GraphiteClient.h
r330af36 r74e060a 25 25 #include <client/command_line_parser.hpp> 26 26 #include <nscapi/targets.hpp> 27 28 #include <nsca/nsca_packet.hpp> 27 #include <nscapi/nscapi_protobuf_types.hpp> 29 28 30 29 NSC_WRAPPERS_MAIN(); … … 33 32 34 33 namespace po = boost::program_options; 35 36 class NSCAAgent : public nscapi::impl::simple_plugin { 34 namespace sh = nscapi::settings_helper; 35 36 class GraphiteClient : public nscapi::impl::simple_plugin { 37 37 private: 38 38 39 39 std::wstring channel_; 40 40 std::wstring target_path; 41 const static std::wstring command_prefix; 41 42 std::string hostname_; 42 43 bool cacheNscaHost_; 43 44 long time_delta_; 44 45 45 nscapi::target_handler targets; 46 struct g_data { 47 std::string path; 48 std::string value; 49 }; 50 51 struct custom_reader { 52 typedef nscapi::targets::target_object object_type; 53 typedef nscapi::targets::target_object target_object; 54 55 static void init_default(target_object &target) { 56 target.set_property_int(_T("timeout"), 30); 57 target.set_property_string(_T("encryption"), _T("ase")); 58 target.set_property_int(_T("payload length"), 512); 59 } 60 61 static void add_custom_keys(sh::settings_registry &settings, boost::shared_ptr<nscapi::settings_proxy> proxy, object_type &object) { 62 settings.path(object.path).add_key() 63 64 (_T("timeout"), sh::int_fun_key<int>(boost::bind(&object_type::set_property_int, &object, _T("timeout"), _1), 30), 65 _T("TIMEOUT"), _T("Timeout when reading/writing packets to/from sockets.")) 66 67 (_T("payload length"), sh::int_fun_key<int>(boost::bind(&object_type::set_property_int, &object, _T("payload length"), _1), 512), 68 _T("PAYLOAD LENGTH"), _T("Length of payload to/from the NRPE agent. This is a hard specific value so you have to \"configure\" (read recompile) your NRPE agent to use the same value for it to work.")) 69 70 (_T("encryption"), sh::string_fun_key<std::wstring>(boost::bind(&object_type::set_property_string, &object, _T("encryption"), _1), _T("aes")), 71 _T("ENCRYPTION METHOD"), _T("Number corresponding to the various encryption algorithms (see the wiki). Has to be the same as the server or it wont work at all.")) 72 73 (_T("password"), sh::string_fun_key<std::wstring>(boost::bind(&object_type::set_property_string, &object, _T("password"), _1), _T("")), 74 _T("PASSWORD"), _T("The password to use. Again has to be the same as the server or it wont work at all.")) 75 76 (_T("time offset"), sh::string_fun_key<std::wstring>(boost::bind(&object_type::set_property_string, &object, _T("delay"), _1), _T("0")), 77 _T("TIME OFFSET"), _T("Time offset.")) 78 ; 79 } 80 static void post_process_target(target_object &target) { 81 } 82 }; 83 84 nscapi::targets::handler<custom_reader> targets; 46 85 client::command_manager commands; 47 86 … … 55 94 int time_delta; 56 95 57 connection_data(nscapi::functions::destination_container recipient, nscapi::functions::destination_container sender) { 96 connection_data(nscapi::protobuf::types::destination_container recipient, nscapi::protobuf::types::destination_container target, nscapi::protobuf::types::destination_container sender) { 97 recipient.import(target); 58 98 timeout = recipient.get_int_data("timeout", 30); 59 99 buffer_length = recipient.get_int_data("payload length", 512); 60 100 password = recipient.get_string_data("password"); 61 101 encryption = recipient.get_string_data("encryption"); 102 std::string tmp = recipient.get_string_data("time offset"); 103 if (!tmp.empty()) 62 104 time_delta = strEx::stol_as_time_sec(recipient.get_string_data("time offset")); 63 net::url url = recipient.get_url(5667); 64 host = url.host; 65 port = url.get_port(); 105 else 106 time_delta = 0; 107 host = recipient.address.get_host(); 108 port = strEx::s::itos(recipient.address.get_port(5667)); 109 sender_hostname = sender.address.host; 110 if (sender.has_data("host")) 66 111 sender_hostname = sender.get_string_data("host"); 67 }68 unsigned int get_encryption() {69 return nsca::nsca_encrypt::helpers::encryption_to_int(encryption);70 112 } 71 113 … … 85 127 struct clp_handler_impl : public client::clp_handler, client::target_lookup_interface { 86 128 87 NSCAAgent *instance; 88 clp_handler_impl(NSCAAgent *instance) : instance(instance) {} 89 90 int query(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply); 91 int submit(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply); 92 int exec(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply); 93 94 virtual nscapi::functions::destination_container lookup_target(std::wstring &id) { 95 nscapi::functions::destination_container ret; 96 nscapi::target_handler::optarget t = instance->targets.find_target(id); 97 if (t) { 98 if (!t->alias.empty()) 99 ret.id = utf8::cvt<std::string>(t->alias); 100 if (!t->host.empty()) 101 ret.host = utf8::cvt<std::string>(t->host); 102 if (t->has_option("address")) 103 ret.address = utf8::cvt<std::string>(t->options[_T("address")]); 104 else 105 ret.address = utf8::cvt<std::string>(t->host); 106 BOOST_FOREACH(const nscapi::target_handler::target::options_type::value_type &kvp, t->options) { 107 ret.data[utf8::cvt<std::string>(kvp.first)] = utf8::cvt<std::string>(kvp.second); 108 } 109 } 129 GraphiteClient *instance; 130 clp_handler_impl(GraphiteClient *instance) : instance(instance) {} 131 132 int query(client::configuration::data_type data, const Plugin::QueryRequestMessage &request_message, std::string &reply); 133 int submit(client::configuration::data_type data, const Plugin::SubmitRequestMessage &request_message, std::string &reply); 134 int exec(client::configuration::data_type data, const Plugin::ExecuteRequestMessage &request_message, std::string &reply); 135 136 virtual nscapi::protobuf::types::destination_container lookup_target(std::wstring &id) { 137 nscapi::targets::optional_target_object opt = instance->targets.find_object(id); 138 if (opt) 139 return opt->to_destination_container(); 140 nscapi::protobuf::types::destination_container ret; 110 141 return ret; 111 142 } … … 114 145 115 146 public: 116 NSCAAgent();117 virtual ~ NSCAAgent();147 GraphiteClient(); 148 virtual ~GraphiteClient(); 118 149 // Module calls 119 150 bool loadModule(); … … 141 172 } 142 173 static std::wstring getModuleDescription() { 143 return std::wstring(_T(" Passive check support (needs NSCA on nagios server).\nAvalible crypto are: ")) + getCryptos();174 return std::wstring(_T("Graphite client")); 144 175 } 145 176 … … 152 183 153 184 private: 154 boost::tuple<int,std::wstring> send(connection_data data, const std::list< nsca::packet> packets);185 boost::tuple<int,std::wstring> send(connection_data data, const std::list<g_data> payload); 155 186 void add_options(po::options_description &desc, connection_data &command_data); 156 static connection_data parse_header(const ::Plugin::Common_Header &header );187 static connection_data parse_header(const ::Plugin::Common_Header &header, client::configuration::data_type data); 157 188 158 189 private: 159 190 void add_local_options(po::options_description &desc, client::configuration::data_type data); 160 void setup(client::configuration &config );191 void setup(client::configuration &config, const ::Plugin::Common_Header& header); 161 192 void add_command(std::wstring key, std::wstring args); 162 193 void add_target(std::wstring key, std::wstring args); -
modules/GraphiteClient/module.cmake
ra87ce04 r74e060a 1 SET (BUILD_MODULE 0)1 SET (BUILD_MODULE 1) 2 2 3 3 -
scripts/python/test_eventlog.py
r72eea1f r74e060a 17 17 last_perfdata = None 18 18 got_simple_response = None 19 message_count = 0 19 20 20 21 class SingletonHelper: … … 51 52 self.last_status = status 52 53 self.last_message = message 54 self.message_count = self.message_count + 1 53 55 self.last_perfdata = perf 54 56 return True … … 57 59 None 58 60 59 def test_create(self, source, id, severity, category, arguments):61 def test_create(self, source, id, level, severity, category, facility, arguments): 60 62 self.last_message = None 63 self.message_count = 0 61 64 args = ['--source', source, 62 65 '--id', id, 66 '--level', level, 63 67 '--severity', severity, 64 '--category', category 68 '--category', category, 69 '--facility', facility 65 70 ] 66 71 for f in arguments: … … 69 74 (ret, msg) = Core.get().simple_exec('any', 'insert-eventlog', args) 70 75 return ret == 0 76 77 78 def test_w_expected(self, filter, syntax, expected): 79 result = TestResult('Validating filter: %s'%filter) 80 (res, msg, perf) = Core.get().simple_query('CheckEventLog', ['file=Application', 'debug=true', 'warn=ne:%d'%expected, 'crit=ne:%d'%expected, 'filter=%s'%filter, 'syntax=%s'%syntax]) 81 result.assert_equals(res, status.OK, "Validate status OK for %s"%filter) 82 (res, msg, perf) = Core.get().simple_query('CheckEventLog', ['file=Application', 'debug=true', 'warn=eq:%d'%expected, 'crit=ne:%d'%expected, 'filter=%s'%filter, 'syntax=%s'%syntax]) 83 result.assert_equals(res, status.WARNING, "Validate status OK for %s"%filter) 84 (res, msg, perf) = Core.get().simple_query('CheckEventLog', ['file=Application', 'debug=true', 'warn=eq:%d'%expected, 'crit=eq:%d'%expected, 'filter=%s'%filter, 'syntax=%s'%syntax]) 85 result.assert_equals(res, status.CRITICAL, "Validate status CRIT for %s"%filter) 86 return result 71 87 88 def test_syntax(self, filter, syntax, expected): 89 result = TestResult('Validating syntax: %s'%syntax) 90 (res, msg, perf) = Core.get().simple_query('CheckEventLog', ['file=Application', 'warn=ne:1', 'filter=%s'%filter, 'syntax=%s'%syntax, 'descriptions']) 91 result.assert_equals(msg, expected, "Validate message rendering syntax: %s"%msg) 92 return result 93 72 94 def run_test(self): 73 result = TestResult() 74 result.add_message(self.test_create('Application Error', 1000, '0', 'error', ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']), 'Testing to create a log message') 95 result = TestResult('Checking CheckEventLog') 96 cache = TestResult('Checking CheckEventLog CACHE') 97 98 (res, msg, perf) = Core.get().simple_query('CheckEventLogCACHE', ['warn=eq:1', 'crit=eq:2']) 99 cache.assert_equals(res, status.OK, "Validate cache is empty") 100 cache.assert_equals(msg, 'Eventlog check ok', "Validate cache is ok: %s"%msg) 101 102 103 a_list = ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] 104 result.add_message(self.test_create('Application Error', 1000, 'error', 0, 0, 0, a_list), 'Testing to create a log message') 75 105 sleep(500) 76 log(self.last_message)77 log('%s'%self.last_message)78 106 result.assert_equals(self.last_message, 'error Application Error: ', 'Verify that message is sent through') 107 result.assert_equals(self.message_count, 1, 'Verify that onlyt one message is sent through') 108 109 result.add_message(self.test_create('Application Error', 1000, 'info', 2, 1, 5, a_list), 'Testing to create a log message') 110 sleep(500) 111 result.assert_equals(self.last_message, 'info Application Error: ', 'Verify that message is sent through') 112 result.assert_equals(self.message_count, 1, 'Verify that onlyt one message is sent through') 113 114 (res, msg, perf) = Core.get().simple_query('CheckEventLogCACHE', ['warn=eq:1', 'crit=eq:2']) 115 cache.assert_equals(res, status.CRITICAL, "Validate cache has items") 116 cache.assert_equals(msg, 'error Application Error: , info Application Error: , eventlog: 2 = critical', "Validate cache is ok: %s"%msg) 117 cache.assert_equals(perf, "'eventlog'=2;1;2", "Validate cache is ok: %s"%msg) 118 (res, msg, perf) = Core.get().simple_query('CheckEventLogCACHE', ['warn=eq:1', 'crit=eq:2']) 119 cache.assert_equals(res, status.OK, "Validate cache is empty (again)") 120 cache.assert_equals(msg, 'Eventlog check ok', "Validate cache is ok: %s"%msg) 79 121 80 (res, msg, perf) = Core.get().simple_query('CheckEventLog', ['file=Application', 'debug=true', 'warn=gt:1', 'filter=generated gt -2h', 'syntax=:%computer%:, %source%', 'descriptions']) 81 log('===>> %s <==='%msg) 82 result.add_message(self.test_create('Application Error', 1000, '0', 'error', ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']), 'Testing to create a log message') 122 result.add(cache) 83 123 124 r = TestResult('Checking filters') 125 r.add(self.test_w_expected('id = 1000 and generated gt 1m', '%generated%', 0)) 126 r.add(self.test_w_expected('id = 1000 and generated gt -1m', '%generated%', 2)) 127 r.add(self.test_w_expected('id = 1000 and generated gt -1m and id = 1000', '%generated%: %id%, %category%', 2)) 128 r.add(self.test_w_expected('id = 1000 and generated gt -1m and category = 1', '%category%', 1)) 129 r.add(self.test_w_expected('id = 1000 and generated gt -1m and category = 0', '%category%', 1)) 130 r.add(self.test_w_expected("id = 1000 and generated gt -1m and level = 'error'", '%level%', 1)) 131 r.add(self.test_w_expected("id = 1000 and generated gt -1m and level = 'info'", '%level%', 1)) 132 result.add(r) 133 134 r = TestResult('Checking syntax') 135 r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 0', '%source% - %type% - %category%', 'Application Error - error - 0')) 136 r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 1', '%source% - %type% - %category%', 'Application Error - info - 1')) 137 r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 0', '%facility% - %qualifier% - %customer%', '0 - 0 - 0')) 138 r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 1', '%facility% - %qualifier% - %customer%', '5 - 5 - 0')) 139 r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 0', '%rawid% - %severity% - %log%', '1000 - success - Application')) 140 r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 1', '%rawid% - %severity% - %log%', '2147812328 - warning - Application')) 141 r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 0', '%id% - %strings%', '1000 - a, a, a, a, a, a, a, a, a, a, a, a, a, ')) 142 r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 1', '%id% - %strings%', '1000 - a, a, a, a, a, a, a, a, a, a, a, a, a, ')) 143 result.add(r) 144 84 145 return result 85 146 … … 92 153 93 154 conf.set_string('/settings/pytest_eventlog/real-time', 'enabled', 'true') 94 #conf.set_string('/settings/pytest_eventlog/real-time', 'filter', 'generated gt -2h') 155 conf.set_string('/settings/pytest_eventlog/real-time', 'filter', 'id = 1000 and category = 0') 156 conf.set_string('/settings/pytest_eventlog/real-time/filters', 'test', 'id = 1000 and category = 1') 95 157 conf.set_string('/settings/pytest_eventlog/real-time', 'maximum age', '5s') 96 158 conf.set_string('/settings/pytest_eventlog/real-time', 'destination', 'pytest_evlog') 97 159 conf.set_string('/settings/pytest_eventlog/real-time', 'language', 'english') 160 conf.set_string('/settings/pytest_eventlog/real-time', 'debug', 'true') 161 conf.set_string('/settings/pytest_eventlog/real-time', 'enable active', 'true') 98 162 99 163 conf.save() -
version.hpp
ree52cdd r74e060a 1 1 #ifndef VERSION_HPP 2 2 #define VERSION_HPP 3 #define PRODUCTVER 0,4,0,14 04 #define STRPRODUCTVER "0,4,0,14 0"5 #define STRPRODUCTDATE "2012-0 2-22"3 #define PRODUCTVER 0,4,0,145 4 #define STRPRODUCTVER "0,4,0,145" 5 #define STRPRODUCTDATE "2012-03-18" 6 6 #endif // VERSION_HPP -
version.txt
r84cdb9b r74e060a 1 1 version=0.4.0 2 build=14 03 date=2012-0 2-222 build=145 3 date=2012-03-18
Note: See TracChangeset
for help on using the changeset viewer.








