Compare commits

...

37 Commits

Author SHA1 Message Date
Denis Knauf 56045ae80d usage 2015-07-03 15:45:45 +02:00
Denis Knauf cf6610318c file-linking-test 2015-07-03 15:43:08 +02:00
Denis Knauf 511ae1e9eb file-linking-test 2015-07-03 15:42:26 +02:00
Denis Knauf a13080c8fe file-linking-test 2015-07-03 15:40:46 +02:00
Denis Knauf 270df6c90f file-linking-test 2015-07-03 15:40:24 +02:00
Denis Knauf e230f74bcd copyright & homepage 2015-07-03 15:36:20 +02:00
Denis Knauf 11d0f09c6d random padding bytes for strings 2015-07-03 15:35:20 +02:00
Denis Knauf a2b6bde057 compatibility to nsca-2.9 (NSCA::Packet3__2_9) 2015-07-03 15:26:42 +02:00
Denis Knauf 8249577e7a perfdata-labels: quote. 2013-04-24 16:55:46 +02:00
Denis Knauf 9ac69477a0 Regenerate gemspec for version 0.2.1 2013-04-24 16:26:18 +02:00
Denis Knauf 161e6739e5 Version bump to 0.2.1 2013-04-24 16:26:14 +02:00
Denis Knauf ee60209b3c checks: @perfdatas should user symbols as keys. +test 2013-04-24 16:26:02 +02:00
Denis Knauf f7b6f4d63b Regenerate gemspec for version 0.2.0 2013-04-11 14:25:43 +02:00
Denis Knauf 51d465872d Version bump to 0.2.0 2013-04-11 14:25:37 +02:00
Denis Knauf 8b0f1f9015 check: text can be generated, also if no return_code given (retcode will be used). hostname-call must be chompd. tests 2013-04-11 14:23:32 +02:00
Denis Knauf 4b8cc9eef8 measure only time units (s, ms) and if ms, value must be in ms. 2013-04-10 18:21:01 +02:00
Denis Knauf fccfe5a1d5 perfdata::base#to_sym: use to_sym of class. 2013-04-10 17:48:46 +02:00
Denis Knauf 13172b5cbe Check/Perfdata: to_a, to_sym, to_h, clone. some new tests. 2013-04-10 17:32:19 +02:00
Denis Knauf eff34860cf Perfdata.measure: copy and paste error removed. 2013-04-10 15:29:42 +02:00
Denis Knauf 541cb69a92 Perfdata.measure: copy and paste error removed. 2013-04-10 15:27:15 +02:00
Denis Knauf d676b83138 perfdata_for: perfdata_label -> label 2013-04-09 21:13:05 +02:00
Denis Knauf 21031daf8e perfdata_for: type: value -> label 2013-04-09 21:05:37 +02:00
Denis Knauf 27d4db6782 perfdata_for label. Perfdata::Base.to_sym 2013-04-09 21:02:17 +02:00
Denis Knauf 96a58c12dd check: accessor return_code, status, timestamp 2013-04-09 16:41:56 +02:00
Denis Knauf 9f84e5f38d Regenerate gemspec for version 0.1.4 2013-04-09 16:20:36 +02:00
Denis Knauf 3fefa4854f Version bump to 0.1.4 2013-04-09 16:20:32 +02:00
Denis Knauf 98bf84261d tests changed (checks) 2013-04-09 16:19:13 +02:00
Denis Knauf e53c648263 checks: meaning of create and new changed (like performance data) 2013-04-09 16:15:47 +02:00
Denis Knauf ab1eeda1eb Regenerate gemspec for version 0.1.3 2013-04-09 15:57:27 +02:00
Denis Knauf 66860abae5 Version bump to 0.1.3 2013-04-09 15:57:19 +02:00
Denis Knauf 4a1336efc8 Rakefile had have wrong license. now correct lgpl-3. MIT was wrong! 2013-04-09 15:57:08 +02:00
Denis Knauf 9f19471434 Regenerate gemspec for version 0.1.2 2013-04-09 15:33:32 +02:00
Denis Knauf 1a25705641 Version bump to 0.1.2 2013-04-09 15:33:28 +02:00
Denis Knauf 0480986133 checks: no auto-const-set (was unclean), cl-parameter removed. 2013-04-09 15:33:22 +02:00
Denis Knauf 7832b62b51 Regenerate gemspec for version 0.1.1 2013-04-09 12:23:16 +02:00
Denis Knauf 311b80516b Version bump to 0.1.1 2013-04-09 12:22:34 +02:00
Denis Knauf aeaabffc40 check: perfdata-labels are symbols. perfdata works. 2013-04-09 12:20:55 +02:00
10 changed files with 420 additions and 151 deletions

