Skip to content
Browse files

refactor & cleanup

  • Loading branch information...
1 parent f374ff3 commit 4c063dbc153a1f86e5e6a2bc49d5e841b103113e @hollow hollow committed Nov 25, 2011
View
3 config.ru
@@ -1,3 +0,0 @@
-require 'livestatus/api'
-$0 = "livestatusd"
-run Livestatus::API
View
8 examples/config.ru
@@ -0,0 +1,8 @@
+require 'livestatus/api'
+
+Livestatus::API.config = {
+ :uri => "unix:///var/nagios/rw/live"
+}
+
+$0 = "livestatusd (#{Livestatus::API.config[:uri]})"
+run Livestatus::API
View
10 lib/livestatus.rb
@@ -7,4 +7,14 @@
module Livestatus
mattr_accessor :connection
self.connection = nil
+
+ def self.get(model, options = {})
+ raise AttributeError, "no global connection found" unless self.connection
+ self.connection.get(model, options)
+ end
+
+ def self.command(cmd, time = nil)
+ raise AttributeError, "no global connection found" unless self.connection
+ self.connection.command(cmd, time)
+ end
end
View
5 lib/livestatus/api.rb
@@ -1,10 +1,13 @@
+require "active_support/core_ext"
require 'livestatus/connection'
require 'livestatus/models'
require 'sinatra/base'
require 'yajl'
module Livestatus
class API < Sinatra::Base
+ cattr_accessor :config
+
def parse_headers(env)
Hash[env.select do |k, v|
k =~ /^HTTP_X_LIVESTATUS_/
@@ -23,7 +26,7 @@ def parse_headers(env)
halt 400, 'invalid method' unless ['GET', 'COMMAND'].include?(method)
method = method.downcase.to_sym
- c = Livestatus::Connection.new(:uri => 'unix:///var/nagios/rw/live')
+ c = Livestatus::Connection.new(self.config)
case method
when :get
View
7 lib/livestatus/connection.rb
@@ -1,4 +1,5 @@
require "livestatus/handler"
+require "livestatus/memoize"
module Livestatus
@@ -12,10 +13,6 @@ def initialize(config)
end
def handler
- @handler ||= handler!
- end
-
- def handler!
case @config[:uri]
when /^https?:\/\//
PatronHandler.new(self, @config)
@@ -25,6 +22,8 @@ def handler!
raise AttributeError, "unknown uri type: #{@config[:uri]}"
end
end
+
+ memoize :handler
end
end
View
2 lib/livestatus/handler/patron.rb
@@ -12,7 +12,7 @@ def initialize(connection, config)
@session = Patron::Session.new
@session.timeout = 10
@session.headers["User-Agent"] = "livestatus/#{VERSION} ruby/#{RUBY_VERSION}"
- @session.insecure = config[:insecure]
+ @session.insecure = config.fetch(:insecure, false)
@session.auth_type = config.fetch(:auth_type, :basic).to_sym
@session.username = config[:username]
@session.password = config[:password]
View
79 lib/livestatus/handler/unix.rb
@@ -7,7 +7,7 @@ module Livestatus
class UnixHandler
def initialize(connection, config)
@connection = connection
- @socket = UNIXSocket.open(config[:uri].sub(/^unix:\/\//, ''))
+ @path = config[:uri].sub(/^unix:\/\//, '')
end
def get(model, options = {})
@@ -17,49 +17,74 @@ def get(model, options = {})
:keep_alive => "on",
})
- headers = options.map do |k,v|
- if v.is_a?(Array)
- v.map do |e|
- "#{k.to_s.camelize}: #{e}"
- end
- else
- "#{k.to_s.camelize}: #{v}"
- end
- end.flatten.join("\n")
-
- headers += "\n" unless headers.empty?
-
- @socket.write("GET #{model.table_name}\n#{headers}\n")
-
- res = @socket.read(16)
- status, length = res[0..2].to_i, res[4..14].chomp.to_i
+ send("GET #{model.table_name}\n#{build_headers(options)}")
+ status, length = recv
unless status == 200
raise HandlerException, "livestatus query failed with status #{status}"
end
- data = Yajl::Parser.new.parse(@socket.read(length))
+ data = Yajl::Parser.parse(recv(length))
- if options.include?(:columns)
- columns = options[:columns].split(" ")
- else
- columns = data.delete_at(0)
- end
-
- column_zip(columns, data).map do |d|
+ column_zip(data, options).map do |d|
model.new(d, @connection)
end
end
def command(cmd, time = nil)
time = Time.now.to_i unless time
- @socket.write("COMMAND [#{time}] #{cmd}\n\n")
+ send("COMMAND [#{time}] #{cmd}\n")
nil
end
private
- def column_zip(columns, data)
+ def socket
+ @socket ||= socket!
+ @socket = socket! if @socket.closed?
+ @socket
+ end
+
+ def socket!
+ UNIXSocket.open(@path)
+ end
+
+ def send(msg)
+ socket.write(msg + "\n")
+ end
+
+ def recv(length = nil)
+ if length.nil?
+ # read response header
+ res = socket.read(16)
+ [res[0..2].to_i, res[4..14].chomp.to_i]
+ else
+ # read response body
+ socket.read(length)
+ end
+ end
+
+ def build_headers(options)
+ options.map do |k, v|
+ if v.is_a?(Array)
+ v.map do |e|
+ "#{k.to_s.camelize}: #{e}"
+ end
+ else
+ "#{k.to_s.camelize}: #{v}"
+ end
+ end.flatten.join("\n").tap do |s|
+ s += "\n" unless s.empty?
+ end
+ end
+
+ def column_zip(data, options)
+ if options.include?(:columns)
+ columns = options[:columns].split(" ")
+ else
+ columns = data.delete_at(0)
+ end
+
data.map do |d|
Hash[columns.zip(d)]
end
View
17 lib/livestatus/memoize.rb
@@ -0,0 +1,17 @@
+module Memoize
+
+ def memoize(*names)
+ names.each do |name|
+ original = "#{name}!"
+ alias_method original, name
+ define_method(name) do |*args|
+ key = self.to_s.unpack("a*") << name.to_s.unpack("a*") << args
+ @__memoize_cache__ ||= {}
+ @__memoize_cache__[key] ||= send(original, *args)
+ end
+ end
+ end
+
+end
+
+Module.send(:include, ::Memoize)
View
6 lib/livestatus/models.rb
@@ -39,12 +39,6 @@ def time_attributes(*accessors)
end
end
- module ID
- def id
- Digest::SHA1.hexdigest(_id)[0..7]
- end
- end
-
module State
def state
{
View
7 lib/livestatus/models/host.rb
@@ -1,5 +1,4 @@
class Livestatus::Host < Livestatus::Base
- include Livestatus::ID
include Livestatus::CheckType
include Livestatus::State
@@ -15,15 +14,11 @@ class Livestatus::Host < Livestatus::Base
:last_time_unreachable, :last_time_up, :next_check, :next_notification
def services
- @data[:host_services_with_state].map do |service|
+ @data[:services_with_state].map do |service|
Livestatus::Service.new({
:display_name => service[0],
:state => service[1],
})
end
end
-
- def _id
- display_name
- end
end
View
5 lib/livestatus/models/service.rb
@@ -1,5 +1,4 @@
class Livestatus::Service < Livestatus::Base
- include Livestatus::ID
include Livestatus::CheckType
include Livestatus::State
@@ -22,8 +21,4 @@ class Livestatus::Service < Livestatus::Base
:last_hard_state_change, :last_notification, :last_state_change,
:last_time_critical, :last_time_ok, :last_time_unknown, :last_time_warning,
:next_check, :next_notification
-
- def _id
- host_display_name + display_name
- end
end

0 comments on commit 4c063db

Please sign in to comment.
Something went wrong with that request. Please try again.