ref: refs/heads/master
commit 86a117beb5de0867187d2c1469f778f2f1d80f5f
Author: Bjoern Geuken
Date: Thu Jul 9 18:41:22 2009 +0200
status module: code rewiev, added tests, added some #fixme marks
Todo: path of metrics needs to be read from collect.conf,
couldn't stub IO class (no EOF),
Health Status
---
plugins/status/Rakefile | 49 +++++++++++++++
.../status/app/controllers/status_controller.rb | 4 +-
plugins/status/app/models/status.rb | 47 ++++++++-------
plugins/status/test/test_helper.rb | 52 ++++++++++++++++
plugins/status/test/unit/status_test.rb | 65 ++++++++++++++++----
5 files changed, 182 insertions(+), 35 deletions(-)
diff --git a/plugins/status/Rakefile b/plugins/status/Rakefile
new file mode 100644
index 0000000..3b4fea5
--- /dev/null
+++ b/plugins/status/Rakefile
@@ -0,0 +1,49 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+require 'rake/packagetask'
+require File.join(File.dirname(__FILE__), 'config', 'rails_parent')
+require File.join(RailsParent.parent, 'config', 'boot')
+require 'tasks/rails'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the status plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the security plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'Status'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+desc 'Generate tarball package'
+Rake::PackageTask.new('www', :noversion) do |p|
+ %x[rm -r package/www]
+ p.need_tar_bz2 = true
+ p.package_dir = 'package'
+ p.package_files.include('**/*')
+ p.package_files.exclude('package')
+end
+
+desc "install policies"
+task :install do |t|
+ Dir.glob("**/*.policy").each do |policy|
+ sudo "cp #{policy} /usr/share/PolicyKit/policy"
+ end
+end
+
+def sudo(cmd)
+ puts "#{cmd}"
+ %x[sudo -p "Password: " #{cmd}]
+end
+
diff --git a/plugins/status/app/controllers/status_controller.rb b/plugins/status/app/controllers/status_controller.rb
index c57f1bd..bda2e65 100644
--- a/plugins/status/app/controllers/status_controller.rb
+++ b/plugins/status/app/controllers/status_controller.rb
@@ -32,9 +32,11 @@ class StatusController < ApplicationController
render ErrorResult.error(403, 1, "no permission") and return
else
@status = Status.new
+ #logger.debug params.inspect
+ @status.set_datapath()
+logger.debug @status.datapath
@status.collect_data(params[:start], params[:stop], params[:data])
# @status.collect_data("11:13,07/02/2009", "11:14,07/07/2009", %w{cpu memory disk})
-
end
end
diff --git a/plugins/status/app/models/status.rb b/plugins/status/app/models/status.rb
index 3ae51a8..39efdc8 100644
--- a/plugins/status/app/models/status.rb
+++ b/plugins/status/app/models/status.rb
@@ -1,16 +1,18 @@
class Status < ActiveRecord::Base
require 'scr'
- attr_accessor :data
+ attr_accessor :data,
+ :datapath,
+ :health_status,
+ :metrics
- def initialize
+ def initialize()
@scr = Scr.instance
@health_status = nil
@data = Hash.new
start_collectd
-# @collectd_base_dir = "/var/lib/collectd/"
- @datapath = set_datapath
- @metrics = available_metrics
+ @datapath = nil #set_datapath
+# @metrics = available_metrics
end
def start_collectd
@@ -25,23 +27,20 @@ class Status < ActiveRecord::Base
# set path of stored rrd files, default: /var/lib/collectd/$host.$domain
def set_datapath(path=nil)
- default = "/var/lib/collectd/"
- unless path.nil?
- @datapath = path.chomp("/")
- else # set default path
- cmd = IO.popen("hostname")
- host = cmd.read
+ if path.blank? #FIXME: read currently used rrdb file from /etc/collectd.conf
+ cmd = IO.popen("ls /var/lib/collectd/")
+ path = cmd.read
cmd.close
- cmd = IO.popen("domainname")
- domainname = cmd.read
- cmd.close
- @datapath = "#{default}#{host.strip}.#{domainname.strip}"
+ path = path.split " " #FIXME
+ @datapath = "/var/lib/collectd/#{path[0].strip}"
+ else # set default path
+ @datapath = path.chomp("/")
end
return @datapath
end
def available_metrics
- metrics = Hash.new
+ @metrics = Hash.new
cmd = IO.popen("ls #{@datapath}")
output = cmd.read
cmd.close
@@ -49,9 +48,13 @@ class Status < ActiveRecord::Base
fp = IO.popen("ls #{@datapath}/#{l}")
files = fp.read
fp.close
- metrics["#{l}"] = { :rrds => files.split(" ")}
+ rrds = Array.new
+ files.split(" ").each do |d|
+ rrds << d if d.include? ".rrd" #only .rrd files
+ @metrics["#{l}"] = { :rrds => rrds}
+ end
end
- return metrics
+ return @metrics
end
def available_metric_files
@@ -68,7 +71,8 @@ class Status < ActiveRecord::Base
end
# creates several metrics for a defined period
- def collect_data(start=Time.now, stop=Time.now, data = %w{cpu memory disk})
+ def collect_data(start=nil, stop=nil, data = %w{cpu memory disk})
+ available_metrics
result = Hash.new
unless @timestamp.nil? # collectd not started
case data
@@ -103,15 +107,14 @@ class Status < ActiveRecord::Base
if start.blank?
start = "--start #{Time.now.strftime("%H:%M,%m/%d/%Y")}"
else
- start = "--start #{start}"#start.strftime("%H:%M,%m/%d/%Y")}"
+ start = "--start #{start}"
end
if stop.blank?
stop = "--end #{Time.now.strftime("%H:%M,%m/%d/%Y")}"
else
- stop = "--end #{stop}"#stop.strftime("%H:%M,%m/%d/%Y")}"
+ stop = "--end #{stop}"
end
cmd = IO.popen("rrdtool fetch #{@datapath}/#{rrdfile} AVERAGE #{start} #{stop}")
-
output = cmd.read
cmd.close
return "failed" if output.blank?
diff --git a/plugins/status/test/test_helper.rb b/plugins/status/test/test_helper.rb
new file mode 100644
index 0000000..7d67910
--- /dev/null
+++ b/plugins/status/test/test_helper.rb
@@ -0,0 +1,52 @@
+# find the rails parent
+require File.join(File.dirname(__FILE__), '..', 'config', 'rails_parent')
+# first config rails
+require File.expand_path( File.join("config","environment"), RailsParent.parent )
+# then enable testing, this will get the routing right
+ENV["RAILS_ENV"] = "test"
+require 'test_help'
+
+class ActiveSupport::TestCase
+ # Transactional fixtures accelerate your tests by wrapping each test method
+ # in a transaction that's rolled back on completion. This ensures that the
+ # test database remains unchanged so your fixtures don't have to be reloaded
+ # between every test method. Fewer database queries means faster tests.
+ #
+ # Read Mike Clark's excellent walkthrough at
+ # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
+ #
+ # Every Active Record database supports transactions except MyISAM tables
+ # in MySQL. Turn off transactional fixtures in this case; however, if you
+ # don't care one way or the other, switching from MyISAM to InnoDB tables
+ # is recommended.
+ #
+ # The only drawback to using transactional fixtures is when you actually
+ # need to test transactions. Since your test is bracketed by a transaction,
+ # any transactions started in your code will be automatically rolled back.
+ self.use_transactional_fixtures = true
+
+ # Instantiated fixtures are slow, but give you @david where otherwise you
+ # would need people(:david). If you don't want to migrate your existing
+ # test cases which use the @david style and don't mind the speed hit (each
+ # instantiated fixtures translates to a database query per test method),
+ # then set this back to true.
+ self.use_instantiated_fixtures = false
+
+ # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
+ #
+ # Note: You'll currently still have to declare fixtures explicitly in integration tests
+ # -- they do not yet inherit this setting
+ fixtures :all
+
+ # Add more helper methods to be used by all tests here...
+
+ # See http://pennysmalls.com/2009/03/04/rails-23-breakage-and-fixage/
+ def clean_backtrace(&block)
+ yield
+ rescue ActiveSupport::TestCase::Assertion => error
+ framework_path = Regexp.new(File.expand_path("#{File.dirname(__FILE__)}/assertions"))
+ error.backtrace.reject! { |line| File.expand_path(line) =~ framework_path }
+ raise
+ end
+
+end
diff --git a/plugins/status/test/unit/status_test.rb b/plugins/status/test/unit/status_test.rb
index 8d209f8..ed8cac4 100644
--- a/plugins/status/test/unit/status_test.rb
+++ b/plugins/status/test/unit/status_test.rb
@@ -4,20 +4,61 @@ require 'mocha'
require 'test_helper'
class StatusTest < ActiveSupport::TestCase
-# fixtures :accounts
def setup
-# @controller = SecuritiesController.new
-# @request = ActionController::TestRequest.new
# http://railsforum.com/viewtopic.php?id=1719
end
-=begin
- def test_vailable_metrics
- IO.stubs(:popen).with("ls random_path").returns("cpu memory")
- IO.stubs(:popen).with("ls random_path/cpu").returns("idle")
- IO.stubs(:popen).with("ls random_path/memory").returns("free buffered used")
-
- status = Status.new
- assert status.available_metrics {"cpu" => {:rrds => "idle"}, "memory" => {:rrds => "free buffered used"}}
+
+ def test_set_datapath
+ Scr.instance.stubs(:execute).with(["collectd"]).returns(nil)
+
+ status = Status.new()
+ assert status.set_datapath("/var/lib/collectd/test/"), "/var/lib/collectd/test"
+ status = Status.new()
+ assert_equal status.set_datapath("/test/foo.bar"), "/test/foo.bar"
+ end
+
+ def test_set_datapath_default
+ Scr.instance.stubs(:execute).with(["collectd"]).returns(nil)
+ IO.stubs(:popen).with("hostname").returns(String) #FIXME: replace String with IO
+ IO.stubs(:popen).with("domainname").returns(String) # returns(IO.new(2, "r+")) dont work
+ IO.stubs(:popen).with("ls /var/lib/collectd/").returns(String) # because of missing EOF token
+ String.stubs(:read).with(nil).returns("test")
+ String.stubs(:close).with(nil).returns(nil)
+
+ status = Status.new()
+ assert_equal status.set_datapath(), "/var/lib/collectd/test"
+ end
+
+ def test_available_metrics
+ Scr.instance.stubs(:execute).with(["collectd"]).returns(nil)
+
+# stubs(:set_datapath)
+
+ IO.stubs(:popen).with("ls /var/lib/collectd").returns(String) #FIXME: replace String with IO
+ IO.stubs(:popen).with("ls /var/lib/collectd/cpu").returns(String)
+ IO.stubs(:popen).with("ls /var/lib/collectd/memory").returns(String)
+ String.stubs(:read).with(nil).returns("cpu memory")
+ String.stubs(:close).with(nil).returns(nil)
+
+ status = Status.new()
+ status.datapath = "/var/lib/collectd"
+ assert_equal status.available_metrics, {"memory"=>{:rrds=>[]}, "cpu"=>{:rrds=>[]}}
+#{"memory"=>{:rrds=>["cpu", "memory"]}, "cpu"=>{:rrds=>["cpu", "memory"]}}
+ end
+
+ def test_collect_data
+
+ end
+
+ def test_fetch_data
+ Scr.instance.stubs(:execute).with(["collectd"]).returns(nil)
+ IO.stubs(:popen).with("rrdtool fetch /test/memory-free.rrd AVERAGE --start #{Time.now.strftime("%H:%M,%m/%d/%Y")} --stop #{Time.now.strftime("%H:%M,%m/%d/%Y")}").returns(String)
+ String.stubs(:read).with(nil).returns(" value\n\n1247156690: nan\n1247156700: nan\n1247156710: nan\n")
+ String.stubs(:close).with(nil).returns(nil)
+
+ status = Status.new()
+ status.datapath = "/test"
+ assert_equal status.fetch_data("memory-free.rrd"), {"memory-free" => {"value" => \
+ {"T_1247156690" => "nan", "T_1247156700" => "nan", "T_1247156710" => "nan"}}}
end
-=end
end
--
To unsubscribe, e-mail: yast-commit+unsubscribe@opensuse.org
For additional commands, e-mail: yast-commit+help@opensuse.org