View File

@ -8,7 +8,17 @@ This is a ruby-pure implementation.
First it was planed to provide a client-API, but now there is also a full server-API.
Tested against nsca-2.7.
Tested against nsca-2.7, -2.9.
Usage
=====
Simple sending
```ruby
NSCA.destinations << NSCA::Client.new('localhost')
NSCA.send 'serverA', 'serviceA', 1, 'Ok'
```
TO DO AND DONE
==============
@ -16,7 +26,6 @@ TO DO AND DONE
TODO
----
* build packet with performance data
* server side parsing of performance data
* more documentations
* mcrypt-support
@ -30,9 +39,9 @@ DONE
* server-API (recv from client)
* check-API (describe checks and performance data)
* fast usable API for sending checks
* build packet with performance data
Copyright
=========
Copyright (c) 2013 Denis Knauf. See LICENSE.txt for
further details.
Copyright (c) 2013-2015 Denis Knauf. See [LICENSE.txt](LICENSE.txt) for further details.

View File

@ -15,8 +15,8 @@ require 'jeweler'
Jeweler::Tasks.new do |gem|
# gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
gem.name = "nsca"
gem.homepage = "http://github.com/DenisKnauf/nsca"
gem.license = "MIT"
gem.homepage = "http://github.com/DenisKnauf/ruby-nsca"
gem.license = "LGPL-3"
gem.summary = %Q{Nagios passive alerts with friendly API}
gem.description = %Q{Create your alerts easily and send it to Nagios}
gem.email = "Denis.Knauf@gmail.com"

View File

@ -1 +1 @@
0.1.0
0.2.1

View File

@ -18,6 +18,35 @@ module NSCA
clname[0] = clname[0].upcase
clname.to_sym
end
def xor_stream key
key = case key
when Array then key
when String then key.bytes.to_a
when Enumerable then key.to_a
end
return lambda{|x|x} if [nil, '', []].include? key
length = key.length
i = 0
lambda do |str|
r = ''
str.bytes.each_with_index do |c, j|
r[j] = (c ^ key[i]).chr
i = (i + 1) % length
end
r
end
end
def crc32_stream
sum = 0xFFFFFFFF
lambda do |str|
sum = str.bytes.inject sum do |r, b|
8.times.inject( r^b) {|r,_i| (r>>1) ^ (0xEDB88320 * (r&1)) }
end if str
sum ^ 0xFFFFFFFF
end
end
end
end
@ -28,6 +57,30 @@ module NSCA
NSCA.destinations.each {|server| server.send *results }
self
end
def xor key, msg = nil, key_a = nil
NSCA::Helper.xor_stream( key_a || key)[ msg]
end
def crc32 msg
NSCA::Helper.crc32_stream[ msg]
end
# Builds a null terminated, null padded string of length maxlen
def str2cstr str, maxlen = nil
str = str.to_s
str = str.to_s[0..(maxlen-2)] if maxlen
"#{str}\x00"
end
def rand_padding( str, maxlen) str + SecureRandom.random_bytes( maxlen - str.length) end
def str2cstr_rand_padding( str, maxlen = nil) rand_padding str2cstr( str, maxlen), maxlen end
def str2nstr str, maxlen = nil
str = str.to_s.gsub ' ', "\x00"
"#{str} "
end
def str2nstr_rand_padding( str, maxlen = nil) rand_padding str2nstr( str, maxlen), maxlen end
def cstr2str( str, maxlen = nil) str[ 0, str.index( ?\0) || ((maxlen||str.length+1)-1)] end
def nstr2str( str, maxlen = nil) str[ 0, str.index( ' ') || ((maxlen||str.length+1)-1)].gsub( "\x00", ' ') end
end
end

View File

@ -1,29 +1,45 @@
module NSCA
module PerformanceData
class TimeUnitExpected < Exception
end
class Base
extend Timeout
extend Benchmark
class <<self
attr_reader :label, :unit, :warn, :crit, :min, :max
def init label, unit = nil, warn = nil, crit = nil, min = nil, max = nil
@label, @unit, @warn, @crit, @min, @max = label.to_s, unit, warn, crit, min, max
def init *args
a, o = args, args.last.is_a?( Hash) ? args.pop : {}
@label, @unit = a[0]||o[:label], a[1]||o[:unit]
@warn, @crit = a[2]||o[:warn], a[3]||o[:crit]
@min, @max = a[4]||o[:min], a[5]||o[:max]
raise ArgumentError, "Label expected" unless @label
@label = @label.to_s
self
end
def measure &block
timeout ||= 0
exception = Class.new Timeout::Error
pd = perfdatas[perfdata_label]
timeout = pd.max
f = case unit.to_s.to_sym
when :s then 1
when :ms then 1000
else raise TimeUnitExpected, "Unit must be seconds (s) or miliseconds (ms) not (#{unit})"
end
exception = ::Class.new Timeout::Error
timeout = max
m = realtime do
begin
timeout timeout, exception, &block
rescue exception
end
end
new m
new f * m
end
def to_sym() label.to_sym end
def to_h() {label: @label, unit: @unit, warn: @warn, crit: @crit, min: @min, max: @max } end
def to_a() [label, unit, warn, crit, min, max] end
def clone( opts = nil) ::Class.new( self).init opts ? to_h.merge( opts) : to_h end
end
attr_reader :value
@ -34,7 +50,13 @@ module NSCA
def crit() self.class.crit end
def min() self.class.min end
def max() self.class.max end
def to_s() "#{label}=#{value}#{unit},#{warn},#{crit},#{min},#{max}" end
def to_a() [label, value, unit, warn, crit, min, max] end
def to_s() "'#{label.gsub /[\n'\|]/, ''}'=#{value}#{unit},#{warn},#{crit},#{min},#{max}" end
def to_sym() self.class.to_sym end
def to_h
{label: @label, value: @value, unit: @unit, warn: @warn, crit: @crit, min: @min, max: @max}
end
def return_code
if @value.nil? then 3
@ -46,13 +68,9 @@ module NSCA
end
class <<self
def new label, unit = nil, warn = nil, crit = nil, min = nil, max = nil
cl = Class.new Base
cl.init label, unit, warn, crit, min, max
end
def create label, unit = nil, warn = nil, crit = nil, min = nil, max = nil
cl = new label, unit, warn, crit, min, max
def new( *args) ::Class.new( Base).init *args end
def create label, *args
cl = new label, *args
clname = NSCA::Helper.class_name_gen label
self.const_set clname, cl if clname
cl
@ -62,8 +80,10 @@ module NSCA
module Check
class Base
attr_reader :perfdatas, :return_code, :status, :timestamp
def initialize return_code = nil, status = nil, perfdatas = nil
attr_accessor :return_code, :status, :timestamp
attr_reader :perfdatas
def initialize return_code = nil, status = nil, perfdatas = nil, timestamp = nil
@perfdatas = {}
init return_code, status, perfdatas, timestamp || Time.now
end
@ -71,61 +91,63 @@ module NSCA
def init return_code = nil, status = nil, perfdatas = nil, timestamp = nil
@return_code = return_code if return_code
@status = status if status
perfdatas.each &method( :[]) if perfdatas
case perfdatas
when Hash
perfdatas.each &method( :[])
when Array
push *perfdatas
end
@timestamp = timestamp if timestamp
self
end
def [] perfdata_label
pd = @perfdatas[perfdata_label]
pd = @perfdatas[perfdata_label.to_sym]
pd && pd.value
end
def push *perfdatas
perfdatas.each {|perfdata| @perfdatas[perfdata.label.to_sym] = perfdata }
@perfdatas
end
def perfdata_for label
if label.is_a? PerformanceData::Base
label
else
label = label.to_sym
self.class.perfdatas[label] || PerformanceData::Base.new( label)
end
end
def []= perfdata_label, value
cl = self.class.perfdatas[perfdata_label]
cl ||= PerformanceData::Base.new perfdata_label
@perfdatas[perfdata_label] = cl.new value
return push value if value.is_a? PerformanceData::Base
perfdata_label = perfdata_label.to_sym
@perfdatas[perfdata_label] = perfdata_for( perfdata_label).new value
end
def text
r = "#{status || ReturnCode.find(return_code)}"
r += " | #{perfdatas.map( &:to_s).join ' '}" unless perfdatas.empty?
r = "#{status || ReturnCode.find(retcode)}"
r += " | #{perfdatas.each_value.map( &:to_s).join ' '}" unless perfdatas.empty?
r
end
def measure( perfdata_label, &block) @perfdatas[perfdata_label].measure &block end
def measure perfdata_label, &block
push perfdata_for( perfdata_label).measure( &block)
end
def send() NSCA::send self end
def ok status = nil, perfdatas = nil
init ReturnCode::OK, status, perfdatas
send
end
def warning status = nil, perfdatas = nil
init ReturnCode::WARNING, status, perfdatas
send
end
def ok( *args) init ReturnCode::OK, *args end
def warning( *args) init ReturnCode::WARNING, *args end
alias warn warning
def critical status = nil, perfdatas = nil
init ReturnCode::CRITICAL, status, perfdatas
send
end
def critical( *args) init ReturnCode::CRITICAL, *args end
alias crit critical
def unknown status = nil, perfdatas = nil
init ReturnCode::UNKNOWN, status, perfdatas
send
end
def unknown( *args) init ReturnCode::UNKNOWN, *args end
def determine_return_code
self.class.perfdatas.map do |label, pdc|
pd = @perfdatas[label]
if pd
pd.return_code
else
-1
end
pd ? pd.return_code : -1
end.max
end
@ -136,12 +158,24 @@ module NSCA
def service() self.class.service end
def hostname() self.class.hostname end
def to_a() [timestamp, retcode, hostname, service, text] end
def to_h
{timestamp: timestamp, return_code: retcode, hostname: hostname, server: service, status: text}
end
def to_packet version = nil
version ||= PacketV3
version.new timestamp, retcode, hostname, service, text
end
class <<self
attr_reader :service, :hostname, :perfdatas
def init service, hostname = nil, perfdatas = nil
@service, @hostname, @perfdatas = service, hostname || `hostname -f`, {}
perfdatas.each {|pd| @perfdatas[pd.label] = pd }
def init *args
a, o = args, args.last.is_a?( Hash) ? args.pop : {}
service, hostname = nil, perfdatas = nil
@service, @hostname, @perfdatas = a[0]||o[:service], a[1]||o[:hostname]||`hostname`.chomp, {}
perfdatas = a[2]||o[:perfdatas]
perfdatas.each {|pd| @perfdatas[pd.to_sym] = pd } if perfdatas
self
end
@ -151,18 +185,23 @@ module NSCA
def critical( status = nil, perfdatas = nil) new.warning status, perfdatas end
alias crit critical
def unknown( status = nil, perfdatas = nil) new.unknown status, perfdatas end
def to_a() [service, hostname, perfdatas.dup] end
def to_h() {service: service, hostname: hostname, perfdatas: perfdatas.values} end
def to_sym() "#{hostname}|#{service}".to_sym end
def clone( opts = nil) ::Class.new( self).init opts ? to_h.merge( opts) : to_h end
end
end
class <<self
def create service, hostname = nil, perfdatas = nil
def new service, hostname = nil, perfdatas = nil
cl = Class.new Base
cl.init service, hostname, perfdatas
cl
end
def new service, hostname = nil, perfdatas = nil
cl = create service, hostname, perfdatas
def create service, hostname = nil, perfdatas = nil
cl = new service, hostname, perfdatas
clname = NSCA::Helper.class_name_gen service.to_s
self.const_set clname, cl if clname
cl
@ -171,12 +210,12 @@ module NSCA
end
module Checks
def perfdata( cl, *params) const_set cl, NSCA::PerformanceData.new( *params) end
def perfdata( *params) NSCA::PerformanceData.new( *params) end
def check cl, service, hostname, perfdatas = nil
def check service, hostname, perfdatas = nil
perfdatas ||= []
perfdatas.map! {|cl| cl.is_a?( Symbol) ? const_get( cl) : cl }
const_set cl, NSCA::Check.new( service, hostname, perfdatas)
NSCA::Check.new service, hostname, perfdatas
end
end
end

View File

@ -61,19 +61,26 @@ module NSCA
# @param [String(length<512)] status Status-line inclusive optional Performance Data.
def build_packet timestamp, return_code, hostname, service, status
packet = @packet_version.new timestamp || @timestamp, return_code, hostname, service, status
packet.build @iv_key, @password
packet.build
end
# Sends a check-result.
# @see #build_packet
def send_packet( *a) @socket.write build_packet( *a) end
def send_packet( *a)
packet = case a.first
when NSCA::Packet then a.first.build
when NSCA::Check::Base then a.first.to_packet( @packet_version).build
else build_packet( *a)
end
packet = NSCA::xor @iv_key, packet
packet = NSCA::xor @password, packet
@socket.write packet
end
# Sends check-results
# @param [Array<NSCA::Check::Base>] results
def send *results
results.flatten.each do |r|
send_packet r.timestamp, r.retcode, r.hostname, r.service, r.text
end
results.flatten.each &method(:send_packet)
end
# Closes connection to NSCA.
@ -85,7 +92,7 @@ module NSCA
@hostname, @port, @password = hostname, port, password
end
def open( &e) Connection.open @hostname, @port, @password, &e end
def open( &e) Connection.open hostname: @hostname, port: @port, password: @password, &e end
def send( *results) open {|conn| conn.send results } end
end
end

View File

@ -1,29 +1,4 @@
module NSCA
class <<self
def xor key, msg, key_a = nil
key_a ||= key.unpack 'C*'
l = key_a.length
return msg if l < 1
# Slice the message in parts of length key_a.length.
# XOR each char of a part with char at the same index in key_a.
msg.unpack( 'C*').each_with_index.map {|c,i| c^key_a[i%l] }.pack 'C*'
end
def crc32 msg
(msg.each_byte.inject 0xFFFFFFFF do |r,b|
8.times.inject( r^b) {|r,_i| (r>>1) ^ (0xEDB88320 * (r&1)) }
end) ^ 0xFFFFFFFF
end
# Builds a null terminated, null padded string of length maxlen
def str2cstr( str, maxlen = nil)
str = str.to_s
str = str.to_s[0..(maxlen-2)] if maxlen
"#{str}\x00"
end
def cstr2str( str, maxlen = nil) str[ 0, x.index( ?\0) || ((maxlen||0)-1)] end
end
class Packet
class CSC32CheckFailed <Exception
end
@ -57,7 +32,7 @@ module NSCA
END_OF_TRANSMISSION = ?\x0a
HOSTNAME_LENGTH = 64
SERVICE_LENGTH = 128
STATUS_LENGTH = 512
PLUGIN_OUTPUT_LENGTH = 512
# these line describes the data package:
# typedef struct data_packet_struct{
@ -71,41 +46,54 @@ module NSCA
# char plugin_output[MAX_PLUGINOUTPUT_LENGTH];
# /* two extra padding-xx, too. */
# }data_packet;
PACK_STRING = "s> xx L> L> s> Z#{HOSTNAME_LENGTH} Z#{SERVICE_LENGTH} Z#{STATUS_LENGTH} xx"
PACK_LENGTH = 2+2+4+4+2+HOSTNAME_LENGTH+SERVICE_LENGTH+STATUS_LENGTH+2
PACK_STRING = "s> xx L> L> s> A#{HOSTNAME_LENGTH} A#{SERVICE_LENGTH} A#{PLUGIN_OUTPUT_LENGTH} xx"
PACK_LENGTH = 2+2+4+4+2+HOSTNAME_LENGTH+SERVICE_LENGTH+PLUGIN_OUTPUT_LENGTH+2
register_version PACKET_VERSION, self
# Builds a check-result-line for NSCA.
#
# Will be terminated by end-of-terminate.
def build key = nil, password = nil
def build slf = nil
cl = (slf || self).class
entry = [
PACKET_VERSION,
cl::PACKET_VERSION,
0, # crc32 (unknown yet)
(timestamp || Time.now).to_i,
return_code.to_i,
NSCA::str2cstr( hostname || `hostname -f`, HOSTNAME_LENGTH),
NSCA::str2cstr( service, SERVICE_LENGTH),
NSCA::str2cstr( status, STATUS_LENGTH) # incl perfdata
NSCA::str2cstr_rand_padding( hostname || `hostname -f`, cl::HOSTNAME_LENGTH),
NSCA::str2cstr_rand_padding( service, cl::SERVICE_LENGTH),
NSCA::str2cstr_rand_padding( status, cl::PLUGIN_OUTPUT_LENGTH) # incl perfdata
]
# generate crc32 and put it at entry[2...6]
entry[1] = NSCA::crc32 entry.pack( PACK_STRING)
entry = entry.pack PACK_STRING
entry = NSCA::xor key, entry if key
entry = NSCA::xor password, entry if password
entry[1] = NSCA::crc32 entry.pack( cl::PACK_STRING)
entry = entry.pack cl::PACK_STRING
entry
end
def self.parse entry, key = nil, password = nil, no_verification_checks = nil
entry = NSCA::xor key, entry if key
entry = NSCA::xor password, entry if password
def self.parse entry, no_verification_checks = nil
entry = entry.to_s.dup
ver, crc32sum, *x = entry.unpack( PACK_STRING)
x[2] = NSCA::cstr2str x[2]
x[3] = NSCA::cstr2str x[3]
x[4] = NSCA::cstr2str x[4]
raise VersionCheckFailed, "Packet version 3 expected. (recv: #{ver})" \
unless no_verification_checks or 3 == ver
entry[4..7] = ?\x00*4
raise CSC32CheckFailed, "crc32-check failed. packet seems to be broken." \
unless no_verification_checks or crc32sum == NSCA::crc32( entry)
crc32 = NSCA::crc32 entry
raise CSC32CheckFailed, "crc32-check failed. packet seems to be broken: #{crc32sum.inspect} != #{crc32.inspect}" \
unless no_verification_checks or crc32sum == crc32
new *x
end
end
class PacketV3__2_9 < PacketV3
NAGIOS_VERSION = 2.7
PACKET_VERSION = 3
END_OF_TRANSMISSION = ?\x0a
PLUGIN_OUTPUT_LENGTH = 4096
HOSTNAME_LENGTH = 64
SERVICE_LENGTH = 128
PACK_STRING = "s> xx L> L> s> A#{HOSTNAME_LENGTH} A#{SERVICE_LENGTH} A#{PLUGIN_OUTPUT_LENGTH} xx"
PACK_LENGTH = 2+2+4+4+2+HOSTNAME_LENGTH+SERVICE_LENGTH+PLUGIN_OUTPUT_LENGTH+2
end
end

View File

@ -2,12 +2,12 @@ module NSCA
class Server
include Enumerable
attr_reader :iv_key, :server, :packet_version, :password
attr_reader :iv_key, :server, :packet_version, :password, :xor_iv_key, :xor_password
def initialize *args
opts = {}
opts = args.pop.dup if args.last.is_a? Hash
opts[:host] ||= opts[:hostname]
opts[:sock] ||= opts[:socket]
opts[:serv] ||= opts[:server]
opts[:pass] ||= opts[:password]
case args[0]
@ -15,7 +15,7 @@ module NSCA
opts[:port] = args[0]
opts[:host] ||= args[1]
when IO
opts[:sock] = args[0]
opts[:serv] = args[0]
end
@packet_version = opts[:packet_version] || PacketV3
@ -25,7 +25,7 @@ module NSCA
@server = if opts[:serv].is_a?( TCPServer) or opts[:serv].is_a?( UNIXServer)
opts[:serv]
elsif opts[:port].is_a? Integer
TCPServer.new *[opts[:port], opts[:host]].compact
TCPServer.new *[opts[:host], opts[:port]].compact
else
raise ArgumentError, "Server or port-number expected"
end
@ -50,22 +50,36 @@ module NSCA
@packet_version = server.packet_version
@packet_length = @packet_version::PACK_LENGTH
@socket.write [@iv_key, Time.now.to_i].pack( 'a* L>')
@xor_password = NSCA::Helper.xor_stream @password
@xor_iv_key = NSCA::Helper.xor_stream @iv_key
end
def fetch
data = read
@packet_version.parse data, @iv_key, @password if data
iv_key = NSCA::Helper.xor_stream @iv_key
password = NSCA::Helper.xor_stream @password
packet_version = iv_key[ password[ read PacketV3::PACKET_VERSION]]
v = packet_version.unpack( 's>').first
case v
when 3
data = packet_version + iv_key[ password[ read( PacketV3::PACK_LENGTH - PacketV3::PACKET_VERSION)]]
begin
return PacketV3.parse( data)
rescue NSCA::Packet::CSC32CheckFailed
x = read( PacketV3__2_9::PACK_LENGTH - data.length)
raise if x.nil?
return PacketV3__2_9.parse( data + iv_key[ password[ x]])
end
else raise "Unknown Version #{v.inspect}"
end
end
def each &block
return Enumerator.new( self) unless block_given?
while data = fetch
yield data
end
yield fetch until eof?
end
def eof?() @socket.eof? end
def read() @socket.read @packet_length end
def read( len = nil) @socket.read( len || @packet_length) end
def close() @socket.close end
end
end

View File

@ -5,11 +5,11 @@
Gem::Specification.new do |s|
s.name = "nsca"
s.version = "0.1.0"
s.version = "0.2.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Denis Knauf"]
s.date = "2013-04-08"
s.date = "2013-04-24"
s.description = "Create your alerts easily and send it to Nagios"
s.email = "Denis.Knauf@gmail.com"
s.extra_rdoc_files = [
@ -35,7 +35,7 @@ Gem::Specification.new do |s|
"test/test_nsca.rb"
]
s.homepage = "http://github.com/DenisKnauf/nsca"
s.licenses = ["MIT"]
s.licenses = ["LGPL-3"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.23"
s.summary = "Nagios passive alerts with friendly API"

View File

@ -1,35 +1,89 @@
require 'helper'
require 'dummy_server'
require 'securerandom'
class TestNSCA < Test::Unit::TestCase
class TestChecks
extend NSCA::Checks
perfdata :PD1, :pd1_in_sec, :s, 10, 20, 0, 30
perfdata :PD2, :pd2_in_1, 1, 0.99, 0.98, 0, 1
perfdata :PD3, :pd3_count, :c, 3, 5, 0
check :T0, 'TestNSCA0', 'uxnags01-sbe.net.mobilkom.at'
check :T1, 'TestNSCA1', 'uxnags01-sbe.net.mobilkom.at', [PD1, PD2]
check :T2, :TestNSCA2, 'uxnags01-sbe.net.mobilkom.at', [PD1, PD2, PD3]
context 'xor' do
should 'return a if a (random) will xored double with random key. (1000 rounds)' do
1000.times do
key_len = SecureRandom.random_number 1000
a_len = SecureRandom.random_number 1000
key = SecureRandom.random_bytes key_len
a = SecureRandom.random_bytes a_len
assert_equal a, NSCA.xor( key, NSCA.xor(key, a))
end
end
end
end
class TestNSCACommunication < Test::Unit::TestCase
Port = 5787
def dummy_server *args
server = Thread.new do
begin
NSCA.dummy_server *args
rescue Object
#STDERR.puts "#{$!.class}: #{$!}", $!.backtrace.map{|bt|" #{bt}"}
raise
ensure
#STDERR.puts "Dummy Server Shutdown"
end
end
sleep 1 # server needs time to start...
server
end
context 'our test server' do
should 'receive data. NSCA-server should run on localhost 5777. if not, ignore this test. password=abcdefghijkl' do
PD1 = TestChecks::PD1
PD2 = TestChecks::PD2
PD3 = TestChecks::PD3
T0 = TestChecks::T0
T1 = TestChecks::T1
T2 = TestChecks::T2
include NSCA::Checks
context "our dummy test server on localhost:#{Port} with random password" do
should 'receive data' do
password = 'password' || SecureRandom.random_bytes
timestamp = Time.now
PD1 = perfdata :pd1_in_sec, :s, 10, 20, 0, 30
PD2 = perfdata :pd2_in_1, 1, 0.99, 0.98, 0, 1
PD3 = perfdata :pd3_count, :c, 3, 5, 0
T0 = check 'TestNSCA0', 'localhost'
T1 = check 'TestNSCA1', 'localhost', [PD1, PD2]
T2 = check :TestNSCA2, 'localhost', [PD1, PD2, PD3]
checks = []
checks << TestChecks::T0.new( 1, "0123456789"*51+"AB")
t0 = T0.new( 1, "0123456789"*51+"AB", nil, timestamp) # oversized service name
checks << t0
pd1 = PD1.new 3
pd2 = PD2.new 0.9996
pd3 = PD3.new 2
checks << TestChecks::T1.new( nil, "Should be OK", [pd1, pd2, pd3])
t1 = T1.new( nil, "Should be OK", [pd1, pd2, pd3], timestamp)
checks << t1
NSCA::destinations << NSCA::Client.new( 'localhost', 5667, password: 'abcdefghijkl')
NSCA::destinations.clear
NSCA::destinations << NSCA::Client.new( 'localhost', Port, password)
server = dummy_server port: Port, password: password
NSCA::send *checks
pc0, pc1 = server.value
[[t0, pc0], [t1, pc1]].each do |(test, packet)|
assert_equal test.hostname, packet.hostname
assert_equal test.service, packet.service
assert_equal timestamp.to_i, packet.timestamp.to_i
assert_equal test.retcode, packet.return_code
end
# original with AB, but B is char 512 and will be replaced by \0
assert_equal "0123456789"*51+"A", pc0.status
assert_equal "Should be OK | 'pd1_in_sec'=3s,10,20,0,30 'pd2_in_1'=0.99961,0.99,0.98,0,1 'pd3_count'=2c,3,5,0,", pc1.status
end
should 'fail crc32 if wrong password' do
password = 'password' || SecureRandom.random_bytes
timestamp = Time.now
T3 = check 'TestNSCA0', 'localhost'
NSCA::destinations.clear
NSCA::destinations << NSCA::Client.new( 'localhost', Port, password+'a')
server = dummy_server hostname: 'localhost', port: Port, password: password
NSCA::send [T3.new( 1, 'status', nil, timestamp)]
assert_raise( NSCA::Packet::CSC32CheckFailed) { server.join }
end
end
end
@ -69,8 +123,14 @@ class TestNSCA::PerformanceData < Test::Unit::TestCase
context 'Created NSCA::PerformanceData-subclasses' do
should 'be the same like returned' do
cl = NSCA::PerformanceData.create 'returned and subclass the same test'
assert cl == NSCA::PerformanceData::Returned_and_subclass_the_same_test, 'Classes are not the same.'
PA = NSCA::PerformanceData.create 'returned and subclass the same test'
assert_equal PA, NSCA::PerformanceData::Returned_and_subclass_the_same_test
end
should 'not exists, if #new used' do
pb = NSCA::PerformanceData.new 'no subclass'
assert_raise NameError do
NSCA::PerformanceData::No_subclass
end
end
should 'have a unit if given' do
assert :s == perfdata( 'have an unit test', :s).unit, "Not s as unit"
@ -85,11 +145,110 @@ class TestNSCA::PerformanceData < Test::Unit::TestCase
assert nil == perfdata( 'have not a warn test', nil, nil).warn, "Not nil as warn"
end
end
end
context 'Measure' do
should 'work with s' do
PC = perfdata 'something in seconds', :s
assert PC.measure { true }.is_a?( PC), 'can not be created?'
end
class TestNSCA::Client < Test::Unit::TestCase
should '' do
NSCA::Client
should 'work with ms' do
PD = perfdata 'something in mili seconds', :ms
assert PD.measure { true }.is_a?( PD), 'can not be created?'
end
should 'not work with something else' do
PE = perfdata 'something else than time', :c
assert_raise NSCA::PerformanceData::TimeUnitExpected do
PE.measure { true }
end
end
should 'measure something between 1s..3s if i sleep 2 seconds' do
PF = perfdata 'wait 2 seconds', :s
pf = PF.measure { sleep 2 }
assert (1..3).include?( pf.value), "Not in range 1s..3s: #{pf.value}s"
end
should 'measure something between 1000ms..3000ms if i sleep 2 seconds' do
PG = perfdata 'wait 2000 mili second', :ms
pf = PG.measure { sleep 2 }
assert (1000..3000).include?( pf.value), "Not in range 1000ms..3000ms: #{pf.value}ms"
end
end
end
class TestNSCA::Check < Test::Unit::TestCase
context 'Data' do
should 'also be empty' do
CF = NSCA::Check.new 'empty data'
cf = CF.new
hostname = `hostname`.chomp
assert_equal [cf.timestamp, 3, hostname, 'empty data', 'UNKNOWN'], cf.to_a
end
should 'have default a timestamp. ~ -10s..10s' do
CG = NSCA::Check.new 'default timestamp'
cg = CG.new
now = Time.now
range = Time.at(now-10) .. Time.at(now+10)
assert range.begin <= cg.timestamp && cg.timestamp <= range.end,
"Not a valid timestamp ~now: #{cg.timestamp}"
end
end
context 'Subclasses' do
should 'be created by NSCA::Check.create' do
CA = NSCA::Check.create 'a uniq name'
assert_same CA, NSCA::Check::A_uniq_name
end
end
context 'No Subclasses' do
should 'be created by NSCA::Check.new' do
CB = NSCA::Check.new 'a uniq name, too'
assert_raise NameError, 'A class named NSCA::Check::A_uniq_name_too exists' do
CB == NSCA::Check::A_uniq_name_too
end
end
end
context 'Clones' do
should 'have old class as superclass' do
CC1 = NSCA::Check.new( 'a check which will be for cloning')
CC2 = CC1.clone
assert_equal CC2.superclass, CC1
end
should 'have the same data' do
CD1 = NSCA::Check.new 'a check for same data after cloning'
CD2 = CD1.clone
assert_equal CD2.to_a, CD2.to_a
end
should 'have the same data, except specific data' do
CE1 = NSCA::Check.new 'a check for same data after cloning again, but...'
CE2 = CE1.clone service: '... but the service will be changed.'
assert_not_equal CE1.service, CE2.service
assert_equal 'a check for same data after cloning again, but...', CE1.service
assert_equal '... but the service will be changed.', CE2.service
ce1_data, ce2_data = CE1.to_a, CE2.to_a
ce1_data[0] = ce2_data[0] = 'dummy'
assert_equal ce1_data, ce2_data
end
end
context 'Perfdatas in Checks' do
should 'be saved as symbol-key' do
PH = NSCA::PerformanceData.new 'simplename', :ms
CH = NSCA::Check.new 'a check with perfdata', 'hostname', [PH]
assert_equal PH, CH.perfdatas[:'simplename']
ch = CH.new
assert_equal nil, ch['simplename']
assert_equal nil, ch[:simplename]
a = 0
ch.measure( 'simplename') { 0.upto( 10000) { a += 1 } }
assert_equal ch['simplename'], ch[:simplename]
end
end
end