diff options
author | Claire McQuin <claire@opscode.com> | 2013-07-31 17:10:15 -0700 |
---|---|---|
committer | Claire McQuin <claire@opscode.com> | 2013-08-07 10:16:39 -0700 |
commit | 2fdf7078f3497c84ee8469d294030a3b169ea5d0 (patch) | |
tree | b17bb9f89ee7c789e438e87d3a9a974b494a794d /lib/ohai | |
parent | 07a1512d4b941c76bd62dcd27e1aa94969814e52 (diff) | |
download | ohai-2fdf7078f3497c84ee8469d294030a3b169ea5d0.tar.gz |
convert plugins to new dsl.
Diffstat (limited to 'lib/ohai')
132 files changed, 4457 insertions, 3933 deletions
diff --git a/lib/ohai/dsl/plugin.rb b/lib/ohai/dsl/plugin.rb index a66988f5..a00e7eef 100644 --- a/lib/ohai/dsl/plugin.rb +++ b/lib/ohai/dsl/plugin.rb @@ -1,3 +1,9 @@ +# +# +# + +require 'ohai/os' + require 'ohai/mixin/command' require 'ohai/mixin/seconds_to_human' @@ -9,10 +15,11 @@ module Ohai plugin_class = Class.new(DSL::Plugin, &block) const_set(plugin_name, plugin_class) end - + module DSL class Plugin + include Ohai::OS include Ohai::Mixin::Command include Ohai::Mixin::SecondsToHuman @@ -39,6 +46,12 @@ module Ohai end end + def self.depends_os(*args) + args.each do |attr| + depends_attrs << "#{Ohai::OS.collect_os}/#{attr}" + end + end + def self.collect_data(&block) define_method(:run, &block) end @@ -53,6 +66,7 @@ module Ohai end def require_plugin(*args) + # @todo: backwards compat # @controller.require_plugin(*args) end diff --git a/lib/ohai/loader.rb b/lib/ohai/loader.rb index e73a1de0..2c7cbf56 100644 --- a/lib/ohai/loader.rb +++ b/lib/ohai/loader.rb @@ -2,6 +2,7 @@ # # +require 'ohai/log' require 'ohai/mash' require 'ohai/dsl/plugin' require 'ohai/mixin/from_file' @@ -11,58 +12,52 @@ module Ohai include Ohai::Mixin::FromFile def initialize(controller) - @metadata = controller.metadata - @loaded_plugins = controller.loaded_plugins + @attributes = controller.attributes + @plugins = controller.plugins end - def load_plugin(plugin_name) - filename = "#{plugin_name.gsub("::", File::SEPARATOR)}.rb" + def load_plugin(plugin_path, plugin_name=nil) plugin = nil - - # @todo: what to do with plugins found on multiple paths? - # currently assumes one path per plugin (or, last loaded plugin - # gets saved) - Ohai::Config[:plugin_path].each do |path| - check_path = File.expand_path(File.join(path, filename)) - if File.exist?(check_path) - plugin = from_file(check_path) - collect_metadata(plugin_name, check_path, plugin) - end - end - - # @todo: some better error handling here + + plugin = from_file(plugin_path) if plugin.nil? - puts "Unable to load plugin #{plugin_name}!" - else - @loaded_plugins[plugin_name] = plugin + Ohai::Log.debug("Unable to load plugin at #{plugin_path}") + return end + + plugin_key = plugin_name || plugin.name + register_plugin(plugin, plugin_path, plugin_key) + collect_provides(plugin, plugin_key) end private - def collect_metadata(plugin_name, file, plugin) - collect_provides(plugin_name, file, plugin.provides_attrs) - # @todo: collect depends data and fill in to metadata + def register_plugin(plugin, file, plugin_key) + @plugins[plugin_key] ||= Mash.new + + p = @plugins[plugin_key] + p[:plugin] = plugin + p[:source] = file + p[:depends] = plugin.depends_attrs end + - def collect_provides(plugin_name, file, attrs) - attrs.each do |attr| + def collect_provides(plugin, plugin_key) + plugin_provides = plugin.provides_attrs + + plugin_provides.each do |attr| parts = attr.split('/') - m = @metadata + a = @attributes unless parts.length == 0 parts.shift if parts[0].length == 0 parts.each do |part| - m[part] ||= Mash.new - m = m[part] + a[part] ||= Mash.new + a = a[part] end end - %w{ _providers _plugin_name }.each do |key| - m[key] ||= [] - end - - m[:_providers] << file - m[:_plugin_name] << plugin_name + a[:_providers] ||= [] + a[:_providers] << plugin_key end end diff --git a/lib/ohai/os.rb b/lib/ohai/os.rb new file mode 100644 index 00000000..c2471dd2 --- /dev/null +++ b/lib/ohai/os.rb @@ -0,0 +1,71 @@ +# +# +# + +require 'rbconfig' + +module Ohai + module OS + + def self.collect_os + case ::RbConfig::CONFIG['host_os'] + when /aix(.+)$/ + return "aix" + when /darwin(.+)$/ + return "darwin" + when /hpux(.+)$/ + return "hpux" + when /linux/ + return "linux" + when /freebsd(.+)$/ + return "freebsd" + when /openbsd(.+)$/ + return "openbsd" + when /netbsd(.*)$/ + return "netbsd" + when /solaris2/ + return "solaris2" + when /mswin|mingw32|windows/ + # After long discussion in IRC the "powers that be" have come to a concensus + # that there is no other Windows platforms exist that were not based on the + # Windows_NT kernel, so we herby decree that "windows" will refer to all + # platforms built upon the Windows_NT kernel and have access to win32 or win64 + # subsystems. + return "windows" + else + return ::RbConfig::CONFIG['host_os'] + end + end + + def collect_os + case ::RbConfig::CONFIG['host_os'] + when /aix(.+)$/ + return "aix" + when /darwin(.+)$/ + return "darwin" + when /hpux(.+)$/ + return "hpux" + when /linux/ + return "linux" + when /freebsd(.+)$/ + return "freebsd" + when /openbsd(.+)$/ + return "openbsd" + when /netbsd(.*)$/ + return "netbsd" + when /solaris2/ + return "solaris2" + when /mswin|mingw32|windows/ + # After long discussion in IRC the "powers that be" have come to a concensus + # that there is no other Windows platforms exist that were not based on the + # Windows_NT kernel, so we herby decree that "windows" will refer to all + # platforms built upon the Windows_NT kernel and have access to win32 or win64 + # subsystems. + return "windows" + else + return ::RbConfig::CONFIG['host_os'] + end + end + + end +end diff --git a/lib/ohai/plugins/aix/cpu.rb b/lib/ohai/plugins/aix/cpu.rb index 32b2dc91..169ce782 100644 --- a/lib/ohai/plugins/aix/cpu.rb +++ b/lib/ohai/plugins/aix/cpu.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::cpu" +Ohai.plugin(:Cpu) do + depends "sigar::cpu" +end diff --git a/lib/ohai/plugins/aix/filesystem.rb b/lib/ohai/plugins/aix/filesystem.rb index 8322ee0b..15b39e08 100644 --- a/lib/ohai/plugins/aix/filesystem.rb +++ b/lib/ohai/plugins/aix/filesystem.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::filesystem" +Ohai.plugin(:Filesystem) do + depends "sigar::filesystem" +end diff --git a/lib/ohai/plugins/aix/hostname.rb b/lib/ohai/plugins/aix/hostname.rb index 805b4734..b01959bf 100644 --- a/lib/ohai/plugins/aix/hostname.rb +++ b/lib/ohai/plugins/aix/hostname.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::hostname" +Ohai.plugin(:Hostname) do + depends "sigar::hostname" +end diff --git a/lib/ohai/plugins/aix/memory.rb b/lib/ohai/plugins/aix/memory.rb index dd3532fb..d625ff83 100644 --- a/lib/ohai/plugins/aix/memory.rb +++ b/lib/ohai/plugins/aix/memory.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::memory" +Ohai.plugin(:Memory) do + depends "sigar::memory" +end diff --git a/lib/ohai/plugins/aix/network.rb b/lib/ohai/plugins/aix/network.rb index 7071abef..e65eb8bf 100644 --- a/lib/ohai/plugins/aix/network.rb +++ b/lib/ohai/plugins/aix/network.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::network" +Ohai.plugin(:Network) do + depends "sigar::network" +end diff --git a/lib/ohai/plugins/aix/platform.rb b/lib/ohai/plugins/aix/platform.rb index bea329d6..712711ad 100644 --- a/lib/ohai/plugins/aix/platform.rb +++ b/lib/ohai/plugins/aix/platform.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::platform" +Ohai.plugin(:Platform) do + depends "sigar::platform" +end diff --git a/lib/ohai/plugins/aix/ps.rb b/lib/ohai/plugins/aix/ps.rb index 9532014a..7fb57ddb 100644 --- a/lib/ohai/plugins/aix/ps.rb +++ b/lib/ohai/plugins/aix/ps.rb @@ -16,8 +16,12 @@ # limitations under the License. # -provides "command/ps" +Ohai.plugin(:Ps) do + provides "command/ps" -require_plugin 'command' + depends 'command' -command[:ps] = 'ps -ef' + collect_data do + command[:ps] = 'ps -ef' + end +end diff --git a/lib/ohai/plugins/aix/uptime.rb b/lib/ohai/plugins/aix/uptime.rb index 23aa89f3..bd6f3938 100644 --- a/lib/ohai/plugins/aix/uptime.rb +++ b/lib/ohai/plugins/aix/uptime.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::uptime" +Ohai.plugin(:Uptime) do + depends "sigar::uptime" +end diff --git a/lib/ohai/plugins/azure.rb b/lib/ohai/plugins/azure.rb index d13a388f..27454f48 100644 --- a/lib/ohai/plugins/azure.rb +++ b/lib/ohai/plugins/azure.rb @@ -1,13 +1,16 @@ -provides "azure" +Ohai.plugin(:Azure) do + provides "azure" - -azure_metadata_from_hints = hint?('azure') -if azure_metadata_from_hints - Ohai::Log.debug("azure_metadata_from_hints is present.") - azure Mash.new - azure_metadata_from_hints.each {|k, v| azure[k] = v } -else - Ohai::Log.debug("No hints present for azure.") - false -end
\ No newline at end of file + collect_data do + azure_metadata_from_hints = hint?('azure') + if azure_metadata_from_hints + Ohai::Log.debug("azure_metadata_from_hints is present.") + azure Mash.new + azure_metadata_from_hints.each {|k, v| azure[k] = v } + else + Ohai::Log.debug("No hints present for azure.") + false + end + end +end diff --git a/lib/ohai/plugins/c.rb b/lib/ohai/plugins/c.rb index 3e05aa06..44517e47 100644 --- a/lib/ohai/plugins/c.rb +++ b/lib/ohai/plugins/c.rb @@ -18,93 +18,97 @@ require 'rbconfig' -provides "languages/c" +Ohai.plugin(:C) do + provides "languages/c" -require_plugin "languages" + depends "languages" -c = Mash.new + collect_data do + c Mash.new -#gcc -status, stdout, stderr = run_command(:no_status_check => true, :command => "gcc -v") -if status == 0 - description = stderr.split($/).last - output = description.split - if output.length >= 3 - c[:gcc] = Mash.new - c[:gcc][:version] = output[2] - c[:gcc][:description] = description - end -end + #gcc + status, stdout, stderr = run_command(:no_status_check => true, :command => "gcc -v") + if status == 0 + description = stderr.split($/).last + output = description.split + if output.length >= 3 + c[:gcc] = Mash.new + c[:gcc][:version] = output[2] + c[:gcc][:description] = description + end + end -#glibc -["/lib/libc.so.6", "/lib64/libc.so.6"].each do |glibc| - status, stdout, stderr = run_command(:no_status_check => true, :command => glibc) - if status == 0 - description = stdout.split($/).first - if description =~ /(\d+\.\d+\.?\d*)/ - c[:glibc] = Mash.new - c[:glibc][:version] = $1 - c[:glibc][:description] = description + #glibc + ["/lib/libc.so.6", "/lib64/libc.so.6"].each do |glibc| + status, stdout, stderr = run_command(:no_status_check => true, :command => glibc) + if status == 0 + description = stdout.split($/).first + if description =~ /(\d+\.\d+\.?\d*)/ + c[:glibc] = Mash.new + c[:glibc][:version] = $1 + c[:glibc][:description] = description + end + break + end end - break - end -end -#ms cl -status, stdout, stderr = run_command(:no_status_check => true, :command => "cl /?") -if status == 0 - description = stderr.split($/).first - if description =~ /Compiler Version ([\d\.]+)/ - c[:cl] = Mash.new - c[:cl][:version] = $1 - c[:cl][:description] = description - end -end + #ms cl + status, stdout, stderr = run_command(:no_status_check => true, :command => "cl /?") + if status == 0 + description = stderr.split($/).first + if description =~ /Compiler Version ([\d\.]+)/ + c[:cl] = Mash.new + c[:cl][:version] = $1 + c[:cl][:description] = description + end + end -#ms vs -status, stdout, stderr = run_command(:no_status_check => true, :command => "devenv.com /?") -if status == 0 - lines = stdout.split($/) - description = lines[0].length == 0 ? lines[1] : lines[0] - if description =~ /Visual Studio Version ([\d\.]+)/ - c[:vs] = Mash.new - c[:vs][:version] = $1.chop - c[:vs][:description] = description - end -end + #ms vs + status, stdout, stderr = run_command(:no_status_check => true, :command => "devenv.com /?") + if status == 0 + lines = stdout.split($/) + description = lines[0].length == 0 ? lines[1] : lines[0] + if description =~ /Visual Studio Version ([\d\.]+)/ + c[:vs] = Mash.new + c[:vs][:version] = $1.chop + c[:vs][:description] = description + end + end -#ibm xlc -status, stdout, stderr = run_command(:no_status_check => true, :command => "xlc -qversion") -if status == 0 or (status >> 8) == 249 - description = stdout.split($/).first - if description =~ /V(\d+\.\d+)/ - c[:xlc] = Mash.new - c[:xlc][:version] = $1 - c[:xlc][:description] = description.strip - end -end + #ibm xlc + status, stdout, stderr = run_command(:no_status_check => true, :command => "xlc -qversion") + if status == 0 or (status >> 8) == 249 + description = stdout.split($/).first + if description =~ /V(\d+\.\d+)/ + c[:xlc] = Mash.new + c[:xlc][:version] = $1 + c[:xlc][:description] = description.strip + end + end -#sun pro -status, stdout, stderr = run_command(:no_status_check => true, :command => "cc -V -flags") -if status == 0 - output = stderr.split - if stderr =~ /^cc: Sun C/ && output.size >= 4 - c[:sunpro] = Mash.new - c[:sunpro][:version] = output[3] - c[:sunpro][:description] = stderr.chomp - end -end + #sun pro + status, stdout, stderr = run_command(:no_status_check => true, :command => "cc -V -flags") + if status == 0 + output = stderr.split + if stderr =~ /^cc: Sun C/ && output.size >= 4 + c[:sunpro] = Mash.new + c[:sunpro][:version] = output[3] + c[:sunpro][:description] = stderr.chomp + end + end -#hpux cc -status, stdout, stderr = run_command(:no_status_check => true, :command => "what /opt/ansic/bin/cc") -if status == 0 - description = stdout.split($/).select { |line| line =~ /HP C Compiler/ }.first - if description - output = description.split - c[:hpcc] = Mash.new - c[:hpcc][:version] = output[1] if output.size >= 1 - c[:hpcc][:description] = description.strip + #hpux cc + status, stdout, stderr = run_command(:no_status_check => true, :command => "what /opt/ansic/bin/cc") + if status == 0 + description = stdout.split($/).select { |line| line =~ /HP C Compiler/ }.first + if description + output = description.split + c[:hpcc] = Mash.new + c[:hpcc][:version] = output[1] if output.size >= 1 + c[:hpcc][:description] = description.strip + end + end + + languages[:c] = c if c.keys.length > 0 end end - -languages[:c] = c if c.keys.length > 0 diff --git a/lib/ohai/plugins/chef.rb b/lib/ohai/plugins/chef.rb index 2b36a219..1fa6c585 100644 --- a/lib/ohai/plugins/chef.rb +++ b/lib/ohai/plugins/chef.rb @@ -17,9 +17,14 @@ # require 'chef/version' -provides "chef" -self[:chef_packages] = Mash.new unless self[:chef_packages] -self[:chef_packages][:chef] = Mash.new -self[:chef_packages][:chef][:version] = Chef::VERSION -self[:chef_packages][:chef][:chef_root] = Chef::CHEF_ROOT +Ohai.plugin(:Chef) do + provides "chef" + + collect_data do + self[:chef_packages] = Mash.new unless self[:chef_packages] + self[:chef_packages][:chef] = Mash.new + self[:chef_packages][:chef][:version] = Chef::VERSION + self[:chef_packages][:chef][:chef_root] = Chef::CHEF_ROOT + end +end diff --git a/lib/ohai/plugins/cloud.rb b/lib/ohai/plugins/cloud.rb index 9d0001af..e8019074 100644 --- a/lib/ohai/plugins/cloud.rb +++ b/lib/ohai/plugins/cloud.rb @@ -14,234 +14,238 @@ # See the License for the specific language governing permissions and # limitations under the License. -provides "cloud" - -require_plugin "ec2" -require_plugin "gce" -require_plugin "rackspace" -require_plugin "eucalyptus" -require_plugin "linode" -require_plugin "openstack" -require_plugin "azure" - -# Make top-level cloud hashes -# -def create_objects - cloud Mash.new - cloud[:public_ips] = Array.new - cloud[:private_ips] = Array.new -end -#--------------------------------------- -# Google Compute Engine (gce) -#-------------------------------------- - -def on_gce? - gce != nil -end -def get_gce_values - cloud[:public_ipv4] = [] - cloud[:local_ipv4] = [] - - public_ips = gce['network']["networkInterface"].collect do |interface| - if interface.has_key?('accessConfiguration') - interface['accessConfiguration'].collect{|ac| ac['externalIp']} +Ohai.plugin(:Cloud) do + provides "cloud" + + depends "ec2" + depends "gce" + depends "rackspace" + depends "eucalyptus" + depends "linode" + depends "openstack" + depends "azure" + + # Make top-level cloud hashes + # + def create_objects + cloud Mash.new + cloud[:public_ips] = Array.new + cloud[:private_ips] = Array.new + end + #--------------------------------------- + # Google Compute Engine (gce) + #-------------------------------------- + + def on_gce? + gce != nil + end + def get_gce_values + cloud[:public_ipv4] = [] + cloud[:local_ipv4] = [] + + public_ips = gce['network']["networkInterface"].collect do |interface| + if interface.has_key?('accessConfiguration') + interface['accessConfiguration'].collect{|ac| ac['externalIp']} + end + end.flatten.compact + + private_ips = gce['network']["networkInterface"].collect do |interface| + interface['ip'] + end.compact + + cloud[:public_ips] += public_ips + cloud[:private_ips] += private_ips + cloud[:public_ipv4] += public_ips + cloud[:public_hostname] = nil + cloud[:local_ipv4] += private_ips + cloud[:local_hostname] = gce['hostname'] + cloud[:provider] = "gce" + end + + # ---------------------------------------- + # ec2 + # ---------------------------------------- + + # Is current cloud ec2? + # + # === Return + # true:: If ec2 Hash is defined + # false:: Otherwise + def on_ec2? + ec2 != nil + end + + # Fill cloud hash with ec2 values + def get_ec2_values + cloud[:public_ips] << ec2['public_ipv4'] + cloud[:private_ips] << ec2['local_ipv4'] + cloud[:public_ipv4] = ec2['public_ipv4'] + cloud[:public_hostname] = ec2['public_hostname'] + cloud[:local_ipv4] = ec2['local_ipv4'] + cloud[:local_hostname] = ec2['local_hostname'] + cloud[:provider] = "ec2" + end + + # ---------------------------------------- + # rackspace + # ---------------------------------------- + + # Is current cloud rackspace? + # + # === Return + # true:: If rackspace Hash is defined + # false:: Otherwise + def on_rackspace? + rackspace != nil + end + + # Fill cloud hash with rackspace values + def get_rackspace_values + cloud[:public_ips] << rackspace['public_ipv4'] if rackspace['public_ipv4'] + cloud[:private_ips] << rackspace['local_ipv4'] if rackspace['local_ipv4'] + cloud[:public_ipv4] = rackspace['public_ipv4'] + cloud[:public_ipv6] = rackspace['public_ipv6'] + cloud[:public_hostname] = rackspace['public_hostname'] + cloud[:local_ipv4] = rackspace['local_ipv4'] + cloud[:local_ipv6] = rackspace['local_ipv6'] + cloud[:local_hostname] = rackspace['local_hostname'] + cloud[:provider] = "rackspace" + end + + # ---------------------------------------- + # linode + # ---------------------------------------- + + # Is current cloud linode? + # + # === Return + # true:: If linode Hash is defined + # false:: Otherwise + def on_linode? + linode != nil + end + + # Fill cloud hash with linode values + def get_linode_values + cloud[:public_ips] << linode['public_ip'] + cloud[:private_ips] << linode['private_ip'] + cloud[:public_ipv4] = linode['public_ipv4'] + cloud[:public_hostname] = linode['public_hostname'] + cloud[:local_ipv4] = linode['local_ipv4'] + cloud[:local_hostname] = linode['local_hostname'] + cloud[:provider] = "linode" + end + + # ---------------------------------------- + # eucalyptus + # ---------------------------------------- + + # Is current cloud eucalyptus? + # + # === Return + # true:: If eucalyptus Hash is defined + # false:: Otherwise + def on_eucalyptus? + eucalyptus != nil + end + + def get_eucalyptus_values + cloud[:public_ips] << eucalyptus['public_ipv4'] + cloud[:private_ips] << eucalyptus['local_ipv4'] + cloud[:public_ipv4] = eucalyptus['public_ipv4'] + cloud[:public_hostname] = eucalyptus['public_hostname'] + cloud[:local_ipv4] = eucalyptus['local_ipv4'] + cloud[:local_hostname] = eucalyptus['local_hostname'] + cloud[:provider] = "eucalyptus" + end + + # ---------------------------------------- + # openstack + # ---------------------------------------- + + # Is current cloud openstack-based? + # + # === Return + # true:: If openstack Hash is defined + # false:: Otherwise + def on_openstack? + openstack != nil + end + + # Fill cloud hash with openstack values + def get_openstack_values + cloud[:public_ips] << openstack['public_ipv4'] + cloud[:private_ips] << openstack['local_ipv4'] + cloud[:public_ipv4] = openstack['public_ipv4'] + cloud[:public_hostname] = openstack['public_hostname'] + cloud[:local_ipv4] = openstack['local_ipv4'] + cloud[:local_hostname] = openstack['local_hostname'] + cloud[:provider] = openstack['provider'] + end + + # ---------------------------------------- + # azure + # ---------------------------------------- + + # Is current cloud azure? + # + # === Return + # true:: If azure Hash is defined + # false:: Otherwise + def on_azure? + azure != nil + end + + # Fill cloud hash with azure values + def get_azure_values + cloud[:vm_name] = azure["vm_name"] + cloud[:public_ips] << azure['public_ip'] + cloud[:public_fqdn] = azure['public_fqdn'] + cloud[:public_ssh_port] = azure['public_ssh_port'] if azure['public_ssh_port'] + cloud[:public_winrm_port] = azure['public_winrm_port'] if azure['public_winrm_port'] + cloud[:provider] = "azure" + end + + collect_data do + # setup gce cloud + if on_gce? + create_objects + get_gce_values end - end.flatten.compact - - private_ips = gce['network']["networkInterface"].collect do |interface| - interface['ip'] - end.compact - - cloud[:public_ips] += public_ips - cloud[:private_ips] += private_ips - cloud[:public_ipv4] += public_ips - cloud[:public_hostname] = nil - cloud[:local_ipv4] += private_ips - cloud[:local_hostname] = gce['hostname'] - cloud[:provider] = "gce" -end - -# setup gce cloud -if on_gce? - create_objects - get_gce_values -end - -# ---------------------------------------- -# ec2 -# ---------------------------------------- - -# Is current cloud ec2? -# -# === Return -# true:: If ec2 Hash is defined -# false:: Otherwise -def on_ec2? - ec2 != nil -end - -# Fill cloud hash with ec2 values -def get_ec2_values - cloud[:public_ips] << ec2['public_ipv4'] - cloud[:private_ips] << ec2['local_ipv4'] - cloud[:public_ipv4] = ec2['public_ipv4'] - cloud[:public_hostname] = ec2['public_hostname'] - cloud[:local_ipv4] = ec2['local_ipv4'] - cloud[:local_hostname] = ec2['local_hostname'] - cloud[:provider] = "ec2" -end - -# setup ec2 cloud -if on_ec2? - create_objects - get_ec2_values -end - -# ---------------------------------------- -# rackspace -# ---------------------------------------- - -# Is current cloud rackspace? -# -# === Return -# true:: If rackspace Hash is defined -# false:: Otherwise -def on_rackspace? - rackspace != nil -end - -# Fill cloud hash with rackspace values -def get_rackspace_values - cloud[:public_ips] << rackspace['public_ipv4'] if rackspace['public_ipv4'] - cloud[:private_ips] << rackspace['local_ipv4'] if rackspace['local_ipv4'] - cloud[:public_ipv4] = rackspace['public_ipv4'] - cloud[:public_ipv6] = rackspace['public_ipv6'] - cloud[:public_hostname] = rackspace['public_hostname'] - cloud[:local_ipv4] = rackspace['local_ipv4'] - cloud[:local_ipv6] = rackspace['local_ipv6'] - cloud[:local_hostname] = rackspace['local_hostname'] - cloud[:provider] = "rackspace" -end - -# setup rackspace cloud -if on_rackspace? - create_objects - get_rackspace_values -end - -# ---------------------------------------- -# linode -# ---------------------------------------- - -# Is current cloud linode? -# -# === Return -# true:: If linode Hash is defined -# false:: Otherwise -def on_linode? - linode != nil -end - -# Fill cloud hash with linode values -def get_linode_values - cloud[:public_ips] << linode['public_ip'] - cloud[:private_ips] << linode['private_ip'] - cloud[:public_ipv4] = linode['public_ipv4'] - cloud[:public_hostname] = linode['public_hostname'] - cloud[:local_ipv4] = linode['local_ipv4'] - cloud[:local_hostname] = linode['local_hostname'] - cloud[:provider] = "linode" -end - -# setup linode cloud data -if on_linode? - create_objects - get_linode_values -end - -# ---------------------------------------- -# eucalyptus -# ---------------------------------------- - -# Is current cloud eucalyptus? -# -# === Return -# true:: If eucalyptus Hash is defined -# false:: Otherwise -def on_eucalyptus? - eucalyptus != nil -end - -def get_eucalyptus_values - cloud[:public_ips] << eucalyptus['public_ipv4'] - cloud[:private_ips] << eucalyptus['local_ipv4'] - cloud[:public_ipv4] = eucalyptus['public_ipv4'] - cloud[:public_hostname] = eucalyptus['public_hostname'] - cloud[:local_ipv4] = eucalyptus['local_ipv4'] - cloud[:local_hostname] = eucalyptus['local_hostname'] - cloud[:provider] = "eucalyptus" -end - -if on_eucalyptus? - create_objects - get_eucalyptus_values -end -# ---------------------------------------- -# openstack -# ---------------------------------------- - -# Is current cloud openstack-based? -# -# === Return -# true:: If openstack Hash is defined -# false:: Otherwise -def on_openstack? - openstack != nil -end + # setup ec2 cloud + if on_ec2? + create_objects + get_ec2_values + end -# Fill cloud hash with openstack values -def get_openstack_values - cloud[:public_ips] << openstack['public_ipv4'] - cloud[:private_ips] << openstack['local_ipv4'] - cloud[:public_ipv4] = openstack['public_ipv4'] - cloud[:public_hostname] = openstack['public_hostname'] - cloud[:local_ipv4] = openstack['local_ipv4'] - cloud[:local_hostname] = openstack['local_hostname'] - cloud[:provider] = openstack['provider'] -end + # setup rackspace cloud + if on_rackspace? + create_objects + get_rackspace_values + end -# setup openstack cloud -if on_openstack? - create_objects - get_openstack_values -end + # setup linode cloud data + if on_linode? + create_objects + get_linode_values + end -# ---------------------------------------- -# azure -# ---------------------------------------- + if on_eucalyptus? + create_objects + get_eucalyptus_values + end -# Is current cloud azure? -# -# === Return -# true:: If azure Hash is defined -# false:: Otherwise -def on_azure? - azure != nil -end + # setup openstack cloud + if on_openstack? + create_objects + get_openstack_values + end -# Fill cloud hash with azure values -def get_azure_values - cloud[:vm_name] = azure["vm_name"] - cloud[:public_ips] << azure['public_ip'] - cloud[:public_fqdn] = azure['public_fqdn'] - cloud[:public_ssh_port] = azure['public_ssh_port'] if azure['public_ssh_port'] - cloud[:public_winrm_port] = azure['public_winrm_port'] if azure['public_winrm_port'] - cloud[:provider] = "azure" + # setup azure cloud data + if on_azure? + create_objects + get_azure_values + end + end end - -# setup azure cloud data -if on_azure? - create_objects - get_azure_values -end
\ No newline at end of file diff --git a/lib/ohai/plugins/command.rb b/lib/ohai/plugins/command.rb index 4578a385..930846a5 100644 --- a/lib/ohai/plugins/command.rb +++ b/lib/ohai/plugins/command.rb @@ -16,6 +16,10 @@ # limitations under the License. # -provides "command" +Ohai.plugin(:Command) do + provides "command" -command Mash.new
\ No newline at end of file + collect_data do + command Mash.new + end +end diff --git a/lib/ohai/plugins/darwin/cpu.rb b/lib/ohai/plugins/darwin/cpu.rb index 37c4c573..45b1c0ec 100644 --- a/lib/ohai/plugins/darwin/cpu.rb +++ b/lib/ohai/plugins/darwin/cpu.rb @@ -16,8 +16,12 @@ # limitations under the License. # -provides "cpu" +Ohai.plugin(:DarwinCpu) do + provides "cpu" -cpu Mash.new -cpu[:real] = from("sysctl -n hw.physicalcpu").to_i -cpu[:total] = from("sysctl -n hw.logicalcpu").to_i + collect_data do + cpu Mash.new + cpu[:real] = from("sysctl -n hw.physicalcpu").to_i + cpu[:total] = from("sysctl -n hw.logicalcpu").to_i + end +end diff --git a/lib/ohai/plugins/darwin/filesystem.rb b/lib/ohai/plugins/darwin/filesystem.rb index 65abebff..3a03f7fb 100644 --- a/lib/ohai/plugins/darwin/filesystem.rb +++ b/lib/ohai/plugins/darwin/filesystem.rb @@ -16,42 +16,46 @@ # limitations under the License. # -provides "filesystem" +Ohai.plugin(:DarwinFilesystem) do + provides "filesystem" -fs = Mash.new + collect_data do + fs = Mash.new -block_size = 0 -popen4("df") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^Filesystem\s+(\d+)-/ - block_size = $1.to_i - next - when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ - filesystem = $1 - fs[filesystem] = Mash.new - fs[filesystem][:block_size] = block_size - fs[filesystem][:kb_size] = $2.to_i / (1024 / block_size) - fs[filesystem][:kb_used] = $3.to_i / (1024 / block_size) - fs[filesystem][:kb_available] = $4.to_i / (1024 / block_size) - fs[filesystem][:percent_used] = $5 - fs[filesystem][:mount] = $6 + block_size = 0 + popen4("df") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^Filesystem\s+(\d+)-/ + block_size = $1.to_i + next + when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ + filesystem = $1 + fs[filesystem] = Mash.new + fs[filesystem][:block_size] = block_size + fs[filesystem][:kb_size] = $2.to_i / (1024 / block_size) + fs[filesystem][:kb_used] = $3.to_i / (1024 / block_size) + fs[filesystem][:kb_available] = $4.to_i / (1024 / block_size) + fs[filesystem][:percent_used] = $5 + fs[filesystem][:mount] = $6 + end + end end - end -end -popen4("mount") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/ - filesystem = $1 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem][:mount] = $2 - fs[filesystem][:fs_type] = $3 - fs[filesystem][:mount_options] = $4.split(/,\s*/) + popen4("mount") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/ + filesystem = $1 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem][:mount] = $2 + fs[filesystem][:fs_type] = $3 + fs[filesystem][:mount_options] = $4.split(/,\s*/) + end + end end + + filesystem fs end end - -filesystem fs
\ No newline at end of file diff --git a/lib/ohai/plugins/darwin/hostname.rb b/lib/ohai/plugins/darwin/hostname.rb index ca8e2757..35bc62b4 100644 --- a/lib/ohai/plugins/darwin/hostname.rb +++ b/lib/ohai/plugins/darwin/hostname.rb @@ -16,7 +16,11 @@ # limitations under the License. # -provides "fqdn", "hostname" +Ohai.plugin(:DarwinHostname) do + provides "fqdn", "hostname" -hostname from("hostname -s") -fqdn from("hostname")
\ No newline at end of file + collect_data do + hostname from("hostname -s") + fqdn from("hostname") + end +end diff --git a/lib/ohai/plugins/darwin/kernel.rb b/lib/ohai/plugins/darwin/kernel.rb index c4d50ffa..b42b4c6f 100644 --- a/lib/ohai/plugins/darwin/kernel.rb +++ b/lib/ohai/plugins/darwin/kernel.rb @@ -16,22 +16,26 @@ # limitations under the License. # -provides "kernel" +Ohai.plugin(:DarwinKernel) do + provides "kernel" -kernel[:os] = kernel[:name] + collect_data do + kernel[:os] = kernel[:name] -if from("sysctl -n hw.optional.x86_64").to_i == 1 - kernel[:machine] = 'x86_64' -end + if from("sysctl -n hw.optional.x86_64").to_i == 1 + kernel[:machine] = 'x86_64' + end -kext = Mash.new -popen4("kextstat -k -l") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /(\d+)\s+(\d+)\s+0x[0-9a-f]+\s+0x([0-9a-f]+)\s+0x[0-9a-f]+\s+([a-zA-Z0-9\.]+) \(([0-9\.]+)\)/ - kext[$4] = { :version => $5, :size => $3.hex, :index => $1, :refcount => $2 } + kext = Mash.new + popen4("kextstat -k -l") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /(\d+)\s+(\d+)\s+0x[0-9a-f]+\s+0x([0-9a-f]+)\s+0x[0-9a-f]+\s+([a-zA-Z0-9\.]+) \(([0-9\.]+)\)/ + kext[$4] = { :version => $5, :size => $3.hex, :index => $1, :refcount => $2 } + end + end end + + kernel[:modules] = kext end end - -kernel[:modules] = kext diff --git a/lib/ohai/plugins/darwin/network.rb b/lib/ohai/plugins/darwin/network.rb index cc2b1243..4530f5ba 100644 --- a/lib/ohai/plugins/darwin/network.rb +++ b/lib/ohai/plugins/darwin/network.rb @@ -16,182 +16,188 @@ # limitations under the License. # -provides "network", "counters/network" - require 'scanf' -from("route -n get default").split("\n").each do |line| - if line =~ /(\w+): ([\w\.]+)/ - case $1 - when "gateway" - network[:default_gateway] = $2 - when "interface" - network[:default_interface] = $2 - end - end -end +Ohai.plugin(:DarwinNetwork) do + provides "network", "counters/network" -def parse_media(media_string) - media = Hash.new - line_array = media_string.split(' ') + def parse_media(media_string) + media = Hash.new + line_array = media_string.split(' ') - 0.upto(line_array.length - 1) do |i| - unless line_array[i].eql?("none") + 0.upto(line_array.length - 1) do |i| + unless line_array[i].eql?("none") - if line_array[i + 1] =~ /^\<([a-zA-Z\-\,]+)\>$/ - media[line_array[i]] = Hash.new unless media.has_key?(line_array[i]) - if media[line_array[i]].has_key?("options") - $1.split(",").each do |opt| - media[line_array[i]]["options"] << opt unless media[line_array[i]]["options"].include?(opt) + if line_array[i + 1] =~ /^\<([a-zA-Z\-\,]+)\>$/ + media[line_array[i]] = Hash.new unless media.has_key?(line_array[i]) + if media[line_array[i]].has_key?("options") + $1.split(",").each do |opt| + media[line_array[i]]["options"] << opt unless media[line_array[i]]["options"].include?(opt) + end + else + media[line_array[i]]["options"] = $1.split(",") end else - media[line_array[i]]["options"] = $1.split(",") + if line_array[i].eql?("autoselect") + media["autoselect"] = Hash.new unless media.has_key?("autoselect") + media["autoselect"]["options"] = [] + end end else - if line_array[i].eql?("autoselect") - media["autoselect"] = Hash.new unless media.has_key?("autoselect") - media["autoselect"]["options"] = [] - end + media["none"] = { "options" => [] } end - else - media["none"] = { "options" => [] } end - end - media -end + media + end -def encaps_lookup(ifname) - return "Loopback" if ifname.eql?("lo") - return "1394" if ifname.eql?("fw") - return "IPIP" if ifname.eql?("gif") - return "6to4" if ifname.eql?("stf") - return "dot1q" if ifname.eql?("vlan") - "Unknown" -end + def encaps_lookup(ifname) + return "Loopback" if ifname.eql?("lo") + return "1394" if ifname.eql?("fw") + return "IPIP" if ifname.eql?("gif") + return "6to4" if ifname.eql?("stf") + return "dot1q" if ifname.eql?("vlan") + "Unknown" + end -def scope_lookup(scope) - return "Node" if scope.eql?("::1") - return "Link" if scope.match(/^fe80\:/) - return "Site" if scope.match(/^fec0\:/) - "Global" -end + def scope_lookup(scope) + return "Node" if scope.eql?("::1") + return "Link" if scope.match(/^fe80\:/) + return "Site" if scope.match(/^fec0\:/) + "Global" + end -def excluded_setting?(setting) - setting.match('_sw_cksum') -end + def excluded_setting?(setting) + setting.match('_sw_cksum') + end -def locate_interface(ifaces, ifname, mac) - return ifname unless ifaces[ifname].nil? - # oh well, time to go hunting! - return ifname.chop if ifname.match /\*$/ - ifaces.keys.each do |ifc| - ifaces[ifc][:addresses].keys.each do |addr| - return ifc if addr.eql? mac + def locate_interface(ifaces, ifname, mac) + return ifname unless ifaces[ifname].nil? + # oh well, time to go hunting! + return ifname.chop if ifname.match /\*$/ + ifaces.keys.each do |ifc| + ifaces[ifc][:addresses].keys.each do |addr| + return ifc if addr.eql? mac + end end + + nil end - - nil -end -iface = Mash.new -popen4("ifconfig -a") do |pid, stdin, stdout, stderr| - stdin.close - cint = nil - stdout.each do |line| - if line =~ /^([0-9a-zA-Z\.\:\-]+): \S+ mtu (\d+)$/ - cint = $1 - iface[cint] = Mash.new unless iface[cint]; iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:mtu] = $2 - if line =~ /\sflags\=\d+\<((UP|BROADCAST|DEBUG|SMART|SIMPLEX|LOOPBACK|POINTOPOINT|NOTRAILERS|RUNNING|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC|,)+)\>\s/ - flags = $1.split(',') - else - flags = Array.new - end - iface[cint][:flags] = flags.flatten - if cint =~ /^(\w+)(\d+.*)/ - iface[cint][:type] = $1 - iface[cint][:number] = $2 - iface[cint][:encapsulation] = encaps_lookup($1) + collect_data do + network Mash.new + + from("route -n get default").split("\n").each do |line| + if line =~ /(\w+): ([\w\.]+)/ + case $1 + when "gateway" + network[:default_gateway] = $2 + when "interface" + network[:default_interface] = $2 + end end end - if line =~ /^\s+ether ([0-9a-f\:]+)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "lladdr" } - iface[cint][:encapsulation] = "Ethernet" - end - if line =~ /^\s+lladdr ([0-9a-f\:]+)\s/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "lladdr" } - end - if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask 0x(([0-9a-f]){1,8})\s*$/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => $2.scanf('%2x'*4)*"."} - end - if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask 0x(([0-9a-f]){1,8}) broadcast (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => $2.scanf('%2x'*4)*".", "broadcast" => $4 } - end - if line =~ /\s+inet6 ([a-f0-9\:]+)(\s*|(\%[a-z0-9]+)\s*) prefixlen (\d+)\s*/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $4 , "scope" => scope_lookup($1) } - end - if line =~ /\s+inet6 ([a-f0-9\:]+)(\s*|(\%[a-z0-9]+)\s*) prefixlen (\d+) scopeid 0x([a-f0-9]+)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $4 , "scope" => scope_lookup($1) } - end - if line =~ /^\s+media: ((\w+)|(\w+ [a-zA-Z0-9\-\<\>]+)) status: (\w+)/ - iface[cint][:media] = Mash.new unless iface[cint][:media] - iface[cint][:media][:selected] = parse_media($1) - iface[cint][:status] = $4 - end - if line =~ /^\s+supported media: (.*)/ - iface[cint][:media] = Mash.new unless iface[cint][:media] - iface[cint][:media][:supported] = parse_media($1) + + iface = Mash.new + popen4("ifconfig -a") do |pid, stdin, stdout, stderr| + stdin.close + cint = nil + stdout.each do |line| + if line =~ /^([0-9a-zA-Z\.\:\-]+): \S+ mtu (\d+)$/ + cint = $1 + iface[cint] = Mash.new unless iface[cint]; iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:mtu] = $2 + if line =~ /\sflags\=\d+\<((UP|BROADCAST|DEBUG|SMART|SIMPLEX|LOOPBACK|POINTOPOINT|NOTRAILERS|RUNNING|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC|,)+)\>\s/ + flags = $1.split(',') + else + flags = Array.new + end + iface[cint][:flags] = flags.flatten + if cint =~ /^(\w+)(\d+.*)/ + iface[cint][:type] = $1 + iface[cint][:number] = $2 + iface[cint][:encapsulation] = encaps_lookup($1) + end + end + if line =~ /^\s+ether ([0-9a-f\:]+)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "lladdr" } + iface[cint][:encapsulation] = "Ethernet" + end + if line =~ /^\s+lladdr ([0-9a-f\:]+)\s/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "lladdr" } + end + if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask 0x(([0-9a-f]){1,8})\s*$/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => $2.scanf('%2x'*4)*"."} + end + if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask 0x(([0-9a-f]){1,8}) broadcast (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => $2.scanf('%2x'*4)*".", "broadcast" => $4 } + end + if line =~ /\s+inet6 ([a-f0-9\:]+)(\s*|(\%[a-z0-9]+)\s*) prefixlen (\d+)\s*/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $4 , "scope" => scope_lookup($1) } + end + if line =~ /\s+inet6 ([a-f0-9\:]+)(\s*|(\%[a-z0-9]+)\s*) prefixlen (\d+) scopeid 0x([a-f0-9]+)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $4 , "scope" => scope_lookup($1) } + end + if line =~ /^\s+media: ((\w+)|(\w+ [a-zA-Z0-9\-\<\>]+)) status: (\w+)/ + iface[cint][:media] = Mash.new unless iface[cint][:media] + iface[cint][:media][:selected] = parse_media($1) + iface[cint][:status] = $4 + end + if line =~ /^\s+supported media: (.*)/ + iface[cint][:media] = Mash.new unless iface[cint][:media] + iface[cint][:media][:supported] = parse_media($1) + end + end end - end -end -popen4("arp -an") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^\S+ \((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) on ([a-zA-Z0-9\.\:\-]+).*\[(\w+)\]/ - # MAC addr really should be normalized to include all the zeroes. - next if iface[$3].nil? # this should never happen - iface[$3][:arp] = Mash.new unless iface[$3][:arp] - iface[$3][:arp][$1] = $2 + popen4("arp -an") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^\S+ \((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) on ([a-zA-Z0-9\.\:\-]+).*\[(\w+)\]/ + # MAC addr really should be normalized to include all the zeroes. + next if iface[$3].nil? # this should never happen + iface[$3][:arp] = Mash.new unless iface[$3][:arp] + iface[$3][:arp][$1] = $2 + end + end end - end -end -settings = Mash.new -popen4("sysctl net") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^([a-zA-Z0-9\.\_]+)\: (.*)/ - # should normalize names between platforms for the same settings. - settings[$1] = $2 unless excluded_setting?($1) + settings = Mash.new + popen4("sysctl net") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^([a-zA-Z0-9\.\_]+)\: (.*)/ + # should normalize names between platforms for the same settings. + settings[$1] = $2 unless excluded_setting?($1) + end + end end - end -end -network[:settings] = settings -network[:interfaces] = iface - -net_counters = Mash.new -popen4("netstat -i -d -l -b -n") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^([a-zA-Z0-9\.\:\-\*]+)\s+\d+\s+\<[a-zA-Z0-9\#]+\>\s+([a-f0-9\:]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ || - line =~ /^([a-zA-Z0-9\.\:\-\*]+)\s+\d+\s+\<[a-zA-Z0-9\#]+\>(\s+)(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ - ifname = locate_interface(iface, $1, $2) - next if iface[ifname].nil? # this shouldn't happen, but just in case - net_counters[ifname] = Mash.new unless net_counters[ifname] - net_counters[ifname] = { :rx => { :bytes => $5, :packets => $3, :errors => $4, :drop => 0, :overrun => 0, :frame => 0, :compressed => 0, :multicast => 0 }, - :tx => { :bytes => $8, :packets => $6, :errors => $7, :drop => 0, :overrun => 0, :collisions => $9, :carrier => 0, :compressed => 0 } - } + network[:settings] = settings + network[:interfaces] = iface + + net_counters = Mash.new + popen4("netstat -i -d -l -b -n") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^([a-zA-Z0-9\.\:\-\*]+)\s+\d+\s+\<[a-zA-Z0-9\#]+\>\s+([a-f0-9\:]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ || + line =~ /^([a-zA-Z0-9\.\:\-\*]+)\s+\d+\s+\<[a-zA-Z0-9\#]+\>(\s+)(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ + ifname = locate_interface(iface, $1, $2) + next if iface[ifname].nil? # this shouldn't happen, but just in case + net_counters[ifname] = Mash.new unless net_counters[ifname] + net_counters[ifname] = { :rx => { :bytes => $5, :packets => $3, :errors => $4, :drop => 0, :overrun => 0, :frame => 0, :compressed => 0, :multicast => 0 }, + :tx => { :bytes => $8, :packets => $6, :errors => $7, :drop => 0, :overrun => 0, :collisions => $9, :carrier => 0, :compressed => 0 } + } + end + end end + + counters[:network][:interfaces] = net_counters end end - -counters[:network][:interfaces] = net_counters diff --git a/lib/ohai/plugins/darwin/platform.rb b/lib/ohai/plugins/darwin/platform.rb index 0841aa96..5ed7a98b 100644 --- a/lib/ohai/plugins/darwin/platform.rb +++ b/lib/ohai/plugins/darwin/platform.rb @@ -16,23 +16,27 @@ # limitations under the License. # -provides "platform", "platform_version", "platform_build", "platform_family" +Ohai.plugin(:DarwinPlatform) do + provides "platform", "platform_version", "platform_build", "platform_family" -popen4("/usr/bin/sw_vers") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^ProductName:\s+(.+)$/ - macname = $1 - macname.downcase! - macname.gsub!(" ", "_") - platform macname - when /^ProductVersion:\s+(.+)$/ - platform_version $1 - when /^BuildVersion:\s+(.+)$/ - platform_build $1 + collect_data do + popen4("/usr/bin/sw_vers") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^ProductName:\s+(.+)$/ + macname = $1 + macname.downcase! + macname.gsub!(" ", "_") + platform macname + when /^ProductVersion:\s+(.+)$/ + platform_version $1 + when /^BuildVersion:\s+(.+)$/ + platform_build $1 + end + end end + + platform_family "mac_os_x" end end - -platform_family "mac_os_x" diff --git a/lib/ohai/plugins/darwin/ps.rb b/lib/ohai/plugins/darwin/ps.rb index 16f2e536..dc653e79 100644 --- a/lib/ohai/plugins/darwin/ps.rb +++ b/lib/ohai/plugins/darwin/ps.rb @@ -16,8 +16,12 @@ # limitations under the License. # -provides "command/ps" +Ohai.plugin(:DarwinPs) do + provides "command/ps" -require_plugin 'command' + depends 'command' -command[:ps] = 'ps -ef'
\ No newline at end of file + collect_data do + command[:ps] = 'ps -ef' + end +end diff --git a/lib/ohai/plugins/darwin/system_profiler.rb b/lib/ohai/plugins/darwin/system_profiler.rb index 9eacd63d..0a3f40dd 100644 --- a/lib/ohai/plugins/darwin/system_profiler.rb +++ b/lib/ohai/plugins/darwin/system_profiler.rb @@ -15,56 +15,61 @@ # See the License for the specific language governing permissions and # limitations under the License. # -provides "system_profile" -begin - require 'plist' +Ohai.plugin(:DarwinSystemProfile) do + provides "system_profile" - system_profile Array.new - items Array.new - detail_level = { - 'mini' => [ - "SPParallelATAData", - "SPAudioData", - "SPBluetoothData", - "SPCardReaderData", - "SPDiagnosticsData", - "SPDiscBurningData", - "SPEthernetData", - "SPFibreChannelData", - "SPFireWireData", - "SPDisplaysData", - "SPHardwareRAIDData", - "SPMemoryData", - "SPModemData", - "SPNetworkData", - "SPPCIData", - "SPParallelSCSIData", - "SPPrintersSoftwareData", - "SPPrintersData", - "SPSASData", - "SPSerialATAData", - "SPSoftwareData", - "SPThunderboltData", - "SPUSBData", - "SPWWANData", - "SPAirPortData" - ], - 'full' => [ - "SPHardwareDataType" - ] - } + collect_data do + begin + require 'plist' - detail_level.each do |level, data_types| - popen4("system_profiler -xml -detailLevel #{level} #{data_types.join(' ')}") do |pid, stdin, stdout, stderr| - stdin.close - Plist::parse_xml(stdout.read).each do |e| - items << e + system_profile Array.new + items Array.new + detail_level = { + 'mini' => [ + "SPParallelATAData", + "SPAudioData", + "SPBluetoothData", + "SPCardReaderData", + "SPDiagnosticsData", + "SPDiscBurningData", + "SPEthernetData", + "SPFibreChannelData", + "SPFireWireData", + "SPDisplaysData", + "SPHardwareRAIDData", + "SPMemoryData", + "SPModemData", + "SPNetworkData", + "SPPCIData", + "SPParallelSCSIData", + "SPPrintersSoftwareData", + "SPPrintersData", + "SPSASData", + "SPSerialATAData", + "SPSoftwareData", + "SPThunderboltData", + "SPUSBData", + "SPWWANData", + "SPAirPortData" + ], + 'full' => [ + "SPHardwareDataType" + ] + } + + detail_level.each do |level, data_types| + popen4("system_profiler -xml -detailLevel #{level} #{data_types.join(' ')}") do |pid, stdin, stdout, stderr| + stdin.close + Plist::parse_xml(stdout.read).each do |e| + items << e + end + end end + + system_profile items.sort_by { |h| h['_dataType'] } + rescue LoadError => e + Ohai::Log.debug("Can't load gem: #{e})") end end - - system_profile items.sort_by { |h| h['_dataType'] } -rescue LoadError => e - Ohai::Log.debug("Can't load gem: #{e})") end diff --git a/lib/ohai/plugins/darwin/uptime.rb b/lib/ohai/plugins/darwin/uptime.rb index ea258ec4..44011408 100644 --- a/lib/ohai/plugins/darwin/uptime.rb +++ b/lib/ohai/plugins/darwin/uptime.rb @@ -16,17 +16,20 @@ # limitations under the License. # -provides "uptime", "uptime_seconds" +Ohai.plugin(:DarwinUptime) do + provides "uptime", "uptime_seconds" -# kern.boottime: { sec = 1232765114, usec = 823118 } Fri Jan 23 18:45:14 2009 + # kern.boottime: { sec = 1232765114, usec = 823118 } Fri Jan 23 18:45:14 2009 -popen4("/usr/sbin/sysctl kern.boottime") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /kern.boottime:\D+(\d+)/ - uptime_seconds Time.new.to_i - $1.to_i - uptime seconds_to_human(uptime_seconds) + collect_data do + popen4("/usr/sbin/sysctl kern.boottime") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /kern.boottime:\D+(\d+)/ + uptime_seconds Time.new.to_i - $1.to_i + uptime seconds_to_human(uptime_seconds) + end + end end end end - diff --git a/lib/ohai/plugins/dmi.rb b/lib/ohai/plugins/dmi.rb index b892ebcf..da2566e9 100644 --- a/lib/ohai/plugins/dmi.rb +++ b/lib/ohai/plugins/dmi.rb @@ -18,108 +18,112 @@ require "ohai/plugins/dmi_common" -provides "dmi" - -# dmidecode does not return data without access to /dev/mem (or its equivalent) - -dmi Mash.new - -# all output lines should fall within one of these patterns -handle_line = /^Handle (0x[0-9A-F]{4}), DMI type (\d+), (\d+) bytes/ -type_line = /^([A-Z][a-zA-Z ]+)( Information)?/ -blank_line = /^\s*$/ -data_line = /^\t([^:]+):(?: (.*))?/ -extended_data_line = /^\t\t(.+)/ -# first lines may contain some interesting information: -# # dmidecode 2.10 -# SMBIOS 2.5 present. -# 5 structures occupying 352 bytes. -# Table at 0x000E1000. -dmidecode_version_line = /^# dmidecode (\d+\.\d+)/ -smbios_version_line = /^SMBIOS (\d+\.\d+) present\./ -structures_line = /^(\d+) structures occupying (\d+) bytes\./ -table_location_line = /^Table at (0x[0-9A-E]+)\./ - -dmi_record = nil -field = nil - -popen4("dmidecode") do |pid, stdin, stdout, stderr| - stdin.close - - # ==== EXAMPLE RECORD: ==== - #Handle 0x0000, DMI type 0, 24 bytes - #BIOS Information - # Vendor: American Megatrends Inc. - # Version: 080012 - # ... similar lines trimmed - # Characteristics: - # ISA is supported - # PCI is supported - # ... similar lines trimmed - stdout.each do |line| - next if blank_line.match(line) - - if dmidecode_version = dmidecode_version_line.match(line) - dmi[:dmidecode_version] = dmidecode_version[1] - - elsif smbios_version = smbios_version_line.match(line) - dmi[:smbios_version] = smbios_version[1] - - elsif structures = structures_line.match(line) - dmi[:structures] = Mash.new - dmi[:structures][:count] = structures[1] - dmi[:structures][:size] = structures[2] - - elsif table_location = table_location_line.match(line) - dmi[:table_location] = table_location[1] - - elsif handle = handle_line.match(line) - # Don't overcapture for now (OHAI-260) - next unless DMI::IdToCapture.include?(handle[2].to_i) - - dmi_record = {:type => DMI.id_lookup(handle[2])} - - dmi[dmi_record[:type]] = Mash.new unless dmi.has_key?(dmi_record[:type]) - dmi[dmi_record[:type]][:all_records] = [] unless dmi[dmi_record[:type]].has_key?(:all_records) - dmi_record[:position] = dmi[dmi_record[:type]][:all_records].length - dmi[dmi_record[:type]][:all_records].push(Mash.new) - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:record_id] = handle[1] - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:size] = handle[2] - field = nil - - elsif type = type_line.match(line) - if dmi_record == nil - Ohai::Log.debug("unexpected data line found before header; discarding:\n#{line}") - next +Ohai.plugin(:Dmi) do + provides "dmi" + + # dmidecode does not return data without access to /dev/mem (or its equivalent) + + collect_data do + dmi Mash.new + + # all output lines should fall within one of these patterns + handle_line = /^Handle (0x[0-9A-F]{4}), DMI type (\d+), (\d+) bytes/ + type_line = /^([A-Z][a-zA-Z ]+)( Information)?/ + blank_line = /^\s*$/ + data_line = /^\t([^:]+):(?: (.*))?/ + extended_data_line = /^\t\t(.+)/ + # first lines may contain some interesting information: + # # dmidecode 2.10 + # SMBIOS 2.5 present. + # 5 structures occupying 352 bytes. + # Table at 0x000E1000. + dmidecode_version_line = /^# dmidecode (\d+\.\d+)/ + smbios_version_line = /^SMBIOS (\d+\.\d+) present\./ + structures_line = /^(\d+) structures occupying (\d+) bytes\./ + table_location_line = /^Table at (0x[0-9A-E]+)\./ + + dmi_record = nil + field = nil + + popen4("dmidecode") do |pid, stdin, stdout, stderr| + stdin.close + + # ==== EXAMPLE RECORD: ==== + #Handle 0x0000, DMI type 0, 24 bytes + #BIOS Information + # Vendor: American Megatrends Inc. + # Version: 080012 + # ... similar lines trimmed + # Characteristics: + # ISA is supported + # PCI is supported + # ... similar lines trimmed + stdout.each do |line| + next if blank_line.match(line) + + if dmidecode_version = dmidecode_version_line.match(line) + dmi[:dmidecode_version] = dmidecode_version[1] + + elsif smbios_version = smbios_version_line.match(line) + dmi[:smbios_version] = smbios_version[1] + + elsif structures = structures_line.match(line) + dmi[:structures] = Mash.new + dmi[:structures][:count] = structures[1] + dmi[:structures][:size] = structures[2] + + elsif table_location = table_location_line.match(line) + dmi[:table_location] = table_location[1] + + elsif handle = handle_line.match(line) + # Don't overcapture for now (OHAI-260) + next unless DMI::IdToCapture.include?(handle[2].to_i) + + dmi_record = {:type => DMI.id_lookup(handle[2])} + + dmi[dmi_record[:type]] = Mash.new unless dmi.has_key?(dmi_record[:type]) + dmi[dmi_record[:type]][:all_records] = [] unless dmi[dmi_record[:type]].has_key?(:all_records) + dmi_record[:position] = dmi[dmi_record[:type]][:all_records].length + dmi[dmi_record[:type]][:all_records].push(Mash.new) + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:record_id] = handle[1] + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:size] = handle[2] + field = nil + + elsif type = type_line.match(line) + if dmi_record == nil + Ohai::Log.debug("unexpected data line found before header; discarding:\n#{line}") + next + end + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:application_identifier] = type[1] + + elsif data = data_line.match(line) + if dmi_record == nil + Ohai::Log.debug("unexpected data line found before header; discarding:\n#{line}") + next + end + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][data[1]] = data[2] + field = data[1] + + elsif extended_data = extended_data_line.match(line) + if dmi_record == nil + Ohai::Log.debug("unexpected extended data line found before header; discarding:\n#{line}") + next + end + if field == nil + Ohai::Log.debug("unexpected extended data line found outside data section; discarding:\n#{line}") + next + end + # overwrite "raw" value with a new Mash + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field] = Mash.new unless dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field].class.to_s == 'Mash' + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field][extended_data[1]] = nil + + else + Ohai::Log.debug("unrecognized output line; discarding:\n#{line}") + + end end - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:application_identifier] = type[1] - - elsif data = data_line.match(line) - if dmi_record == nil - Ohai::Log.debug("unexpected data line found before header; discarding:\n#{line}") - next - end - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][data[1]] = data[2] - field = data[1] - - elsif extended_data = extended_data_line.match(line) - if dmi_record == nil - Ohai::Log.debug("unexpected extended data line found before header; discarding:\n#{line}") - next - end - if field == nil - Ohai::Log.debug("unexpected extended data line found outside data section; discarding:\n#{line}") - next - end - # overwrite "raw" value with a new Mash - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field] = Mash.new unless dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field].class.to_s == 'Mash' - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field][extended_data[1]] = nil - - else - Ohai::Log.debug("unrecognized output line; discarding:\n#{line}") - end + + DMI.convenience_keys(dmi) end end - -DMI.convenience_keys(dmi) diff --git a/lib/ohai/plugins/ec2.rb b/lib/ohai/plugins/ec2.rb index 9bede80d..dd000c6b 100644 --- a/lib/ohai/plugins/ec2.rb +++ b/lib/ohai/plugins/ec2.rb @@ -17,41 +17,44 @@ # See the License for the specific language governing permissions and # limitations under the License. -provides "ec2" - require 'ohai/mixin/ec2_metadata' +extend Ohai::Mixin::Ec2Metadata -require_plugin "hostname" -require_plugin "kernel" -require_plugin "network" +Ohai.plugin(:Ec2) do + provides "ec2" -extend Ohai::Mixin::Ec2Metadata + depends "fqdn", "domain" + depends "kernel" + depends "network", "counters/network" -def has_ec2_mac? - network[:interfaces].values.each do |iface| - unless iface[:arp].nil? - if iface[:arp].value?("fe:ff:ff:ff:ff:ff") - Ohai::Log.debug("has_ec2_mac? == true") - return true + def has_ec2_mac? + network[:interfaces].values.each do |iface| + unless iface[:arp].nil? + if iface[:arp].value?("fe:ff:ff:ff:ff:ff") + Ohai::Log.debug("has_ec2_mac? == true") + return true + end end end + Ohai::Log.debug("has_ec2_mac? == false") + false end - Ohai::Log.debug("has_ec2_mac? == false") - false -end -def looks_like_ec2? - # Try non-blocking connect so we don't "block" if - # the Xen environment is *not* EC2 - hint?('ec2') || has_ec2_mac? && can_metadata_connect?(EC2_METADATA_ADDR,80) -end + def looks_like_ec2? + # Try non-blocking connect so we don't "block" if + # the Xen environment is *not* EC2 + hint?('ec2') || has_ec2_mac? && can_metadata_connect?(EC2_METADATA_ADDR,80) + end -if looks_like_ec2? - Ohai::Log.debug("looks_like_ec2? == true") - ec2 Mash.new - fetch_metadata.each {|k, v| ec2[k] = v } - ec2[:userdata] = self.fetch_userdata -else - Ohai::Log.debug("looks_like_ec2? == false") - false + collect_data do + if looks_like_ec2? + Ohai::Log.debug("looks_like_ec2? == true") + ec2 Mash.new + fetch_metadata.each {|k, v| ec2[k] = v } + ec2[:userdata] = self.fetch_userdata + else + Ohai::Log.debug("looks_like_ec2? == false") + false + end + end end diff --git a/lib/ohai/plugins/erlang.rb b/lib/ohai/plugins/erlang.rb index db35cde1..44975f4e 100644 --- a/lib/ohai/plugins/erlang.rb +++ b/lib/ohai/plugins/erlang.rb @@ -16,25 +16,29 @@ # limitations under the License. # -provides "languages/erlang" +Ohai.plugin(:Erlang) do + provides "languages/erlang" -require_plugin "languages" + depends "languages" -output = nil + collect_data do + output = nil -erlang = Mash.new -status, stdout, stderr = run_command(:no_status_check => true, :command => "erl +V") + erlang = Mash.new + status, stdout, stderr = run_command(:no_status_check => true, :command => "erl +V") -if status == 0 - output = stderr.split - if output.length >= 6 - options = output[1] - options.gsub!(/(\(|\))/, '') - erlang[:version] = output[5] - erlang[:options] = options.split(',') - erlang[:emulator] = output[2].gsub!(/(\(|\))/, '') - if erlang[:version] and erlang[:options] and erlang[:emulator] - languages[:erlang] = erlang + if status == 0 + output = stderr.split + if output.length >= 6 + options = output[1] + options.gsub!(/(\(|\))/, '') + erlang[:version] = output[5] + erlang[:options] = options.split(',') + erlang[:emulator] = output[2].gsub!(/(\(|\))/, '') + if erlang[:version] and erlang[:options] and erlang[:emulator] + languages[:erlang] = erlang + end + end end end end diff --git a/lib/ohai/plugins/eucalyptus.rb b/lib/ohai/plugins/eucalyptus.rb index 1ee422bc..ba2b6ef7 100644 --- a/lib/ohai/plugins/eucalyptus.rb +++ b/lib/ohai/plugins/eucalyptus.rb @@ -17,49 +17,51 @@ # See the License for the specific language governing permissions and # limitations under the License. -provides "eucalyptus" - require 'ohai/mixin/ec2_metadata' +extend Ohai::Mixin::Ec2Metadata -require_plugin "hostname" -require_plugin "kernel" -require_plugin "network" +Ohai.plugin(:Eucalyptus) do + provides "eucalyptus" -extend Ohai::Mixin::Ec2Metadata + depends "fqdn", "domain" + depends "kernel" + depends "network" -def get_mac_address(addresses) - detected_addresses = addresses.detect { |address, keypair| keypair == {"family"=>"lladdr"} } - if detected_addresses - return detected_addresses.first - else - return "" + def get_mac_address(addresses) + detected_addresses = addresses.detect { |address, keypair| keypair == {"family"=>"lladdr"} } + if detected_addresses + return detected_addresses.first + else + return "" + end end -end -def has_euca_mac? - network[:interfaces].values.each do |iface| - has_mac = (get_mac_address(iface[:addresses]) =~ /^[dD]0:0[dD]:/) - Ohai::Log.debug("has_euca_mac? == #{!!has_mac}") - return true if has_mac - end + def has_euca_mac? + network[:interfaces].values.each do |iface| + has_mac = (get_mac_address(iface[:addresses]) =~ /^[dD]0:0[dD]:/) + Ohai::Log.debug("has_euca_mac? == #{!!has_mac}") + return true if has_mac + end - Ohai::Log.debug("has_euca_mac? == false") - false -end + Ohai::Log.debug("has_euca_mac? == false") + false + end -def looks_like_euca? - # Try non-blocking connect so we don't "block" if - # the Xen environment is *not* EC2 - hint?('eucalyptus') || has_euca_mac? && can_metadata_connect?(EC2_METADATA_ADDR,80) -end + def looks_like_euca? + # Try non-blocking connect so we don't "block" if + # the Xen environment is *not* EC2 + hint?('eucalyptus') || has_euca_mac? && can_metadata_connect?(EC2_METADATA_ADDR,80) + end -if looks_like_euca? - Ohai::Log.debug("looks_like_euca? == true") - eucalyptus Mash.new - self.fetch_metadata.each {|k, v| eucalyptus[k] = v } - eucalyptus[:userdata] = self.fetch_userdata -else - Ohai::Log.debug("looks_like_euca? == false") - false + collect_data do + if looks_like_euca? + Ohai::Log.debug("looks_like_euca? == true") + eucalyptus Mash.new + self.fetch_metadata.each {|k, v| eucalyptus[k] = v } + eucalyptus[:userdata] = self.fetch_userdata + else + Ohai::Log.debug("looks_like_euca? == false") + false + end + end end - diff --git a/lib/ohai/plugins/freebsd/cpu.rb b/lib/ohai/plugins/freebsd/cpu.rb index d4ae45d4..78ccb628 100644 --- a/lib/ohai/plugins/freebsd/cpu.rb +++ b/lib/ohai/plugins/freebsd/cpu.rb @@ -16,37 +16,41 @@ # limitations under the License. # -provides "cpu" +Ohai.plugin(:Cpu) do + provides "cpu" -# all dmesg output for smp I can find only provides info about a single processor -# identical processors is probably a hardware requirement so we'll duplicate data for each cpu -# old examples: http://www.bnv-bamberg.de/home/ba3294/smp/rbuild/index.htm -cpuinfo = Mash.new + collect_data do + # all dmesg output for smp I can find only provides info about a single processor + # identical processors is probably a hardware requirement so we'll duplicate data for each cpu + # old examples: http://www.bnv-bamberg.de/home/ba3294/smp/rbuild/index.htm + cpuinfo = Mash.new -# /var/run/dmesg.boot -#CPU: QEMU Virtual CPU version 0.9.1 (1862.02-MHz 686-class CPU) -# Origin = "GenuineIntel" Id = 0x623 Stepping = 3 -# Features=0x78bfbfd<FPU,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,CLFLUSH,MMX,FXSR,SSE,SSE2> -# Features2=0x80000001<SSE3,<b31>> + # /var/run/dmesg.boot + #CPU: QEMU Virtual CPU version 0.9.1 (1862.02-MHz 686-class CPU) + # Origin = "GenuineIntel" Id = 0x623 Stepping = 3 + # Features=0x78bfbfd<FPU,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,CLFLUSH,MMX,FXSR,SSE,SSE2> + # Features2=0x80000001<SSE3,<b31>> -File.open("/var/run/dmesg.boot").each do |line| - case line - when /CPU:\s+(.+) \(([\d.]+).+\)/ - cpuinfo["model_name"] = $1 - cpuinfo["mhz"] = $2 - when /Origin = "(.+)"\s+Id = (.+)\s+Stepping = (.+)/ - cpuinfo["vendor_id"] = $1 - cpuinfo["stepping"] = $3 - # These _should_ match /AMD Features2?/ lines as well - when /Features=.+<(.+)>/ - cpuinfo["flags"] = $1.downcase.split(',') - # Features2=0x80000001<SSE3,<b31>> - when /Features2=[a-f\dx]+<(.+)>/ - cpuinfo["flags"].concat($1.downcase.split(',')) - when /Logical CPUs per core: (\d+)/ - cpuinfo["cores"] = $1 + File.open("/var/run/dmesg.boot").each do |line| + case line + when /CPU:\s+(.+) \(([\d.]+).+\)/ + cpuinfo["model_name"] = $1 + cpuinfo["mhz"] = $2 + when /Origin = "(.+)"\s+Id = (.+)\s+Stepping = (.+)/ + cpuinfo["vendor_id"] = $1 + cpuinfo["stepping"] = $3 + # These _should_ match /AMD Features2?/ lines as well + when /Features=.+<(.+)>/ + cpuinfo["flags"] = $1.downcase.split(',') + # Features2=0x80000001<SSE3,<b31>> + when /Features2=[a-f\dx]+<(.+)>/ + cpuinfo["flags"].concat($1.downcase.split(',')) + when /Logical CPUs per core: (\d+)/ + cpuinfo["cores"] = $1 + end + end + + cpu cpuinfo + cpu[:total] = from("sysctl -n hw.ncpu") end end - -cpu cpuinfo -cpu[:total] = from("sysctl -n hw.ncpu") diff --git a/lib/ohai/plugins/freebsd/filesystem.rb b/lib/ohai/plugins/freebsd/filesystem.rb index a086b83d..cd1cf678 100644 --- a/lib/ohai/plugins/freebsd/filesystem.rb +++ b/lib/ohai/plugins/freebsd/filesystem.rb @@ -16,42 +16,46 @@ # limitations under the License. # -provides "filesystem" +Ohai.plugin(:Filesystem) do + provides "filesystem" -fs = Mash.new + collect_data do + fs = Mash.new -# Grab filesystem data from df -popen4("df") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^Filesystem/ - next - when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ - filesystem = $1 - fs[filesystem] = Mash.new - fs[filesystem][:kb_size] = $2 - fs[filesystem][:kb_used] = $3 - fs[filesystem][:kb_available] = $4 - fs[filesystem][:percent_used] = $5 - fs[filesystem][:mount] = $6 + # Grab filesystem data from df + popen4("df") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^Filesystem/ + next + when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ + filesystem = $1 + fs[filesystem] = Mash.new + fs[filesystem][:kb_size] = $2 + fs[filesystem][:kb_used] = $3 + fs[filesystem][:kb_available] = $4 + fs[filesystem][:percent_used] = $5 + fs[filesystem][:mount] = $6 + end + end end - end -end -# Grab mount information from mount -popen4("mount -l") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/ - filesystem = $1 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem][:mount] = $2 - fs[filesystem][:fs_type] = $3 - fs[filesystem][:mount_options] = $4.split(/,\s*/) + # Grab mount information from mount + popen4("mount -l") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/ + filesystem = $1 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem][:mount] = $2 + fs[filesystem][:fs_type] = $3 + fs[filesystem][:mount_options] = $4.split(/,\s*/) + end + end end + + # Set the filesystem data + filesystem fs end end - -# Set the filesystem data -filesystem fs diff --git a/lib/ohai/plugins/freebsd/hostname.rb b/lib/ohai/plugins/freebsd/hostname.rb index c340dd0c..cef0804b 100644 --- a/lib/ohai/plugins/freebsd/hostname.rb +++ b/lib/ohai/plugins/freebsd/hostname.rb @@ -16,7 +16,11 @@ # limitations under the License. # -provides "hostname", "fqdn" +Ohai.plugin(:Hostname) do + provides "hostname", "fqdn" -hostname from("hostname -s") -fqdn from("hostname -f") + collect_data do + hostname from("hostname -s") + fqdn from("hostname -f") + end +end diff --git a/lib/ohai/plugins/freebsd/kernel.rb b/lib/ohai/plugins/freebsd/kernel.rb index a0f57240..f5194821 100644 --- a/lib/ohai/plugins/freebsd/kernel.rb +++ b/lib/ohai/plugins/freebsd/kernel.rb @@ -16,22 +16,25 @@ # limitations under the License. # -provides "kernel" +Ohai.plugin(:Kernel) do + provides "kernel" -kernel[:os] = kernel[:name] -kernel[:ident] = from("uname -i") -kernel[:securelevel] = from_with_regex("sysctl kern.securelevel", /kern.securelevel: (.+)$/) + collect_data do + kernel[:os] = kernel[:name] + kernel[:ident] = from("uname -i") + kernel[:securelevel] = from_with_regex("sysctl kern.securelevel", /kern.securelevel: (.+)$/) -kld = Mash.new -popen4("/sbin/kldstat") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # 1 7 0xc0400000 97f830 kernel - if line =~ /(\d+)\s+(\d+)\s+([0-9a-fx]+)\s+([0-9a-fx]+)\s+([a-zA-Z0-9\_]+)/ - kld[$5] = { :size => $4, :refcount => $2 } + kld = Mash.new + popen4("/sbin/kldstat") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # 1 7 0xc0400000 97f830 kernel + if line =~ /(\d+)\s+(\d+)\s+([0-9a-fx]+)\s+([0-9a-fx]+)\s+([a-zA-Z0-9\_]+)/ + kld[$5] = { :size => $4, :refcount => $2 } + end + end end + + kernel[:modules] = kld end end - -kernel[:modules] = kld - diff --git a/lib/ohai/plugins/freebsd/memory.rb b/lib/ohai/plugins/freebsd/memory.rb index f4f3c98c..77140fec 100644 --- a/lib/ohai/plugins/freebsd/memory.rb +++ b/lib/ohai/plugins/freebsd/memory.rb @@ -16,35 +16,38 @@ # limitations under the License. # -provides "memory" +Ohai.plugin(:Memory) do + provides "memory" -memory Mash.new -memory[:swap] = Mash.new + collect_data do + memory Mash.new + memory[:swap] = Mash.new -# /usr/src/sys/sys/vmmeter.h -memory[:page_size] = from("sysctl -n vm.stats.vm.v_page_size") -memory[:page_count] = from("sysctl -n vm.stats.vm.v_page_count") -memory[:total] = memory[:page_size].to_i * memory[:page_count].to_i -memory[:free] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_free_count").to_i -memory[:active] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_active_count").to_i -memory[:inactive] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_inactive_count").to_i -memory[:cache] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_cache_count").to_i -memory[:wired] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_wire_count").to_i -memory[:buffers] = from("sysctl -n vfs.bufspace") + # /usr/src/sys/sys/vmmeter.h + memory[:page_size] = from("sysctl -n vm.stats.vm.v_page_size") + memory[:page_count] = from("sysctl -n vm.stats.vm.v_page_count") + memory[:total] = memory[:page_size].to_i * memory[:page_count].to_i + memory[:free] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_free_count").to_i + memory[:active] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_active_count").to_i + memory[:inactive] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_inactive_count").to_i + memory[:cache] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_cache_count").to_i + memory[:wired] = memory[:page_size].to_i * from("sysctl -n vm.stats.vm.v_wire_count").to_i + memory[:buffers] = from("sysctl -n vfs.bufspace") -popen4("swapinfo") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # Device 1K-blocks Used Avail Capacity - # /dev/ad0s1b 253648 0 253648 0% - if line =~ /^([\d\w\/]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([\d\%]+)/ - mdev = $1 - memory[:swap][mdev] = Mash.new - memory[:swap][mdev][:total] = $2 - memory[:swap][mdev][:used] = $3 - memory[:swap][mdev][:free] = $4 - memory[:swap][mdev][:percent_free] = $5 + popen4("swapinfo") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # Device 1K-blocks Used Avail Capacity + # /dev/ad0s1b 253648 0 253648 0% + if line =~ /^([\d\w\/]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([\d\%]+)/ + mdev = $1 + memory[:swap][mdev] = Mash.new + memory[:swap][mdev][:total] = $2 + memory[:swap][mdev][:used] = $3 + memory[:swap][mdev][:free] = $4 + memory[:swap][mdev][:percent_free] = $5 + end + end end end end - diff --git a/lib/ohai/plugins/freebsd/network.rb b/lib/ohai/plugins/freebsd/network.rb index a76f57d0..a57ce7e8 100644 --- a/lib/ohai/plugins/freebsd/network.rb +++ b/lib/ohai/plugins/freebsd/network.rb @@ -16,106 +16,110 @@ # limitations under the License. # -provides "network", "counters/network" +Ohai.plugin(:Network) do + provides "network", "counters/network" -from("route -n get default").split("\n").each do |line| - if line =~ /(\w+): ([\w\.]+)/ - case $1 - when "gateway" - network[:default_gateway] = $2 - when "interface" - network[:default_interface] = $2 - end - end -end - -iface = Mash.new -popen4("/sbin/ifconfig -a") do |pid, stdin, stdout, stderr| - stdin.close - cint = nil - stdout.each do |line| - if line =~ /^([0-9a-zA-Z\.]+):\s+/ - cint = $1 - iface[cint] = Mash.new - if cint =~ /^(\w+)(\d+.*)/ - iface[cint][:type] = $1 - iface[cint][:number] = $2 + collect_data do + from("route -n get default").split("\n").each do |line| + if line =~ /(\w+): ([\w\.]+)/ + case $1 + when "gateway" + network[:default_gateway] = $2 + when "interface" + network[:default_interface] = $2 + end end end - # call the family lladdr to match linux for consistency - if line =~ /\s+ether (.+?)\s/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "lladdr" } - end - if line =~ /\s+inet ([\d.]+) netmask ([\da-fx]+)\s*\w*\s*([\d.]*)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - # convert the netmask to decimal for consistency - netmask = "#{$2[2,2].hex}.#{$2[4,2].hex}.#{$2[6,2].hex}.#{$2[8,2].hex}" - if $3.empty? - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask } - else - # found a broadcast address - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask, "broadcast" => $3 } - end - end - if line =~ /\s+inet6 ([a-f0-9\:]+)%?(\w*)\s+prefixlen\s+(\d+)\s*\w*\s*([\da-fx]*)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - if $4.empty? - iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $3 } - else - # found a zone_id / scope - iface[cint][:addresses][$1] = { "family" => "inet6", "zoneid" => $2, "prefixlen" => $3, "scopeid" => $4 } + + iface = Mash.new + popen4("/sbin/ifconfig -a") do |pid, stdin, stdout, stderr| + stdin.close + cint = nil + stdout.each do |line| + if line =~ /^([0-9a-zA-Z\.]+):\s+/ + cint = $1 + iface[cint] = Mash.new + if cint =~ /^(\w+)(\d+.*)/ + iface[cint][:type] = $1 + iface[cint][:number] = $2 + end + end + # call the family lladdr to match linux for consistency + if line =~ /\s+ether (.+?)\s/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "lladdr" } + end + if line =~ /\s+inet ([\d.]+) netmask ([\da-fx]+)\s*\w*\s*([\d.]*)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + # convert the netmask to decimal for consistency + netmask = "#{$2[2,2].hex}.#{$2[4,2].hex}.#{$2[6,2].hex}.#{$2[8,2].hex}" + if $3.empty? + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask } + else + # found a broadcast address + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask, "broadcast" => $3 } + end + end + if line =~ /\s+inet6 ([a-f0-9\:]+)%?(\w*)\s+prefixlen\s+(\d+)\s*\w*\s*([\da-fx]*)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + if $4.empty? + iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $3 } + else + # found a zone_id / scope + iface[cint][:addresses][$1] = { "family" => "inet6", "zoneid" => $2, "prefixlen" => $3, "scopeid" => $4 } + end + end + if line =~ /flags=\d+<(.+)>/ + flags = $1.split(',') + iface[cint][:flags] = flags if flags.length > 0 + end + if line =~ /metric: (\d+) mtu: (\d+)/ + iface[cint][:metric] = $1 + iface[cint][:mtu] = $2 + end end end - if line =~ /flags=\d+<(.+)>/ - flags = $1.split(',') - iface[cint][:flags] = flags if flags.length > 0 - end - if line =~ /metric: (\d+) mtu: (\d+)/ - iface[cint][:metric] = $1 - iface[cint][:mtu] = $2 - end - end -end -popen4("arp -an") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /\((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) on ([0-9a-zA-Z\.\:\-]+)/ - next unless iface[$3] # this should never happen - iface[$3][:arp] = Mash.new unless iface[$3][:arp] - iface[$3][:arp][$1] = $2.downcase + popen4("arp -an") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /\((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) on ([0-9a-zA-Z\.\:\-]+)/ + next unless iface[$3] # this should never happen + iface[$3][:arp] = Mash.new unless iface[$3][:arp] + iface[$3][:arp][$1] = $2.downcase + end + end end - end -end -network["interfaces"] = iface + network["interfaces"] = iface -net_counters = Mash.new -# From netstat(1), not sure of the implications: -# Show the state of all network interfaces or a single interface -# which have been auto-configured (interfaces statically configured -# into a system, but not located at boot time are not shown). -popen4("netstat -ibdn") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # Name Mtu Network Address Ipkts Ierrs Ibytes Opkts Oerrs Obytes Coll Drop - # ed0 1500 <Link#1> 54:52:00:68:92:85 333604 26 151905886 175472 0 24897542 0 905 - # $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 - if line =~ /^([\w\.\*]+)\s+\d+\s+<Link#\d+>\s+([\w:]*)\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ - net_counters[$1] = Mash.new unless net_counters[$1] - net_counters[$1]["rx"] = Mash.new unless net_counters[$1]["rx"] - net_counters[$1]["tx"] = Mash.new unless net_counters[$1]["tx"] - net_counters[$1]["rx"]["packets"] = $3 - net_counters[$1]["rx"]["errors"] = $4 - net_counters[$1]["rx"]["bytes"] = $5 - net_counters[$1]["tx"]["packets"] = $6 - net_counters[$1]["tx"]["errors"] = $7 - net_counters[$1]["tx"]["bytes"] = $8 - net_counters[$1]["tx"]["collisions"] = $9 - net_counters[$1]["tx"]["dropped"] = $10 + net_counters = Mash.new + # From netstat(1), not sure of the implications: + # Show the state of all network interfaces or a single interface + # which have been auto-configured (interfaces statically configured + # into a system, but not located at boot time are not shown). + popen4("netstat -ibdn") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # Name Mtu Network Address Ipkts Ierrs Ibytes Opkts Oerrs Obytes Coll Drop + # ed0 1500 <Link#1> 54:52:00:68:92:85 333604 26 151905886 175472 0 24897542 0 905 + # $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 + if line =~ /^([\w\.\*]+)\s+\d+\s+<Link#\d+>\s+([\w:]*)\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ + net_counters[$1] = Mash.new unless net_counters[$1] + net_counters[$1]["rx"] = Mash.new unless net_counters[$1]["rx"] + net_counters[$1]["tx"] = Mash.new unless net_counters[$1]["tx"] + net_counters[$1]["rx"]["packets"] = $3 + net_counters[$1]["rx"]["errors"] = $4 + net_counters[$1]["rx"]["bytes"] = $5 + net_counters[$1]["tx"]["packets"] = $6 + net_counters[$1]["tx"]["errors"] = $7 + net_counters[$1]["tx"]["bytes"] = $8 + net_counters[$1]["tx"]["collisions"] = $9 + net_counters[$1]["tx"]["dropped"] = $10 + end + end end + + counters[:network][:interfaces] = net_counters end end - -counters[:network][:interfaces] = net_counters diff --git a/lib/ohai/plugins/freebsd/platform.rb b/lib/ohai/plugins/freebsd/platform.rb index 78697e72..45891989 100644 --- a/lib/ohai/plugins/freebsd/platform.rb +++ b/lib/ohai/plugins/freebsd/platform.rb @@ -16,8 +16,11 @@ # limitations under the License. # -provides "platform", "platform_version" - -platform from("uname -s").downcase -platform_version from("uname -r") +Ohai.plugin(:Platform) do + provides "platform", "platform_version" + collect_data do + platform from("uname -s").downcase + platform_version from("uname -r") + end +end diff --git a/lib/ohai/plugins/freebsd/ps.rb b/lib/ohai/plugins/freebsd/ps.rb index f4823327..876ded11 100644 --- a/lib/ohai/plugins/freebsd/ps.rb +++ b/lib/ohai/plugins/freebsd/ps.rb @@ -16,9 +16,13 @@ # limitations under the License. # -provides "command/ps" +Ohai.plugin(:Ps) do + provides "command/ps" -require_plugin 'command' + depends 'command' -# ps -e requires procfs -command[:ps] = 'ps -ax' + collect_data do + # ps -e requires procfs + command[:ps] = 'ps -ax' + end +end diff --git a/lib/ohai/plugins/freebsd/uptime.rb b/lib/ohai/plugins/freebsd/uptime.rb index ea49fa09..e50f9c71 100644 --- a/lib/ohai/plugins/freebsd/uptime.rb +++ b/lib/ohai/plugins/freebsd/uptime.rb @@ -16,16 +16,20 @@ # limitations under the License. # -provides "uptime", "uptime_seconds" +Ohai.plugin(:Uptime) do + provides "uptime", "uptime_seconds" -# kern.boottime: { sec = 1232765114, usec = 823118 } Fri Jan 23 18:45:14 2009 + # kern.boottime: { sec = 1232765114, usec = 823118 } Fri Jan 23 18:45:14 2009 -popen4("/sbin/sysctl kern.boottime") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /kern.boottime:\D+(\d+)/ - uptime_seconds Time.new.to_i - $1.to_i - uptime seconds_to_human(uptime_seconds) + collect_data do + popen4("/sbin/sysctl kern.boottime") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /kern.boottime:\D+(\d+)/ + uptime_seconds Time.new.to_i - $1.to_i + uptime seconds_to_human(uptime_seconds) + end + end end end end diff --git a/lib/ohai/plugins/freebsd/virtualization.rb b/lib/ohai/plugins/freebsd/virtualization.rb index 96ee6fab..ecd5e8e9 100644 --- a/lib/ohai/plugins/freebsd/virtualization.rb +++ b/lib/ohai/plugins/freebsd/virtualization.rb @@ -16,78 +16,81 @@ # limitations under the License. # -provides "virtualization" +Ohai.plugin(:Virtualization) do + provides "virtualization" -virtualization Mash.new + collect_data do + virtualization Mash.new -if from("sysctl -n security.jail.jailed").to_i == 1 - virtualization[:system] = "jail" - virtualization[:role] = "guest" -end - -# detect from modules -popen4("/sbin/kldstat") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /vboxdrv/ - virtualization[:system] = "vbox" - virtualization[:role] = "host" - when /vboxguest/ - virtualization[:system] = "vbox" + if from("sysctl -n security.jail.jailed").to_i == 1 + virtualization[:system] = "jail" virtualization[:role] = "guest" end - end -end + # detect from modules + popen4("/sbin/kldstat") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /vboxdrv/ + virtualization[:system] = "vbox" + virtualization[:role] = "host" + when /vboxguest/ + virtualization[:system] = "vbox" + virtualization[:role] = "guest" + end + end + end -# XXX doesn't work when jail is there but not running (ezjail-admin stop) -if from("jls -n \| wc -l").to_i >= 1 - virtualization[:system] = "jail" - virtualization[:role] = "host" -end -# KVM Host support for FreeBSD is in development -# http://feanor.sssup.it/~fabio/freebsd/lkvm/ + # XXX doesn't work when jail is there but not running (ezjail-admin stop) + if from("jls -n \| wc -l").to_i >= 1 + virtualization[:system] = "jail" + virtualization[:role] = "host" + end + + # KVM Host support for FreeBSD is in development + # http://feanor.sssup.it/~fabio/freebsd/lkvm/ -# Detect KVM/QEMU from cpu, report as KVM -# hw.model: QEMU Virtual CPU version 0.9.1 -if from("sysctl -n hw.model") =~ /QEMU Virtual CPU/ - virtualization[:system] = "kvm" - virtualization[:role] = "guest" -end + # Detect KVM/QEMU from cpu, report as KVM + # hw.model: QEMU Virtual CPU version 0.9.1 + if from("sysctl -n hw.model") =~ /QEMU Virtual CPU/ + virtualization[:system] = "kvm" + virtualization[:role] = "guest" + end -# http://www.dmo.ca/blog/detecting-virtualization-on-linux -if File.exists?("/usr/local/sbin/dmidecode") - popen4("dmidecode") do |pid, stdin, stdout, stderr| - stdin.close - found_virt_manufacturer = nil - found_virt_product = nil - stdout.each do |line| - case line - when /Manufacturer: Microsoft/ - found_virt_manufacturer = "microsoft" - when /Product Name: Virtual Machine/ - found_virt_product = "microsoft" - when /Version: 5.0/ - if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" - virtualization[:system] = "virtualpc" - virtualization[:role] = "guest" - end - when /Version: VS2005R2/ - if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" - virtualization[:system] = "virtualserver" - virtualization[:role] = "guest" - end - when /Manufacturer: VMware/ - found_virt_manufacturer = "vmware" - when /Product Name: VMware Virtual Platform/ - if found_virt_manufacturer == "vmware" - virtualization[:system] = "vmware" - virtualization[:role] = "guest" + # http://www.dmo.ca/blog/detecting-virtualization-on-linux + if File.exists?("/usr/local/sbin/dmidecode") + popen4("dmidecode") do |pid, stdin, stdout, stderr| + stdin.close + found_virt_manufacturer = nil + found_virt_product = nil + stdout.each do |line| + case line + when /Manufacturer: Microsoft/ + found_virt_manufacturer = "microsoft" + when /Product Name: Virtual Machine/ + found_virt_product = "microsoft" + when /Version: 5.0/ + if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" + virtualization[:system] = "virtualpc" + virtualization[:role] = "guest" + end + when /Version: VS2005R2/ + if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" + virtualization[:system] = "virtualserver" + virtualization[:role] = "guest" + end + when /Manufacturer: VMware/ + found_virt_manufacturer = "vmware" + when /Product Name: VMware Virtual Platform/ + if found_virt_manufacturer == "vmware" + virtualization[:system] = "vmware" + virtualization[:role] = "guest" + end + end end end end end end - diff --git a/lib/ohai/plugins/gce.rb b/lib/ohai/plugins/gce.rb index c93f6d57..0c1bcea5 100644 --- a/lib/ohai/plugins/gce.rb +++ b/lib/ohai/plugins/gce.rb @@ -14,27 +14,32 @@ # See the License for the specific language governing permissions and # limitations under the License. -provides "gce" - require 'ohai/mixin/gce_metadata' extend Ohai::Mixin::GCEMetadata -GOOGLE_SYSFS_DMI = '/sys/firmware/dmi/entries/1-0/raw' -#https://developers.google.com/compute/docs/instances#dmi -def has_google_dmi? - ::File.read(GOOGLE_SYSFS_DMI).include?('Google') -end +Ohai.plugin(:Gce) do + provides "gce" + + GOOGLE_SYSFS_DMI = '/sys/firmware/dmi/entries/1-0/raw' + + #https://developers.google.com/compute/docs/instances#dmi + def has_google_dmi? + ::File.read(GOOGLE_SYSFS_DMI).include?('Google') + end -def looks_like_gce? - hint?('gce') || has_google_dmi? && can_metadata_connect?(GCE_METADATA_ADDR,80) -end + def looks_like_gce? + hint?('gce') || has_google_dmi? && can_metadata_connect?(GCE_METADATA_ADDR,80) + end -if looks_like_gce? - Ohai::Log.debug("looks_like_gce? == true") - gce Mash.new - fetch_metadata.each {|k, v| gce[k] = v } -else - Ohai::Log.debug("looks_like_gce? == false") - false + collect_data do + if looks_like_gce? + Ohai::Log.debug("looks_like_gce? == true") + gce Mash.new + fetch_metadata.each {|k, v| gce[k] = v } + else + Ohai::Log.debug("looks_like_gce? == false") + false + end + end end diff --git a/lib/ohai/plugins/groovy.rb b/lib/ohai/plugins/groovy.rb index 8979a563..0873d726 100644 --- a/lib/ohai/plugins/groovy.rb +++ b/lib/ohai/plugins/groovy.rb @@ -16,20 +16,23 @@ # limitations under the License. # -provides "languages/groovy" +Ohai.plugin(:Groovy) do + provides "languages/groovy" -require_plugin "languages" + depends "languages" -output = nil + collect_data do + output = nil -groovy = Mash.new + groovy = Mash.new -status, stdout, stderr = run_command(:no_status_check => true, :command => "groovy -v") -if status == 0 - output = stdout.split - if output.length >= 2 - groovy[:version] = output[2] + status, stdout, stderr = run_command(:no_status_check => true, :command => "groovy -v") + if status == 0 + output = stdout.split + if output.length >= 2 + groovy[:version] = output[2] + end + languages[:groovy] = groovy if groovy[:version] + end end - languages[:groovy] = groovy if groovy[:version] end - diff --git a/lib/ohai/plugins/hostname.rb b/lib/ohai/plugins/hostname.rb index 119e3c29..22c8e1c9 100644 --- a/lib/ohai/plugins/hostname.rb +++ b/lib/ohai/plugins/hostname.rb @@ -16,12 +16,16 @@ # limitations under the License. # -provides "fqdn", "domain" +Ohai.plugin(:Hostname) do + provides "fqdn", "domain" -require_plugin "#{os}::hostname" + depends_os "hostname" -# Domain is everything after the first dot -if fqdn - fqdn =~ /.+?\.(.*)/ - domain $1 -end
\ No newline at end of file + collect_data do + # Domain is everything after the first dot + if fqdn + fqdn =~ /.+?\.(.*)/ + domain $1 + end + end +end diff --git a/lib/ohai/plugins/hpux/cpu.rb b/lib/ohai/plugins/hpux/cpu.rb index 32b2dc91..169ce782 100644 --- a/lib/ohai/plugins/hpux/cpu.rb +++ b/lib/ohai/plugins/hpux/cpu.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::cpu" +Ohai.plugin(:Cpu) do + depends "sigar::cpu" +end diff --git a/lib/ohai/plugins/hpux/filesystem.rb b/lib/ohai/plugins/hpux/filesystem.rb index 8322ee0b..15b39e08 100644 --- a/lib/ohai/plugins/hpux/filesystem.rb +++ b/lib/ohai/plugins/hpux/filesystem.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::filesystem" +Ohai.plugin(:Filesystem) do + depends "sigar::filesystem" +end diff --git a/lib/ohai/plugins/hpux/hostname.rb b/lib/ohai/plugins/hpux/hostname.rb index 805b4734..b01959bf 100644 --- a/lib/ohai/plugins/hpux/hostname.rb +++ b/lib/ohai/plugins/hpux/hostname.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::hostname" +Ohai.plugin(:Hostname) do + depends "sigar::hostname" +end diff --git a/lib/ohai/plugins/hpux/memory.rb b/lib/ohai/plugins/hpux/memory.rb index dd3532fb..d625ff83 100644 --- a/lib/ohai/plugins/hpux/memory.rb +++ b/lib/ohai/plugins/hpux/memory.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::memory" +Ohai.plugin(:Memory) do + depends "sigar::memory" +end diff --git a/lib/ohai/plugins/hpux/network.rb b/lib/ohai/plugins/hpux/network.rb index 7071abef..e65eb8bf 100644 --- a/lib/ohai/plugins/hpux/network.rb +++ b/lib/ohai/plugins/hpux/network.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::network" +Ohai.plugin(:Network) do + depends "sigar::network" +end diff --git a/lib/ohai/plugins/hpux/platform.rb b/lib/ohai/plugins/hpux/platform.rb index bea329d6..712711ad 100644 --- a/lib/ohai/plugins/hpux/platform.rb +++ b/lib/ohai/plugins/hpux/platform.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::platform" +Ohai.plugin(:Platform) do + depends "sigar::platform" +end diff --git a/lib/ohai/plugins/hpux/ps.rb b/lib/ohai/plugins/hpux/ps.rb index 9532014a..7fb57ddb 100644 --- a/lib/ohai/plugins/hpux/ps.rb +++ b/lib/ohai/plugins/hpux/ps.rb @@ -16,8 +16,12 @@ # limitations under the License. # -provides "command/ps" +Ohai.plugin(:Ps) do + provides "command/ps" -require_plugin 'command' + depends 'command' -command[:ps] = 'ps -ef' + collect_data do + command[:ps] = 'ps -ef' + end +end diff --git a/lib/ohai/plugins/hpux/uptime.rb b/lib/ohai/plugins/hpux/uptime.rb index 23aa89f3..bd6f3938 100644 --- a/lib/ohai/plugins/hpux/uptime.rb +++ b/lib/ohai/plugins/hpux/uptime.rb @@ -16,4 +16,6 @@ # limitations under the License. # -require_plugin "sigar::uptime" +Ohai.plugin(:Uptime) do + depends "sigar::uptime" +end diff --git a/lib/ohai/plugins/ip_scopes.rb b/lib/ohai/plugins/ip_scopes.rb index 0b0f377e..722f90bd 100644 --- a/lib/ohai/plugins/ip_scopes.rb +++ b/lib/ohai/plugins/ip_scopes.rb @@ -15,28 +15,32 @@ # See the License for the specific language governing permissions and # limitations under the License. -begin - require 'ipaddr_extensions' +Ohai.plugin(:IpScopes) do + provides "network_ip_scope", "privateaddres" - provides "network_ip_scope", "privateaddress" + depends "domain", "fqdn" + depends "network", "counters/network" - require_plugin "hostname" - require_plugin "network" + collect_data do + begin + require 'ipaddr_extensions' - network['interfaces'].keys.each do |ifName| - next if network['interfaces'][ifName]['addresses'].nil? + network['interfaces'].keys.each do |ifName| + next if network['interfaces'][ifName]['addresses'].nil? - network['interfaces'][ifName]['addresses'].each do |address,attrs| - begin - attrs.merge! 'ip_scope' => address.to_ip.scope - privateaddress address if address.to_ip.scope =~ /PRIVATE/ - rescue ArgumentError - # Just silently fail if we can't create an IP from the string. + network['interfaces'][ifName]['addresses'].each do |address,attrs| + begin + attrs.merge! 'ip_scope' => address.to_ip.scope + privateaddress address if address.to_ip.scope =~ /PRIVATE/ + rescue ArgumentError + # Just silently fail if we can't create an IP from the string. + end + end end + + rescue LoadError => e + # our favourite gem is not installed. Boohoo. + Ohai::Log.debug("ip_scopes: cannot load gem, plugin disabled: #{e}") end end - -rescue LoadError => e - # our favourite gem is not installed. Boohoo. - Ohai::Log.debug("ip_scopes: cannot load gem, plugin disabled: #{e}") end diff --git a/lib/ohai/plugins/java.rb b/lib/ohai/plugins/java.rb index 67310bfd..48664a76 100644 --- a/lib/ohai/plugins/java.rb +++ b/lib/ohai/plugins/java.rb @@ -15,32 +15,37 @@ # See the License for the specific language governing permissions and # limitations under the License. # -provides "languages/java" -require_plugin "languages" +Ohai.plugin(:Java) do + provides "languages/java" -java = Mash.new + depends "languages" -status, stdout, stderr = nil -if RUBY_PLATFORM.downcase.include?("darwin") - if system("/usr/libexec/java_home 2>&1 >/dev/null") - status, stdout, stderr = run_command(:no_status_check => true, :command => "java -version") - end -else - status, stdout, stderr = run_command(:no_status_check => true, :command => "java -version") -end + collect_data do + java = Mash.new -if status == 0 - stderr.split("\n").each do |line| - case line - when /java version \"([0-9\.\_]+)\"/ - java[:version] = $1 - when /^(.+Runtime Environment.*) \((build )?(.+)\)$/ - java[:runtime] = { "name" => $1, "build" => $3 } - when /^(.+ (Client|Server) VM) \(build (.+)\)$/ - java[:hotspot] = { "name" => $1, "build" => $3 } + status, stdout, stderr = nil + if RUBY_PLATFORM.downcase.include?("darwin") + if system("/usr/libexec/java_home 2>&1 >/dev/null") + status, stdout, stderr = run_command(:no_status_check => true, :command => "java -version") + end + else + status, stdout, stderr = run_command(:no_status_check => true, :command => "java -version") end - end - languages[:java] = java if java[:version] + if status == 0 + stderr.split("\n").each do |line| + case line + when /java version \"([0-9\.\_]+)\"/ + java[:version] = $1 + when /^(.+Runtime Environment.*) \((build )?(.+)\)$/ + java[:runtime] = { "name" => $1, "build" => $3 } + when /^(.+ (Client|Server) VM) \(build (.+)\)$/ + java[:hotspot] = { "name" => $1, "build" => $3 } + end + end + + languages[:java] = java if java[:version] + end + end end diff --git a/lib/ohai/plugins/keys.rb b/lib/ohai/plugins/keys.rb index 99709f7a..d786f4fd 100644 --- a/lib/ohai/plugins/keys.rb +++ b/lib/ohai/plugins/keys.rb @@ -17,6 +17,10 @@ # limitations under the License. # -provides "keys" +Ohai.plugin(:Keys) do + provides "keys" -keys Mash.new
\ No newline at end of file + collect_data do + keys Mash.new + end +end diff --git a/lib/ohai/plugins/linode.rb b/lib/ohai/plugins/linode.rb index 2be916e5..a6dfc319 100644 --- a/lib/ohai/plugins/linode.rb +++ b/lib/ohai/plugins/linode.rb @@ -14,44 +14,48 @@ # See the License for the specific language governing permissions and # limitations under the License. -provides "linode" +Ohai.plugin(:Linode) do + provides "linode" -require_plugin "kernel" -require_plugin "network" + depends "kernel" + depends "network", "counters/network" -# Checks for matching linode kernel name -# -# Returns true or false -def has_linode_kernel? - if kernel_data = kernel - kernel_data[:release].split('-').last =~ /linode/ + # Checks for matching linode kernel name + # + # Returns true or false + def has_linode_kernel? + if kernel_data = kernel + kernel_data[:release].split('-').last =~ /linode/ + end end -end -# Identifies the linode cloud by preferring the hint, then -# -# Returns true or false -def looks_like_linode? - hint?('linode') || has_linode_kernel? -end + # Identifies the linode cloud by preferring the hint, then + # + # Returns true or false + def looks_like_linode? + hint?('linode') || has_linode_kernel? + end -# Names linode ip address -# -# name - symbol of ohai name (e.g. :public_ip) -# eth - Interface name (e.g. :eth0) -# -# Alters linode mash with new interface based on name parameter -def get_ip_address(name, eth) - if eth_iface = network[:interfaces][eth] - eth_iface[:addresses].each do |key, info| - linode[name] = key if info['family'] == 'inet' + # Names linode ip address + # + # name - symbol of ohai name (e.g. :public_ip) + # eth - Interface name (e.g. :eth0) + # + # Alters linode mash with new interface based on name parameter + def get_ip_address(name, eth) + if eth_iface = network[:interfaces][eth] + eth_iface[:addresses].each do |key, info| + linode[name] = key if info['family'] == 'inet' + end end end -end -# Setup linode mash if it is a linode system -if looks_like_linode? - linode Mash.new - get_ip_address(:public_ip, :eth0) - get_ip_address(:private_ip, "eth0:1") + collect_data do + # Setup linode mash if it is a linode system + if looks_like_linode? + linode Mash.new + get_ip_address(:public_ip, :eth0) + get_ip_address(:private_ip, "eth0:1") + end + end end diff --git a/lib/ohai/plugins/linux/block_device.rb b/lib/ohai/plugins/linux/block_device.rb index 2fee4b68..94ded2d5 100644 --- a/lib/ohai/plugins/linux/block_device.rb +++ b/lib/ohai/plugins/linux/block_device.rb @@ -16,23 +16,27 @@ # limitations under the License. # -provides "block_device" +Ohai.plugin(:BlockDevice) do + provides "block_device" -if File.exists?("/sys/block") - block = Mash.new - Dir["/sys/block/*"].each do |block_device_dir| - dir = File.basename(block_device_dir) - block[dir] = Mash.new - %w{size removable}.each do |check| - if File.exists?("/sys/block/#{dir}/#{check}") - File.open("/sys/block/#{dir}/#{check}") { |f| block[dir][check] = f.read_nonblock(1024).strip } - end - end - %w{model rev state timeout vendor}.each do |check| - if File.exists?("/sys/block/#{dir}/device/#{check}") - File.open("/sys/block/#{dir}/device/#{check}") { |f| block[dir][check] = f.read_nonblock(1024).strip } + collect_data do + if File.exists?("/sys/block") + block = Mash.new + Dir["/sys/block/*"].each do |block_device_dir| + dir = File.basename(block_device_dir) + block[dir] = Mash.new + %w{size removable}.each do |check| + if File.exists?("/sys/block/#{dir}/#{check}") + File.open("/sys/block/#{dir}/#{check}") { |f| block[dir][check] = f.read_nonblock(1024).strip } + end + end + %w{model rev state timeout vendor}.each do |check| + if File.exists?("/sys/block/#{dir}/device/#{check}") + File.open("/sys/block/#{dir}/device/#{check}") { |f| block[dir][check] = f.read_nonblock(1024).strip } + end + end end + block_device block end end - block_device block end diff --git a/lib/ohai/plugins/linux/cpu.rb b/lib/ohai/plugins/linux/cpu.rb index 48468a5e..0112400c 100644 --- a/lib/ohai/plugins/linux/cpu.rb +++ b/lib/ohai/plugins/linux/cpu.rb @@ -16,45 +16,49 @@ # limitations under the License. # -provides "cpu" +Ohai.plugin(:Cpu) do + provides "cpu" -cpuinfo = Mash.new -real_cpu = Mash.new -cpu_number = 0 -current_cpu = nil + collect_data do + cpuinfo = Mash.new + real_cpu = Mash.new + cpu_number = 0 + current_cpu = nil -File.open("/proc/cpuinfo").each do |line| - case line - when /processor\s+:\s(.+)/ - cpuinfo[$1] = Mash.new - current_cpu = $1 - cpu_number += 1 - when /vendor_id\s+:\s(.+)/ - cpuinfo[current_cpu]["vendor_id"] = $1 - when /cpu family\s+:\s(.+)/ - cpuinfo[current_cpu]["family"] = $1 - when /model\s+:\s(.+)/ - cpuinfo[current_cpu]["model"] = $1 - when /stepping\s+:\s(.+)/ - cpuinfo[current_cpu]["stepping"] = $1 - when /physical id\s+:\s(.+)/ - cpuinfo[current_cpu]["physical_id"] = $1 - real_cpu[$1] = true - when /core id\s+:\s(.+)/ - cpuinfo[current_cpu]["core_id"] = $1 - when /cpu cores\s+:\s(.+)/ - cpuinfo[current_cpu]["cores"] = $1 - when /model name\s+:\s(.+)/ - cpuinfo[current_cpu]["model_name"] = $1 - when /cpu MHz\s+:\s(.+)/ - cpuinfo[current_cpu]["mhz"] = $1 - when /cache size\s+:\s(.+)/ - cpuinfo[current_cpu]["cache_size"] = $1 - when /flags\s+:\s(.+)/ - cpuinfo[current_cpu]["flags"] = $1.split(' ') + File.open("/proc/cpuinfo").each do |line| + case line + when /processor\s+:\s(.+)/ + cpuinfo[$1] = Mash.new + current_cpu = $1 + cpu_number += 1 + when /vendor_id\s+:\s(.+)/ + cpuinfo[current_cpu]["vendor_id"] = $1 + when /cpu family\s+:\s(.+)/ + cpuinfo[current_cpu]["family"] = $1 + when /model\s+:\s(.+)/ + cpuinfo[current_cpu]["model"] = $1 + when /stepping\s+:\s(.+)/ + cpuinfo[current_cpu]["stepping"] = $1 + when /physical id\s+:\s(.+)/ + cpuinfo[current_cpu]["physical_id"] = $1 + real_cpu[$1] = true + when /core id\s+:\s(.+)/ + cpuinfo[current_cpu]["core_id"] = $1 + when /cpu cores\s+:\s(.+)/ + cpuinfo[current_cpu]["cores"] = $1 + when /model name\s+:\s(.+)/ + cpuinfo[current_cpu]["model_name"] = $1 + when /cpu MHz\s+:\s(.+)/ + cpuinfo[current_cpu]["mhz"] = $1 + when /cache size\s+:\s(.+)/ + cpuinfo[current_cpu]["cache_size"] = $1 + when /flags\s+:\s(.+)/ + cpuinfo[current_cpu]["flags"] = $1.split(' ') + end + end + + cpu cpuinfo + cpu[:total] = cpu_number + cpu[:real] = real_cpu.keys.length end end - -cpu cpuinfo -cpu[:total] = cpu_number -cpu[:real] = real_cpu.keys.length
\ No newline at end of file diff --git a/lib/ohai/plugins/linux/filesystem.rb b/lib/ohai/plugins/linux/filesystem.rb index 2076d0b5..561b047b 100644 --- a/lib/ohai/plugins/linux/filesystem.rb +++ b/lib/ohai/plugins/linux/filesystem.rb @@ -16,92 +16,96 @@ # limitations under the License. # -provides "filesystem" +Ohai.plugin(:Filesystem) do + provides "filesystem" -fs = Mash.new + collect_data do + fs = Mash.new -# Grab filesystem data from df -popen4("df -P") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^Filesystem\s+1024-blocks/ - next - when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ - filesystem = $1 - fs[filesystem] = Mash.new - fs[filesystem][:kb_size] = $2 - fs[filesystem][:kb_used] = $3 - fs[filesystem][:kb_available] = $4 - fs[filesystem][:percent_used] = $5 - fs[filesystem][:mount] = $6 + # Grab filesystem data from df + popen4("df -P") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^Filesystem\s+1024-blocks/ + next + when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ + filesystem = $1 + fs[filesystem] = Mash.new + fs[filesystem][:kb_size] = $2 + fs[filesystem][:kb_used] = $3 + fs[filesystem][:kb_available] = $4 + fs[filesystem][:percent_used] = $5 + fs[filesystem][:mount] = $6 + end + end end - end -end -# Grab mount information from /bin/mount -popen4("mount") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^(.+?) on (.+?) type (.+?) \((.+?)\)$/ - filesystem = $1 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem][:mount] = $2 - fs[filesystem][:fs_type] = $3 - fs[filesystem][:mount_options] = $4.split(",") + # Grab mount information from /bin/mount + popen4("mount") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^(.+?) on (.+?) type (.+?) \((.+?)\)$/ + filesystem = $1 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem][:mount] = $2 + fs[filesystem][:fs_type] = $3 + fs[filesystem][:mount_options] = $4.split(",") + end + end end - end -end -# Gather more filesystem types via libuuid, even devices that's aren't mounted -popen4("blkid -s TYPE") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^(\S+): TYPE="(\S+)"/ - filesystem = $1 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem][:fs_type] = $2 + # Gather more filesystem types via libuuid, even devices that's aren't mounted + popen4("blkid -s TYPE") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^(\S+): TYPE="(\S+)"/ + filesystem = $1 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem][:fs_type] = $2 + end + end end - end -end -# Gather device UUIDs via libuuid -popen4("blkid -s UUID") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^(\S+): UUID="(\S+)"/ - filesystem = $1 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem][:uuid] = $2 + # Gather device UUIDs via libuuid + popen4("blkid -s UUID") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^(\S+): UUID="(\S+)"/ + filesystem = $1 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem][:uuid] = $2 + end + end end - end -end -# Gather device labels via libuuid -popen4("blkid -s LABEL") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^(\S+): LABEL="(\S+)"/ - filesystem = $1 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem][:label] = $2 + # Gather device labels via libuuid + popen4("blkid -s LABEL") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^(\S+): LABEL="(\S+)"/ + filesystem = $1 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem][:label] = $2 + end + end end - end -end -# Grab any missing mount information from /proc/mounts -if File.exists?('/proc/mounts') - File.open('/proc/mounts').read_nonblock(4096).each_line do |line| - if line =~ /^(\S+) (\S+) (\S+) (\S+) \S+ \S+$/ - filesystem = $1 - next if fs.has_key?(filesystem) - fs[filesystem] = Mash.new - fs[filesystem][:mount] = $2 - fs[filesystem][:fs_type] = $3 - fs[filesystem][:mount_options] = $4.split(",") + # Grab any missing mount information from /proc/mounts + if File.exists?('/proc/mounts') + File.open('/proc/mounts').read_nonblock(4096).each_line do |line| + if line =~ /^(\S+) (\S+) (\S+) (\S+) \S+ \S+$/ + filesystem = $1 + next if fs.has_key?(filesystem) + fs[filesystem] = Mash.new + fs[filesystem][:mount] = $2 + fs[filesystem][:fs_type] = $3 + fs[filesystem][:mount_options] = $4.split(",") + end + end end + + # Set the filesystem data + filesystem fs end end - -# Set the filesystem data -filesystem fs diff --git a/lib/ohai/plugins/linux/hostname.rb b/lib/ohai/plugins/linux/hostname.rb index 896ad821..0a3f833b 100644 --- a/lib/ohai/plugins/linux/hostname.rb +++ b/lib/ohai/plugins/linux/hostname.rb @@ -16,11 +16,15 @@ # limitations under the License. # -provides "hostname", "fqdn" +Ohai.plugin(:Hostname) do + provides "hostname", "fqdn" -hostname from("hostname -s") -begin - fqdn from("hostname --fqdn") -rescue - Ohai::Log.debug("hostname -f returned an error, probably no domain is set") + collect_data do + hostname from("hostname -s") + begin + fqdn from("hostname --fqdn") + rescue + Ohai::Log.debug("hostname -f returned an error, probably no domain is set") + end + end end diff --git a/lib/ohai/plugins/linux/kernel.rb b/lib/ohai/plugins/linux/kernel.rb index c862688a..87151628 100644 --- a/lib/ohai/plugins/linux/kernel.rb +++ b/lib/ohai/plugins/linux/kernel.rb @@ -16,18 +16,22 @@ # limitations under the License. # -provides "kernel" +Ohai.plugin(:Kernel) do + provides "kernel" -kernel[:os] = from("uname -o") + collect_data do + kernel[:os] = from("uname -o") -kext = Mash.new -popen4("env lsmod") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /([a-zA-Z0-9\_]+)\s+(\d+)\s+(\d+)/ - kext[$1] = { :size => $2, :refcount => $3 } + kext = Mash.new + popen4("env lsmod") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /([a-zA-Z0-9\_]+)\s+(\d+)\s+(\d+)/ + kext[$1] = { :size => $2, :refcount => $3 } + end + end end + + kernel[:modules] = kext end end - -kernel[:modules] = kext diff --git a/lib/ohai/plugins/linux/lsb.rb b/lib/ohai/plugins/linux/lsb.rb index 9750c20a..de6a3b3a 100644 --- a/lib/ohai/plugins/linux/lsb.rb +++ b/lib/ohai/plugins/linux/lsb.rb @@ -16,44 +16,48 @@ # limitations under the License. # -provides "lsb" +Ohai.plugin(:Lsb) do + provides "lsb" -lsb Mash.new + collect_data do + lsb Mash.new -if File.exists?("/etc/lsb-release") - File.open("/etc/lsb-release").each do |line| - case line - when /^DISTRIB_ID=["']?(.+?)["']?$/ - lsb[:id] = $1 - when /^DISTRIB_RELEASE=["']?(.+?)["']?$/ - lsb[:release] = $1 - when /^DISTRIB_CODENAME=["']?(.+?)["']?$/ - lsb[:codename] = $1 - when /^DISTRIB_DESCRIPTION=["']?(.+?)["']?$/ - lsb[:description] = $1 - end - end -elsif File.exists?("/usr/bin/lsb_release") - # Fedora/Redhat, requires redhat-lsb package - popen4("lsb_release -a") do |pid, stdin, stdout, stderr| - - stdin.close - stdout.each do |line| - case line - when /^Distributor ID:\s+(.+)$/ - lsb[:id] = $1 - when /^Description:\s+(.+)$/ - lsb[:description] = $1 - when /^Release:\s+(.+)$/ - lsb[:release] = $1 - when /^Codename:\s+(.+)$/ - lsb[:codename] = $1 - else - lsb[:id] = line + if File.exists?("/etc/lsb-release") + File.open("/etc/lsb-release").each do |line| + case line + when /^DISTRIB_ID=["']?(.+?)["']?$/ + lsb[:id] = $1 + when /^DISTRIB_RELEASE=["']?(.+?)["']?$/ + lsb[:release] = $1 + when /^DISTRIB_CODENAME=["']?(.+?)["']?$/ + lsb[:codename] = $1 + when /^DISTRIB_DESCRIPTION=["']?(.+?)["']?$/ + lsb[:description] = $1 + end end + elsif File.exists?("/usr/bin/lsb_release") + # Fedora/Redhat, requires redhat-lsb package + popen4("lsb_release -a") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^Distributor ID:\s+(.+)$/ + lsb[:id] = $1 + when /^Description:\s+(.+)$/ + lsb[:description] = $1 + when /^Release:\s+(.+)$/ + lsb[:release] = $1 + when /^Codename:\s+(.+)$/ + lsb[:codename] = $1 + else + lsb[:id] = line + end + + end + end + else + Ohai::Log.debug("Skipping LSB, cannot find /etc/lsb-release or /usr/bin/lsb_release") end end -else - Ohai::Log.debug("Skipping LSB, cannot find /etc/lsb-release or /usr/bin/lsb_release") end diff --git a/lib/ohai/plugins/linux/memory.rb b/lib/ohai/plugins/linux/memory.rb index 51ec2099..8dfe3d36 100644 --- a/lib/ohai/plugins/linux/memory.rb +++ b/lib/ohai/plugins/linux/memory.rb @@ -16,68 +16,72 @@ # limitations under the License. # -provides "memory" +Ohai.plugin(:Memory) do + provides "memory" -memory Mash.new -memory[:swap] = Mash.new + collect_data do + memory Mash.new + memory[:swap] = Mash.new -File.open("/proc/meminfo").each do |line| - case line - when /^MemTotal:\s+(\d+) (.+)$/ - memory[:total] = "#{$1}#{$2}" - when /^MemFree:\s+(\d+) (.+)$/ - memory[:free] = "#{$1}#{$2}" - when /^Buffers:\s+(\d+) (.+)$/ - memory[:buffers] = "#{$1}#{$2}" - when /^Cached:\s+(\d+) (.+)$/ - memory[:cached] = "#{$1}#{$2}" - when /^Active:\s+(\d+) (.+)$/ - memory[:active] = "#{$1}#{$2}" - when /^Inactive:\s+(\d+) (.+)$/ - memory[:inactive] = "#{$1}#{$2}" - when /^HighTotal:\s+(\d+) (.+)$/ - memory[:high_total] = "#{$1}#{$2}" - when /^HighFree:\s+(\d+) (.+)$/ - memory[:high_free] = "#{$1}#{$2}" - when /^LowTotal:\s+(\d+) (.+)$/ - memory[:low_total] = "#{$1}#{$2}" - when /^LowFree:\s+(\d+) (.+)$/ - memory[:low_free] = "#{$1}#{$2}" - when /^Dirty:\s+(\d+) (.+)$/ - memory[:dirty] = "#{$1}#{$2}" - when /^Writeback:\s+(\d+) (.+)$/ - memory[:writeback] = "#{$1}#{$2}" - when /^AnonPages:\s+(\d+) (.+)$/ - memory[:anon_pages] = "#{$1}#{$2}" - when /^Mapped:\s+(\d+) (.+)$/ - memory[:mapped] = "#{$1}#{$2}" - when /^Slab:\s+(\d+) (.+)$/ - memory[:slab] = "#{$1}#{$2}" - when /^SReclaimable:\s+(\d+) (.+)$/ - memory[:slab_reclaimable] = "#{$1}#{$2}" - when /^SUnreclaim:\s+(\d+) (.+)$/ - memory[:slab_unreclaim] = "#{$1}#{$2}" - when /^PageTables:\s+(\d+) (.+)$/ - memory[:page_tables] = "#{$1}#{$2}" - when /^NFS_Unstable:\s+(\d+) (.+)$/ - memory[:nfs_unstable] = "#{$1}#{$2}" - when /^Bounce:\s+(\d+) (.+)$/ - memory[:bounce] = "#{$1}#{$2}" - when /^CommitLimit:\s+(\d+) (.+)$/ - memory[:commit_limit] = "#{$1}#{$2}" - when /^Committed_AS:\s+(\d+) (.+)$/ - memory[:committed_as] = "#{$1}#{$2}" - when /^VmallocTotal:\s+(\d+) (.+)$/ - memory[:vmalloc_total] = "#{$1}#{$2}" - when /^VmallocUsed:\s+(\d+) (.+)$/ - memory[:vmalloc_used] = "#{$1}#{$2}" - when /^VmallocChunk:\s+(\d+) (.+)$/ - memory[:vmalloc_chunk] = "#{$1}#{$2}" - when /^SwapCached:\s+(\d+) (.+)$/ - memory[:swap][:cached] = "#{$1}#{$2}" - when /^SwapTotal:\s+(\d+) (.+)$/ - memory[:swap][:total] = "#{$1}#{$2}" - when /^SwapFree:\s+(\d+) (.+)$/ - memory[:swap][:free] = "#{$1}#{$2}" + File.open("/proc/meminfo").each do |line| + case line + when /^MemTotal:\s+(\d+) (.+)$/ + memory[:total] = "#{$1}#{$2}" + when /^MemFree:\s+(\d+) (.+)$/ + memory[:free] = "#{$1}#{$2}" + when /^Buffers:\s+(\d+) (.+)$/ + memory[:buffers] = "#{$1}#{$2}" + when /^Cached:\s+(\d+) (.+)$/ + memory[:cached] = "#{$1}#{$2}" + when /^Active:\s+(\d+) (.+)$/ + memory[:active] = "#{$1}#{$2}" + when /^Inactive:\s+(\d+) (.+)$/ + memory[:inactive] = "#{$1}#{$2}" + when /^HighTotal:\s+(\d+) (.+)$/ + memory[:high_total] = "#{$1}#{$2}" + when /^HighFree:\s+(\d+) (.+)$/ + memory[:high_free] = "#{$1}#{$2}" + when /^LowTotal:\s+(\d+) (.+)$/ + memory[:low_total] = "#{$1}#{$2}" + when /^LowFree:\s+(\d+) (.+)$/ + memory[:low_free] = "#{$1}#{$2}" + when /^Dirty:\s+(\d+) (.+)$/ + memory[:dirty] = "#{$1}#{$2}" + when /^Writeback:\s+(\d+) (.+)$/ + memory[:writeback] = "#{$1}#{$2}" + when /^AnonPages:\s+(\d+) (.+)$/ + memory[:anon_pages] = "#{$1}#{$2}" + when /^Mapped:\s+(\d+) (.+)$/ + memory[:mapped] = "#{$1}#{$2}" + when /^Slab:\s+(\d+) (.+)$/ + memory[:slab] = "#{$1}#{$2}" + when /^SReclaimable:\s+(\d+) (.+)$/ + memory[:slab_reclaimable] = "#{$1}#{$2}" + when /^SUnreclaim:\s+(\d+) (.+)$/ + memory[:slab_unreclaim] = "#{$1}#{$2}" + when /^PageTables:\s+(\d+) (.+)$/ + memory[:page_tables] = "#{$1}#{$2}" + when /^NFS_Unstable:\s+(\d+) (.+)$/ + memory[:nfs_unstable] = "#{$1}#{$2}" + when /^Bounce:\s+(\d+) (.+)$/ + memory[:bounce] = "#{$1}#{$2}" + when /^CommitLimit:\s+(\d+) (.+)$/ + memory[:commit_limit] = "#{$1}#{$2}" + when /^Committed_AS:\s+(\d+) (.+)$/ + memory[:committed_as] = "#{$1}#{$2}" + when /^VmallocTotal:\s+(\d+) (.+)$/ + memory[:vmalloc_total] = "#{$1}#{$2}" + when /^VmallocUsed:\s+(\d+) (.+)$/ + memory[:vmalloc_used] = "#{$1}#{$2}" + when /^VmallocChunk:\s+(\d+) (.+)$/ + memory[:vmalloc_chunk] = "#{$1}#{$2}" + when /^SwapCached:\s+(\d+) (.+)$/ + memory[:swap][:cached] = "#{$1}#{$2}" + when /^SwapTotal:\s+(\d+) (.+)$/ + memory[:swap][:total] = "#{$1}#{$2}" + when /^SwapFree:\s+(\d+) (.+)$/ + memory[:swap][:free] = "#{$1}#{$2}" + end + end end end diff --git a/lib/ohai/plugins/linux/network.rb b/lib/ohai/plugins/linux/network.rb index 9f6891d4..f4258b58 100644 --- a/lib/ohai/plugins/linux/network.rb +++ b/lib/ohai/plugins/linux/network.rb @@ -17,396 +17,400 @@ # require 'ipaddr' -provides "network", "counters/network" - -def encaps_lookup(encap) - return "Loopback" if encap.eql?("Local Loopback") || encap.eql?("loopback") - return "PPP" if encap.eql?("Point-to-Point Protocol") - return "SLIP" if encap.eql?("Serial Line IP") - return "VJSLIP" if encap.eql?("VJ Serial Line IP") - return "IPIP" if encap.eql?("IPIP Tunnel") - return "6to4" if encap.eql?("IPv6-in-IPv4") - return "Ethernet" if encap.eql?("ether") - encap -end - -iface = Mash.new -net_counters = Mash.new - -# Match the lead line for an interface from iproute2 -# 3: eth0.11@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP -# The '@eth0:' portion doesn't exist on primary interfaces and thus is optional in the regex -IPROUTE_INT_REGEX = /^(\d+): ([0-9a-zA-Z@:\.\-_]*?)(@[0-9a-zA-Z]+|):\s/ - -if File.exist?("/sbin/ip") - - # families to get default routes from - families = [ - { - :name => "inet", - :default_route => "0.0.0.0/0", - :default_prefix => :default, - :neighbour_attribute => :arp - }, - { - :name => "inet6", - :default_route => "::/0", - :default_prefix => :default_inet6, - :neighbour_attribute => :neighbour_inet6 - } - ] - - popen4("ip addr") do |pid, stdin, stdout, stderr| - stdin.close - cint = nil - stdout.each do |line| - if line =~ IPROUTE_INT_REGEX - cint = $2 - iface[cint] = Mash.new - if cint =~ /^(\w+)(\d+.*)/ - iface[cint][:type] = $1 - iface[cint][:number] = $2 - end - if line =~ /mtu (\d+)/ - iface[cint][:mtu] = $1 - end +Ohai.plugin(:Network) do + provides "network", "counters/network" + + def encaps_lookup(encap) + return "Loopback" if encap.eql?("Local Loopback") || encap.eql?("loopback") + return "PPP" if encap.eql?("Point-to-Point Protocol") + return "SLIP" if encap.eql?("Serial Line IP") + return "VJSLIP" if encap.eql?("VJ Serial Line IP") + return "IPIP" if encap.eql?("IPIP Tunnel") + return "6to4" if encap.eql?("IPv6-in-IPv4") + return "Ethernet" if encap.eql?("ether") + encap + end - flags = line.scan(/(UP|BROADCAST|DEBUG|LOOPBACK|POINTTOPOINT|NOTRAILERS|LOWER_UP|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC)/) - if flags.length > 1 - iface[cint][:flags] = flags.flatten.uniq - end - end - if line =~ /link\/(\w+) ([\da-f\:]+) / - iface[cint][:encapsulation] = encaps_lookup($1) - unless $2 == "00:00:00:00:00:00" - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$2.upcase] = { "family" => "lladdr" } + collect_data do + iface = Mash.new + net_counters = Mash.new + + # Match the lead line for an interface from iproute2 + # 3: eth0.11@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP + # The '@eth0:' portion doesn't exist on primary interfaces and thus is optional in the regex + IPROUTE_INT_REGEX = /^(\d+): ([0-9a-zA-Z@:\.\-_]*?)(@[0-9a-zA-Z]+|):\s/ + + if File.exist?("/sbin/ip") + + # families to get default routes from + families = [ + { + :name => "inet", + :default_route => "0.0.0.0/0", + :default_prefix => :default, + :neighbour_attribute => :arp + }, + { + :name => "inet6", + :default_route => "::/0", + :default_prefix => :default_inet6, + :neighbour_attribute => :neighbour_inet6 + } + ] + + popen4("ip addr") do |pid, stdin, stdout, stderr| + stdin.close + cint = nil + stdout.each do |line| + if line =~ IPROUTE_INT_REGEX + cint = $2 + iface[cint] = Mash.new + if cint =~ /^(\w+)(\d+.*)/ + iface[cint][:type] = $1 + iface[cint][:number] = $2 + end + + if line =~ /mtu (\d+)/ + iface[cint][:mtu] = $1 + end + + flags = line.scan(/(UP|BROADCAST|DEBUG|LOOPBACK|POINTTOPOINT|NOTRAILERS|LOWER_UP|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC)/) + if flags.length > 1 + iface[cint][:flags] = flags.flatten.uniq + end + end + if line =~ /link\/(\w+) ([\da-f\:]+) / + iface[cint][:encapsulation] = encaps_lookup($1) + unless $2 == "00:00:00:00:00:00" + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$2.upcase] = { "family" => "lladdr" } + end + end + if line =~ /inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\/(\d{1,2}))?/ + tmp_addr, tmp_prefix = $1, $3 + tmp_prefix ||= "32" + original_int = nil + + # Are we a formerly aliased interface? + if line =~ /#{cint}:(\d+)$/ + sub_int = $1 + alias_int = "#{cint}:#{sub_int}" + original_int = cint + cint = alias_int + end + + iface[cint] = Mash.new unless iface[cint] # Create the fake alias interface if needed + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][tmp_addr] = { "family" => "inet", "prefixlen" => tmp_prefix } + iface[cint][:addresses][tmp_addr][:netmask] = IPAddr.new("255.255.255.255").mask(tmp_prefix.to_i).to_s + + if line =~ /peer (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ + iface[cint][:addresses][tmp_addr][:peer] = $1 + end + + if line =~ /brd (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ + iface[cint][:addresses][tmp_addr][:broadcast] = $1 + end + + if line =~ /scope (\w+)/ + iface[cint][:addresses][tmp_addr][:scope] = ($1.eql?("host") ? "Node" : $1.capitalize) + end + + # If we found we were an an alias interface, restore cint to its original value + cint = original_int unless original_int.nil? + end + if line =~ /inet6 ([a-f0-9\:]+)\/(\d+) scope (\w+)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + tmp_addr = $1 + iface[cint][:addresses][tmp_addr] = { "family" => "inet6", "prefixlen" => $2, "scope" => ($3.eql?("host") ? "Node" : $3.capitalize) } + end end end - if line =~ /inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\/(\d{1,2}))?/ - tmp_addr, tmp_prefix = $1, $3 - tmp_prefix ||= "32" - original_int = nil - - # Are we a formerly aliased interface? - if line =~ /#{cint}:(\d+)$/ - sub_int = $1 - alias_int = "#{cint}:#{sub_int}" - original_int = cint - cint = alias_int - end - iface[cint] = Mash.new unless iface[cint] # Create the fake alias interface if needed - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][tmp_addr] = { "family" => "inet", "prefixlen" => tmp_prefix } - iface[cint][:addresses][tmp_addr][:netmask] = IPAddr.new("255.255.255.255").mask(tmp_prefix.to_i).to_s - - if line =~ /peer (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ - iface[cint][:addresses][tmp_addr][:peer] = $1 - end + popen4("ip -d -s link") do |pid, stdin, stdout, stderr| + stdin.close + tmp_int = nil + on_rx = true + stdout.each do |line| + if line =~ IPROUTE_INT_REGEX + tmp_int = $2 + net_counters[tmp_int] = Mash.new unless net_counters[tmp_int] + end - if line =~ /brd (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ - iface[cint][:addresses][tmp_addr][:broadcast] = $1 - end + if line =~ /(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ + int = on_rx ? :rx : :tx + net_counters[tmp_int][int] = Mash.new unless net_counters[tmp_int][int] + net_counters[tmp_int][int][:bytes] = $1 + net_counters[tmp_int][int][:packets] = $2 + net_counters[tmp_int][int][:errors] = $3 + net_counters[tmp_int][int][:drop] = $4 + if(int == :rx) + net_counters[tmp_int][int][:overrun] = $5 + else + net_counters[tmp_int][int][:carrier] = $5 + net_counters[tmp_int][int][:collisions] = $6 + end + + on_rx = !on_rx + end - if line =~ /scope (\w+)/ - iface[cint][:addresses][tmp_addr][:scope] = ($1.eql?("host") ? "Node" : $1.capitalize) - end + if line =~ /qlen (\d+)/ + net_counters[tmp_int][:tx] = Mash.new unless net_counters[tmp_int][:tx] + net_counters[tmp_int][:tx][:queuelen] = $1 + end + + if line =~ /vlan id (\d+)/ + tmp_id = $1 + iface[tmp_int][:vlan] = Mash.new unless iface[tmp_int][:vlan] + iface[tmp_int][:vlan][:id] = tmp_id + + vlan_flags = line.scan(/(REORDER_HDR|GVRP|LOOSE_BINDING)/) + if vlan_flags.length > 0 + iface[tmp_int][:vlan][:flags] = vlan_flags.flatten.uniq + end + end - # If we found we were an an alias interface, restore cint to its original value - cint = original_int unless original_int.nil? - end - if line =~ /inet6 ([a-f0-9\:]+)\/(\d+) scope (\w+)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - tmp_addr = $1 - iface[cint][:addresses][tmp_addr] = { "family" => "inet6", "prefixlen" => $2, "scope" => ($3.eql?("host") ? "Node" : $3.capitalize) } - end - end - end + if line =~ /state (\w+)/ + iface[tmp_int]['state'] = $1.downcase + end - popen4("ip -d -s link") do |pid, stdin, stdout, stderr| - stdin.close - tmp_int = nil - on_rx = true - stdout.each do |line| - if line =~ IPROUTE_INT_REGEX - tmp_int = $2 - net_counters[tmp_int] = Mash.new unless net_counters[tmp_int] - end - if line =~ /(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ - int = on_rx ? :rx : :tx - net_counters[tmp_int][int] = Mash.new unless net_counters[tmp_int][int] - net_counters[tmp_int][int][:bytes] = $1 - net_counters[tmp_int][int][:packets] = $2 - net_counters[tmp_int][int][:errors] = $3 - net_counters[tmp_int][int][:drop] = $4 - if(int == :rx) - net_counters[tmp_int][int][:overrun] = $5 - else - net_counters[tmp_int][int][:carrier] = $5 - net_counters[tmp_int][int][:collisions] = $6 end - - on_rx = !on_rx end - if line =~ /qlen (\d+)/ - net_counters[tmp_int][:tx] = Mash.new unless net_counters[tmp_int][:tx] - net_counters[tmp_int][:tx][:queuelen] = $1 - end - - if line =~ /vlan id (\d+)/ - tmp_id = $1 - iface[tmp_int][:vlan] = Mash.new unless iface[tmp_int][:vlan] - iface[tmp_int][:vlan][:id] = tmp_id - - vlan_flags = line.scan(/(REORDER_HDR|GVRP|LOOSE_BINDING)/) - if vlan_flags.length > 0 - iface[tmp_int][:vlan][:flags] = vlan_flags.flatten.uniq + families.each do |family| + neigh_attr = family[:neighbour_attribute] + default_prefix = family[:default_prefix] + + popen4("ip -f #{family[:name]} neigh show") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^([a-f0-9\:\.]+)\s+dev\s+([^\s]+)\s+lladdr\s+([a-fA-F0-9\:]+)/ + unless iface[$2] + Ohai::Log.warn("neighbour list has entries for unknown interface #{iface[$2]}") + next + end + iface[$2][neigh_attr] = Mash.new unless iface[$2][neigh_attr] + iface[$2][neigh_attr][$1] = $3.downcase + end + end end - end - if line =~ /state (\w+)/ - iface[tmp_int]['state'] = $1.downcase + # checking the routing tables + # why ? + # 1) to set the default gateway and default interfaces attributes + # 2) on some occasions, the best way to select node[:ipaddress] is to look at + # the routing table source field. + # 3) and since we're at it, let's populate some :routes attributes + # (going to do that for both inet and inet6 addresses) + popen4("ip -f #{family[:name]} route show") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^([^\s]+)\s(.*)$/ + route_dest = $1 + route_ending = $2 + # + if route_ending =~ /\bdev\s+([^\s]+)\b/ + route_int = $1 + else + Ohai::Log.debug("Skipping route entry without a device: '#{line}'") + next + end + + unless iface[route_int] + Ohai::Log.debug("Skipping previously unseen interface from 'ip route show': #{route_int}") + next + end + + route_entry = Mash.new( :destination => route_dest, + :family => family[:name] ) + %w[via scope metric proto src].each do |k| + route_entry[k] = $1 if route_ending =~ /\b#{k}\s+([^\s]+)\b/ + end + + # a sanity check, especially for Linux-VServer, OpenVZ and LXC: + # don't report the route entry if the src address isn't set on the node + next if route_entry[:src] and not iface[route_int][:addresses].has_key? route_entry[:src] + + iface[route_int][:routes] = Array.new unless iface[route_int][:routes] + iface[route_int][:routes] << route_entry + end + end + end + # now looking at the routes to set the default attributes + # for information, default routes can be of this form : + # - default via 10.0.2.4 dev br0 + # - default dev br0 scope link + # - default via 10.0.3.1 dev eth1 src 10.0.3.2 metric 10 + # - default via 10.0.4.1 dev eth2 src 10.0.4.2 metric 20 + + # using a temporary var to hold routes and their interface name + routes = iface.collect do |i,iv| + iv[:routes].collect do |r| + r.merge(:dev=>i) if r[:family] == family[:name] + end.compact if iv[:routes] + end.compact.flatten + + # using a temporary var to hold the default route + # in case there are more than 1 default route, sort it by its metric + # and return the first one + # (metric value when unspecified is 0) + default_route = routes.select do |r| + r[:destination] == "default" + end.sort do |x,y| + (x[:metric].nil? ? 0 : x[:metric].to_i) <=> (y[:metric].nil? ? 0 : y[:metric].to_i) + end.first + + if default_route.nil? or default_route.empty? + Ohai::Log.debug("Unable to determine default #{family[:name]} interface") + else + network["#{default_prefix}_interface"] = default_route[:dev] + Ohai::Log.debug("#{default_prefix}_interface set to #{default_route[:dev]}") + + # setting gateway to 0.0.0.0 or :: if the default route is a link level one + network["#{default_prefix}_gateway"] = default_route[:via] ? default_route[:via] : family[:default_route].chomp("/0") + Ohai::Log.debug("#{default_prefix}_gateway set to #{network["#{default_prefix}_gateway"]}") + + # since we're at it, let's populate {ip,mac,ip6}address with the best values + # using the source field when it's specified : + # 1) in the default route + # 2) in the route entry used to reach the default gateway + route = routes.select do |r| + # selecting routes + r[:src] and # it has a src field + iface[r[:dev]] and # the iface exists + iface[r[:dev]][:addresses].has_key? r[:src] and # the src ip is set on the node + iface[r[:dev]][:addresses][r[:src]][:scope].downcase != "link" and # this isn't a link level addresse + ( r[:destination] == "default" or + ( default_route[:via] and # the default route has a gateway + IPAddress(r[:destination]).include? IPAddress(default_route[:via]) # the route matches the gateway + ) + ) + end.sort_by do |r| + # sorting the selected routes: + # - getting default routes first + # - then sort by metric + # - then by prefixlen + [ + r[:destination] == "default" ? 0 : 1, + r[:metric].nil? ? 0 : r[:metric].to_i, + # for some reason IPAddress doesn't accept "::/0", it doesn't like prefix==0 + # just a quick workaround: use 0 if IPAddress fails + begin + IPAddress( r[:destination] == "default" ? family[:default_route] : r[:destination] ).prefix + rescue + 0 + end + ] + end.first + + unless route.nil? or route.empty? + if family[:name] == "inet" + ipaddress route[:src] + macaddress iface[route[:dev]][:addresses].select{|k,v| v["family"]=="lladdr"}.first.first unless iface[route[:dev]][:flags].include? "NOARP" + else + ip6address route[:src] + end + end + end end + else - end - end - - families.each do |family| - neigh_attr = family[:neighbour_attribute] - default_prefix = family[:default_prefix] - - popen4("ip -f #{family[:name]} neigh show") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^([a-f0-9\:\.]+)\s+dev\s+([^\s]+)\s+lladdr\s+([a-fA-F0-9\:]+)/ - unless iface[$2] - Ohai::Log.warn("neighbour list has entries for unknown interface #{iface[$2]}") - next - end - iface[$2][neigh_attr] = Mash.new unless iface[$2][neigh_attr] - iface[$2][neigh_attr][$1] = $3.downcase - end + begin + route_result = from("route -n \| grep -m 1 ^0.0.0.0").split(/[ \t]+/) + network[:default_gateway], network[:default_interface] = route_result.values_at(1,7) + rescue Ohai::Exceptions::Exec + Ohai::Log.debug("Unable to determine default interface") end - end - # checking the routing tables - # why ? - # 1) to set the default gateway and default interfaces attributes - # 2) on some occasions, the best way to select node[:ipaddress] is to look at - # the routing table source field. - # 3) and since we're at it, let's populate some :routes attributes - # (going to do that for both inet and inet6 addresses) - popen4("ip -f #{family[:name]} route show") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^([^\s]+)\s(.*)$/ - route_dest = $1 - route_ending = $2 - # - if route_ending =~ /\bdev\s+([^\s]+)\b/ - route_int = $1 - else - Ohai::Log.debug("Skipping route entry without a device: '#{line}'") - next + popen4("ifconfig -a") do |pid, stdin, stdout, stderr| + stdin.close + cint = nil + stdout.each do |line| + tmp_addr = nil + # dev_valid_name in the kernel only excludes slashes, nulls, spaces + # http://git.kernel.org/?p=linux/kernel/git/stable/linux-stable.git;a=blob;f=net/core/dev.c#l851 + if line =~ /^([0-9a-zA-Z@\.\:\-_]+)\s+/ + cint = $1 + iface[cint] = Mash.new + if cint =~ /^(\w+)(\d+.*)/ + iface[cint][:type] = $1 + iface[cint][:number] = $2 + end end - - unless iface[route_int] - Ohai::Log.debug("Skipping previously unseen interface from 'ip route show': #{route_int}") - next + if line =~ /Link encap:(Local Loopback)/ || line =~ /Link encap:(.+?)\s/ + iface[cint][:encapsulation] = encaps_lookup($1) end - - route_entry = Mash.new( :destination => route_dest, - :family => family[:name] ) - %w[via scope metric proto src].each do |k| - route_entry[k] = $1 if route_ending =~ /\b#{k}\s+([^\s]+)\b/ + if line =~ /HWaddr (.+?)\s/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "lladdr" } + end + if line =~ /inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet" } + tmp_addr = $1 + end + if line =~ /inet6 addr: ([a-f0-9\:]+)\/(\d+) Scope:(\w+)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $2, "scope" => ($3.eql?("Host") ? "Node" : $3) } + end + if line =~ /Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ + iface[cint][:addresses][tmp_addr]["broadcast"] = $1 + end + if line =~ /Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ + iface[cint][:addresses][tmp_addr]["netmask"] = $1 + end + flags = line.scan(/(UP|BROADCAST|DEBUG|LOOPBACK|POINTTOPOINT|NOTRAILERS|RUNNING|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC)\s/) + if flags.length > 1 + iface[cint][:flags] = flags.flatten + end + if line =~ /MTU:(\d+)/ + iface[cint][:mtu] = $1 + end + if line =~ /P-t-P:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ + iface[cint][:peer] = $1 + end + if line =~ /RX packets:(\d+) errors:(\d+) dropped:(\d+) overruns:(\d+) frame:(\d+)/ + net_counters[cint] = Mash.new unless net_counters[cint] + net_counters[cint][:rx] = { "packets" => $1, "errors" => $2, "drop" => $3, "overrun" => $4, "frame" => $5 } + end + if line =~ /TX packets:(\d+) errors:(\d+) dropped:(\d+) overruns:(\d+) carrier:(\d+)/ + net_counters[cint][:tx] = { "packets" => $1, "errors" => $2, "drop" => $3, "overrun" => $4, "carrier" => $5 } + end + if line =~ /collisions:(\d+)/ + net_counters[cint][:tx]["collisions"] = $1 + end + if line =~ /txqueuelen:(\d+)/ + net_counters[cint][:tx]["queuelen"] = $1 + end + if line =~ /RX bytes:(\d+) \((\d+?\.\d+ .+?)\)/ + net_counters[cint][:rx]["bytes"] = $1 + end + if line =~ /TX bytes:(\d+) \((\d+?\.\d+ .+?)\)/ + net_counters[cint][:tx]["bytes"] = $1 end - - # a sanity check, especially for Linux-VServer, OpenVZ and LXC: - # don't report the route entry if the src address isn't set on the node - next if route_entry[:src] and not iface[route_int][:addresses].has_key? route_entry[:src] - - iface[route_int][:routes] = Array.new unless iface[route_int][:routes] - iface[route_int][:routes] << route_entry - end - end - end - # now looking at the routes to set the default attributes - # for information, default routes can be of this form : - # - default via 10.0.2.4 dev br0 - # - default dev br0 scope link - # - default via 10.0.3.1 dev eth1 src 10.0.3.2 metric 10 - # - default via 10.0.4.1 dev eth2 src 10.0.4.2 metric 20 - - # using a temporary var to hold routes and their interface name - routes = iface.collect do |i,iv| - iv[:routes].collect do |r| - r.merge(:dev=>i) if r[:family] == family[:name] - end.compact if iv[:routes] - end.compact.flatten - - # using a temporary var to hold the default route - # in case there are more than 1 default route, sort it by its metric - # and return the first one - # (metric value when unspecified is 0) - default_route = routes.select do |r| - r[:destination] == "default" - end.sort do |x,y| - (x[:metric].nil? ? 0 : x[:metric].to_i) <=> (y[:metric].nil? ? 0 : y[:metric].to_i) - end.first - - if default_route.nil? or default_route.empty? - Ohai::Log.debug("Unable to determine default #{family[:name]} interface") - else - network["#{default_prefix}_interface"] = default_route[:dev] - Ohai::Log.debug("#{default_prefix}_interface set to #{default_route[:dev]}") - - # setting gateway to 0.0.0.0 or :: if the default route is a link level one - network["#{default_prefix}_gateway"] = default_route[:via] ? default_route[:via] : family[:default_route].chomp("/0") - Ohai::Log.debug("#{default_prefix}_gateway set to #{network["#{default_prefix}_gateway"]}") - - # since we're at it, let's populate {ip,mac,ip6}address with the best values - # using the source field when it's specified : - # 1) in the default route - # 2) in the route entry used to reach the default gateway - route = routes.select do |r| - # selecting routes - r[:src] and # it has a src field - iface[r[:dev]] and # the iface exists - iface[r[:dev]][:addresses].has_key? r[:src] and # the src ip is set on the node - iface[r[:dev]][:addresses][r[:src]][:scope].downcase != "link" and # this isn't a link level addresse - ( r[:destination] == "default" or - ( default_route[:via] and # the default route has a gateway - IPAddress(r[:destination]).include? IPAddress(default_route[:via]) # the route matches the gateway - ) - ) - end.sort_by do |r| - # sorting the selected routes: - # - getting default routes first - # - then sort by metric - # - then by prefixlen - [ - r[:destination] == "default" ? 0 : 1, - r[:metric].nil? ? 0 : r[:metric].to_i, - # for some reason IPAddress doesn't accept "::/0", it doesn't like prefix==0 - # just a quick workaround: use 0 if IPAddress fails - begin - IPAddress( r[:destination] == "default" ? family[:default_route] : r[:destination] ).prefix - rescue - 0 - end - ] - end.first - - unless route.nil? or route.empty? - if family[:name] == "inet" - ipaddress route[:src] - macaddress iface[route[:dev]][:addresses].select{|k,v| v["family"]=="lladdr"}.first.first unless iface[route[:dev]][:flags].include? "NOARP" - else - ip6address route[:src] end end - end - end - -else - begin - route_result = from("route -n \| grep -m 1 ^0.0.0.0").split(/[ \t]+/) - network[:default_gateway], network[:default_interface] = route_result.values_at(1,7) - rescue Ohai::Exceptions::Exec - Ohai::Log.debug("Unable to determine default interface") - end - popen4("ifconfig -a") do |pid, stdin, stdout, stderr| - stdin.close - cint = nil - stdout.each do |line| - tmp_addr = nil - # dev_valid_name in the kernel only excludes slashes, nulls, spaces - # http://git.kernel.org/?p=linux/kernel/git/stable/linux-stable.git;a=blob;f=net/core/dev.c#l851 - if line =~ /^([0-9a-zA-Z@\.\:\-_]+)\s+/ - cint = $1 - iface[cint] = Mash.new - if cint =~ /^(\w+)(\d+.*)/ - iface[cint][:type] = $1 - iface[cint][:number] = $2 + popen4("arp -an") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^\S+ \((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) \[(\w+)\] on ([0-9a-zA-Z\.\:\-]+)/ + next unless iface[$4] # this should never happen + iface[$4][:arp] = Mash.new unless iface[$4][:arp] + iface[$4][:arp][$1] = $2.downcase + end end end - if line =~ /Link encap:(Local Loopback)/ || line =~ /Link encap:(.+?)\s/ - iface[cint][:encapsulation] = encaps_lookup($1) - end - if line =~ /HWaddr (.+?)\s/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "lladdr" } - end - if line =~ /inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet" } - tmp_addr = $1 - end - if line =~ /inet6 addr: ([a-f0-9\:]+)\/(\d+) Scope:(\w+)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $2, "scope" => ($3.eql?("Host") ? "Node" : $3) } - end - if line =~ /Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ - iface[cint][:addresses][tmp_addr]["broadcast"] = $1 - end - if line =~ /Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ - iface[cint][:addresses][tmp_addr]["netmask"] = $1 - end - flags = line.scan(/(UP|BROADCAST|DEBUG|LOOPBACK|POINTTOPOINT|NOTRAILERS|RUNNING|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC)\s/) - if flags.length > 1 - iface[cint][:flags] = flags.flatten - end - if line =~ /MTU:(\d+)/ - iface[cint][:mtu] = $1 - end - if line =~ /P-t-P:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ - iface[cint][:peer] = $1 - end - if line =~ /RX packets:(\d+) errors:(\d+) dropped:(\d+) overruns:(\d+) frame:(\d+)/ - net_counters[cint] = Mash.new unless net_counters[cint] - net_counters[cint][:rx] = { "packets" => $1, "errors" => $2, "drop" => $3, "overrun" => $4, "frame" => $5 } - end - if line =~ /TX packets:(\d+) errors:(\d+) dropped:(\d+) overruns:(\d+) carrier:(\d+)/ - net_counters[cint][:tx] = { "packets" => $1, "errors" => $2, "drop" => $3, "overrun" => $4, "carrier" => $5 } - end - if line =~ /collisions:(\d+)/ - net_counters[cint][:tx]["collisions"] = $1 - end - if line =~ /txqueuelen:(\d+)/ - net_counters[cint][:tx]["queuelen"] = $1 - end - if line =~ /RX bytes:(\d+) \((\d+?\.\d+ .+?)\)/ - net_counters[cint][:rx]["bytes"] = $1 - end - if line =~ /TX bytes:(\d+) \((\d+?\.\d+ .+?)\)/ - net_counters[cint][:tx]["bytes"] = $1 - end - end - end - - popen4("arp -an") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^\S+ \((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) \[(\w+)\] on ([0-9a-zA-Z\.\:\-]+)/ - next unless iface[$4] # this should never happen - iface[$4][:arp] = Mash.new unless iface[$4][:arp] - iface[$4][:arp][$1] = $2.downcase - end end - end -end - - -counters[:network][:interfaces] = net_counters -network["interfaces"] = iface + counters[:network][:interfaces] = net_counters + network["interfaces"] = iface + end +end diff --git a/lib/ohai/plugins/linux/platform.rb b/lib/ohai/plugins/linux/platform.rb index a7bb6dd0..f5bdac98 100644 --- a/lib/ohai/plugins/linux/platform.rb +++ b/lib/ohai/plugins/linux/platform.rb @@ -16,101 +16,105 @@ # limitations under the License. # -def get_redhatish_platform(contents) - contents[/^Red Hat/i] ? "redhat" : contents[/(\w+)/i, 1].downcase -end +Ohai.plugin(:Platform) do + provides "platform", "platform_version", "platform_family" -def get_redhatish_version(contents) - contents[/Rawhide/i] ? contents[/((\d+) \(Rawhide\))/i, 1].downcase : contents[/release ([\d\.]+)/, 1] -end + depends 'linux::lsb' -provides "platform", "platform_version", "platform_family" + def get_redhatish_platform(contents) + contents[/^Red Hat/i] ? "redhat" : contents[/(\w+)/i, 1].downcase + end -require_plugin 'linux::lsb' + def get_redhatish_version(contents) + contents[/Rawhide/i] ? contents[/((\d+) \(Rawhide\))/i, 1].downcase : contents[/release ([\d\.]+)/, 1] + end -# platform [ and platform_version ? ] should be lower case to avoid dealing with RedHat/Redhat/redhat matching -if File.exists?("/etc/oracle-release") - contents = File.read("/etc/oracle-release").chomp - platform "oracle" - platform_version get_redhatish_version(contents) -elsif File.exists?("/etc/enterprise-release") - contents = File.read("/etc/enterprise-release").chomp - platform "oracle" - platform_version get_redhatish_version(contents) -elsif File.exists?("/etc/debian_version") - # Ubuntu, GCEL and Debian both have /etc/debian_version - # Ubuntu, GCEL should always have a working lsb, debian does not by default - if lsb[:id] =~ /Ubuntu/i - platform "ubuntu" - platform_version lsb[:release] - elsif lsb[:id] =~ /gcel/i - platform "gcel" - platform_version lsb[:release] - elsif lsb[:id] =~ /LinuxMint/i - platform "linuxmint" - platform_version lsb[:release] - else - if File.exists?("/usr/bin/raspi-config") - platform "raspbian" - else - platform "debian" + collect_data do + # platform [ and platform_version ? ] should be lower case to avoid dealing with RedHat/Redhat/redhat matching + if File.exists?("/etc/oracle-release") + contents = File.read("/etc/oracle-release").chomp + platform "oracle" + platform_version get_redhatish_version(contents) + elsif File.exists?("/etc/enterprise-release") + contents = File.read("/etc/enterprise-release").chomp + platform "oracle" + platform_version get_redhatish_version(contents) + elsif File.exists?("/etc/debian_version") + # Ubuntu, GCEL and Debian both have /etc/debian_version + # Ubuntu, GCEL should always have a working lsb, debian does not by default + if lsb[:id] =~ /Ubuntu/i + platform "ubuntu" + platform_version lsb[:release] + elsif lsb[:id] =~ /gcel/i + platform "gcel" + platform_version lsb[:release] + elsif lsb[:id] =~ /LinuxMint/i + platform "linuxmint" + platform_version lsb[:release] + else + if File.exists?("/usr/bin/raspi-config") + platform "raspbian" + else + platform "debian" + end + platform_version File.read("/etc/debian_version").chomp + end + elsif File.exists?("/etc/redhat-release") + contents = File.read("/etc/redhat-release").chomp + platform get_redhatish_platform(contents) + platform_version get_redhatish_version(contents) + elsif File.exists?("/etc/system-release") + contents = File.read("/etc/system-release").chomp + platform get_redhatish_platform(contents) + platform_version get_redhatish_version(contents) + elsif File.exists?('/etc/gentoo-release') + platform "gentoo" + platform_version File.read('/etc/gentoo-release').scan(/(\d+|\.+)/).join + elsif File.exists?('/etc/SuSE-release') + platform "suse" + suse_release = File.read("/etc/SuSE-release") + platform_version suse_release.scan(/VERSION = (\d+)\nPATCHLEVEL = (\d+)/).flatten.join(".") + platform_version suse_release.scan(/VERSION = ([\d\.]{2,})/).flatten.join(".") if platform_version == "" + elsif File.exists?('/etc/slackware-version') + platform "slackware" + platform_version File.read("/etc/slackware-version").scan(/(\d+|\.+)/).join + elsif File.exists?('/etc/arch-release') + platform "arch" + # no way to determine platform_version in a rolling release distribution + # kernel release will be used - ex. 2.6.32-ARCH + elsif lsb[:id] =~ /RedHat/i + platform "redhat" + platform_version lsb[:release] + elsif lsb[:id] =~ /Amazon/i + platform "amazon" + platform_version lsb[:release] + elsif lsb[:id] =~ /ScientificSL/i + platform "scientific" + platform_version lsb[:release] + elsif lsb[:id] =~ /XenServer/i + platform "xenserver" + platform_version lsb[:release] + elsif lsb[:id] # LSB can provide odd data that changes between releases, so we currently fall back on it rather than dealing with its subtleties + platform lsb[:id].downcase + platform_version lsb[:release] end - platform_version File.read("/etc/debian_version").chomp - end -elsif File.exists?("/etc/redhat-release") - contents = File.read("/etc/redhat-release").chomp - platform get_redhatish_platform(contents) - platform_version get_redhatish_version(contents) -elsif File.exists?("/etc/system-release") - contents = File.read("/etc/system-release").chomp - platform get_redhatish_platform(contents) - platform_version get_redhatish_version(contents) -elsif File.exists?('/etc/gentoo-release') - platform "gentoo" - platform_version File.read('/etc/gentoo-release').scan(/(\d+|\.+)/).join -elsif File.exists?('/etc/SuSE-release') - platform "suse" - suse_release = File.read("/etc/SuSE-release") - platform_version suse_release.scan(/VERSION = (\d+)\nPATCHLEVEL = (\d+)/).flatten.join(".") - platform_version suse_release.scan(/VERSION = ([\d\.]{2,})/).flatten.join(".") if platform_version == "" -elsif File.exists?('/etc/slackware-version') - platform "slackware" - platform_version File.read("/etc/slackware-version").scan(/(\d+|\.+)/).join -elsif File.exists?('/etc/arch-release') - platform "arch" - # no way to determine platform_version in a rolling release distribution - # kernel release will be used - ex. 2.6.32-ARCH -elsif lsb[:id] =~ /RedHat/i - platform "redhat" - platform_version lsb[:release] -elsif lsb[:id] =~ /Amazon/i - platform "amazon" - platform_version lsb[:release] -elsif lsb[:id] =~ /ScientificSL/i - platform "scientific" - platform_version lsb[:release] -elsif lsb[:id] =~ /XenServer/i - platform "xenserver" - platform_version lsb[:release] -elsif lsb[:id] # LSB can provide odd data that changes between releases, so we currently fall back on it rather than dealing with its subtleties - platform lsb[:id].downcase - platform_version lsb[:release] -end -case platform - when /debian/, /ubuntu/, /linuxmint/, /raspbian/, /gcel/ - platform_family "debian" - when /fedora/ - platform_family "fedora" - when /oracle/, /centos/, /redhat/, /scientific/, /enterpriseenterprise/, /amazon/, /xenserver/ # Note that 'enterpriseenterprise' is oracle's LSB "distributor ID" - platform_family "rhel" - when /suse/ - platform_family "suse" - when /gentoo/ - platform_family "gentoo" - when /slackware/ - platform_family "slackware" - when /arch/ - platform_family "arch" + case platform + when /debian/, /ubuntu/, /linuxmint/, /raspbian/, /gcel/ + platform_family "debian" + when /fedora/ + platform_family "fedora" + when /oracle/, /centos/, /redhat/, /scientific/, /enterpriseenterprise/, /amazon/, /xenserver/ # Note that 'enterpriseenterprise' is oracle's LSB "distributor ID" + platform_family "rhel" + when /suse/ + platform_family "suse" + when /gentoo/ + platform_family "gentoo" + when /slackware/ + platform_family "slackware" + when /arch/ + platform_family "arch" + end + end end diff --git a/lib/ohai/plugins/linux/ps.rb b/lib/ohai/plugins/linux/ps.rb index ad4760a8..c3a1aebd 100644 --- a/lib/ohai/plugins/linux/ps.rb +++ b/lib/ohai/plugins/linux/ps.rb @@ -16,8 +16,12 @@ # limitations under the License. # -provides "command/ps" +Ohai.plugin(:Ps) do + provides "command/ps" -require_plugin 'command' + depends 'command' -command[:ps] = 'ps -ef' + collect_data do + command[:ps] = 'ps -ef' + end +end diff --git a/lib/ohai/plugins/linux/uptime.rb b/lib/ohai/plugins/linux/uptime.rb index 29f48eec..2c488809 100644 --- a/lib/ohai/plugins/linux/uptime.rb +++ b/lib/ohai/plugins/linux/uptime.rb @@ -16,13 +16,14 @@ # limitations under the License. # -provides "uptime", "idletime", "uptime_seconds", "idletime_seconds" - -uptime, idletime = File.open("/proc/uptime").gets.split(" ") -uptime_seconds uptime.to_i -uptime seconds_to_human(uptime.to_i) -idletime_seconds idletime.to_i -idletime seconds_to_human(idletime.to_i) - - +Ohai.plugin(:Uptime) do + provides "uptime", "idletime", "uptime_seconds", "idletime_seconds" + collect_data do + uptime, idletime = File.open("/proc/uptime").gets.split(" ") + uptime_seconds uptime.to_i + uptime seconds_to_human(uptime.to_i) + idletime_seconds idletime.to_i + idletime seconds_to_human(idletime.to_i) + end +end diff --git a/lib/ohai/plugins/linux/virtualization.rb b/lib/ohai/plugins/linux/virtualization.rb index 9cdaa9b6..7002ff25 100644 --- a/lib/ohai/plugins/linux/virtualization.rb +++ b/lib/ohai/plugins/linux/virtualization.rb @@ -16,110 +16,114 @@ # limitations under the License. # -provides "virtualization" +Ohai.plugin(:Virtualization) do + provides "virtualization" -virtualization Mash.new + collect_data do + virtualization Mash.new -# if it is possible to detect paravirt vs hardware virt, it should be put in -# virtualization[:mechanism] + # if it is possible to detect paravirt vs hardware virt, it should be put in + # virtualization[:mechanism] -## Xen -# /proc/xen is an empty dir for EL6 + Linode Guests -if File.exists?("/proc/xen") - virtualization[:system] = "xen" - # Assume guest - virtualization[:role] = "guest" + ## Xen + # /proc/xen is an empty dir for EL6 + Linode Guests + if File.exists?("/proc/xen") + virtualization[:system] = "xen" + # Assume guest + virtualization[:role] = "guest" - # This file should exist on most Xen systems, normally empty for guests - if File.exists?("/proc/xen/capabilities") - if File.read("/proc/xen/capabilities") =~ /control_d/i - virtualization[:role] = "host" + # This file should exist on most Xen systems, normally empty for guests + if File.exists?("/proc/xen/capabilities") + if File.read("/proc/xen/capabilities") =~ /control_d/i + virtualization[:role] = "host" + end + end end - end -end - -# Xen Notes: -# - cpuid of guests, if we could get it, would also be a clue -# - may be able to determine if under paravirt from /dev/xen/evtchn (See OHAI-253) -# - EL6 guests carry a 'hypervisor' cpu flag -# - Additional edge cases likely should not change the above assumptions -# but rather be additive - btm - -# Detect from kernel module -if File.exists?("/proc/modules") - modules = File.read("/proc/modules") - if modules =~ /^kvm/ - virtualization[:system] = "kvm" - virtualization[:role] = "host" - elsif modules =~ /^vboxdrv/ - virtualization[:system] = "vbox" - virtualization[:role] = "host" - elsif modules =~ /^vboxguest/ - virtualization[:system] = "vbox" - virtualization[:role] = "guest" - end -end -# Detect KVM/QEMU from cpuinfo, report as KVM -# We could pick KVM from 'Booting paravirtualized kernel on KVM' in dmesg -# 2.6.27-9-server (intrepid) has this / 2.6.18-6-amd64 (etch) does not -# It would be great if we could read pv_info in the kernel -# Wait for reply to: http://article.gmane.org/gmane.comp.emulators.kvm.devel/27885 -if File.exists?("/proc/cpuinfo") - if File.read("/proc/cpuinfo") =~ /QEMU Virtual CPU/ - virtualization[:system] = "kvm" - virtualization[:role] = "guest" - end -end + # Xen Notes: + # - cpuid of guests, if we could get it, would also be a clue + # - may be able to determine if under paravirt from /dev/xen/evtchn (See OHAI-253) + # - EL6 guests carry a 'hypervisor' cpu flag + # - Additional edge cases likely should not change the above assumptions + # but rather be additive - btm -# Detect OpenVZ / Virtuozzo. -# http://wiki.openvz.org/BC_proc_entries -if File.exists?("/proc/bc/0") - virtualization[:system] = "openvz" - virtualization[:role] = "host" -elsif File.exists?("/proc/vz") - virtualization[:system] = "openvz" - virtualization[:role] = "guest" -end - -# http://www.dmo.ca/blog/detecting-virtualization-on-linux -if File.exists?("/usr/sbin/dmidecode") - popen4("dmidecode") do |pid, stdin, stdout, stderr| - stdin.close - dmi_info = stdout.read - case dmi_info - when /Manufacturer: Microsoft/ - if dmi_info =~ /Product Name: Virtual Machine/ - virtualization[:system] = "virtualpc" - virtualization[:role] = "guest" - end - when /Manufacturer: VMware/ - if dmi_info =~ /Product Name: VMware Virtual Platform/ - virtualization[:system] = "vmware" + # Detect from kernel module + if File.exists?("/proc/modules") + modules = File.read("/proc/modules") + if modules =~ /^kvm/ + virtualization[:system] = "kvm" + virtualization[:role] = "host" + elsif modules =~ /^vboxdrv/ + virtualization[:system] = "vbox" + virtualization[:role] = "host" + elsif modules =~ /^vboxguest/ + virtualization[:system] = "vbox" virtualization[:role] = "guest" end - when /Manufacturer: Xen/ - if dmi_info =~ /Product Name: HVM domU/ - virtualization[:system] = "xen" + end + + # Detect KVM/QEMU from cpuinfo, report as KVM + # We could pick KVM from 'Booting paravirtualized kernel on KVM' in dmesg + # 2.6.27-9-server (intrepid) has this / 2.6.18-6-amd64 (etch) does not + # It would be great if we could read pv_info in the kernel + # Wait for reply to: http://article.gmane.org/gmane.comp.emulators.kvm.devel/27885 + if File.exists?("/proc/cpuinfo") + if File.read("/proc/cpuinfo") =~ /QEMU Virtual CPU/ + virtualization[:system] = "kvm" virtualization[:role] = "guest" end - else - nil end - end -end - -# Detect Linux-VServer -if File.exists?("/proc/self/status") - proc_self_status = File.read("/proc/self/status") - vxid = proc_self_status.match(/^(s_context|VxID): (\d+)$/) - if vxid and vxid[2] - virtualization[:system] = "linux-vserver" - if vxid[2] == "0" + # Detect OpenVZ / Virtuozzo. + # http://wiki.openvz.org/BC_proc_entries + if File.exists?("/proc/bc/0") + virtualization[:system] = "openvz" virtualization[:role] = "host" - else + elsif File.exists?("/proc/vz") + virtualization[:system] = "openvz" virtualization[:role] = "guest" - end + end + + # http://www.dmo.ca/blog/detecting-virtualization-on-linux + if File.exists?("/usr/sbin/dmidecode") + popen4("dmidecode") do |pid, stdin, stdout, stderr| + stdin.close + dmi_info = stdout.read + case dmi_info + when /Manufacturer: Microsoft/ + if dmi_info =~ /Product Name: Virtual Machine/ + virtualization[:system] = "virtualpc" + virtualization[:role] = "guest" + end + when /Manufacturer: VMware/ + if dmi_info =~ /Product Name: VMware Virtual Platform/ + virtualization[:system] = "vmware" + virtualization[:role] = "guest" + end + when /Manufacturer: Xen/ + if dmi_info =~ /Product Name: HVM domU/ + virtualization[:system] = "xen" + virtualization[:role] = "guest" + end + else + nil + end + + end + end + + # Detect Linux-VServer + if File.exists?("/proc/self/status") + proc_self_status = File.read("/proc/self/status") + vxid = proc_self_status.match(/^(s_context|VxID): (\d+)$/) + if vxid and vxid[2] + virtualization[:system] = "linux-vserver" + if vxid[2] == "0" + virtualization[:role] = "host" + else + virtualization[:role] = "guest" + end + end + end end end diff --git a/lib/ohai/plugins/lua.rb b/lib/ohai/plugins/lua.rb index 80fb33a5..efd31b77 100644 --- a/lib/ohai/plugins/lua.rb +++ b/lib/ohai/plugins/lua.rb @@ -16,19 +16,23 @@ # limitations under the License. # -provides "languages/lua" +Ohai.plugin(:Lua) do + provides "languages/lua" -require_plugin "languages" + depends "languages" -output = nil + collect_data do + output = nil -lua = Mash.new + lua = Mash.new -status, stdout, stderr = run_command(:no_status_check => true, :command => "lua -v") -if status == 0 - output = stderr.split - if output.length >= 1 - lua[:version] = output[1] + status, stdout, stderr = run_command(:no_status_check => true, :command => "lua -v") + if status == 0 + output = stderr.split + if output.length >= 1 + lua[:version] = output[1] + end + languages[:lua] = lua if lua[:version] + end end - languages[:lua] = lua if lua[:version] end diff --git a/lib/ohai/plugins/mono.rb b/lib/ohai/plugins/mono.rb index ca921a9b..47333536 100644 --- a/lib/ohai/plugins/mono.rb +++ b/lib/ohai/plugins/mono.rb @@ -16,22 +16,26 @@ # limitations under the License. # -provides "languages/mono" +Ohai.plugin(:Mono) do + provides "languages/mono" -require_plugin "languages" + depends "languages" -output = nil + collect_data do + output = nil -mono = Mash.new + mono = Mash.new -status, stdout, stderr = run_command(:no_status_check => true, :command => "mono -V") -if status == 0 - output = stdout.split - if output.length >= 4 - mono[:version] = output[4] + status, stdout, stderr = run_command(:no_status_check => true, :command => "mono -V") + if status == 0 + output = stdout.split + if output.length >= 4 + mono[:version] = output[4] + end + if output.length >= 11 + mono[:builddate] = "%s %s %s %s" % [output[6],output[7],output[8],output[11].gsub!(/\)/,'')] + end + languages[:mono] = mono if mono[:version] + end end - if output.length >= 11 - mono[:builddate] = "%s %s %s %s" % [output[6],output[7],output[8],output[11].gsub!(/\)/,'')] - end - languages[:mono] = mono if mono[:version] end diff --git a/lib/ohai/plugins/netbsd/cpu.rb b/lib/ohai/plugins/netbsd/cpu.rb index 5063db58..2e7f3470 100644 --- a/lib/ohai/plugins/netbsd/cpu.rb +++ b/lib/ohai/plugins/netbsd/cpu.rb @@ -16,33 +16,37 @@ # limitations under the License. # -provides 'cpu' +Ohai.plugin(:Cpu) do + provides 'cpu' -cpuinfo = Mash.new + collect_data do + cpuinfo = Mash.new -# NetBSD provides some cpu information via sysctl, and a little via dmesg.boot -# unlike OpenBSD and FreeBSD, NetBSD does not provide information about the -# available instruction set -# cpu0 at mainbus0 apid 0: Intel 686-class, 2134MHz, id 0x6f6 + # NetBSD provides some cpu information via sysctl, and a little via dmesg.boot + # unlike OpenBSD and FreeBSD, NetBSD does not provide information about the + # available instruction set + # cpu0 at mainbus0 apid 0: Intel 686-class, 2134MHz, id 0x6f6 -File.open("/var/run/dmesg.boot").each do |line| - case line - when /cpu[\d\w\s]+:\s([\w\s\-]+),\s+(\w+),/ - cpuinfo[:model_name] = $1 - cpuinfo[:mhz] = $2.gsub(/mhz/i, "") - end -end + File.open("/var/run/dmesg.boot").each do |line| + case line + when /cpu[\d\w\s]+:\s([\w\s\-]+),\s+(\w+),/ + cpuinfo[:model_name] = $1 + cpuinfo[:mhz] = $2.gsub(/mhz/i, "") + end + end -flags = [] -popen4("dmidecode") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^\s+([A-Z\d-]+)\s+\([\w\s-]+\)$/ - flags << $1.downcase + flags = [] + popen4("dmidecode") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^\s+([A-Z\d-]+)\s+\([\w\s-]+\)$/ + flags << $1.downcase + end + end end - end -end -cpuinfo[:flags] = flags unless flags.empty? + cpuinfo[:flags] = flags unless flags.empty? -cpu cpuinfo + cpu cpuinfo + end +end diff --git a/lib/ohai/plugins/netbsd/filesystem.rb b/lib/ohai/plugins/netbsd/filesystem.rb index 90a76498..c50be3b9 100644 --- a/lib/ohai/plugins/netbsd/filesystem.rb +++ b/lib/ohai/plugins/netbsd/filesystem.rb @@ -16,42 +16,46 @@ # limitations under the License. # -provides "filesystem" +Ohai.plugin(:Filesystem) do + provides "filesystem" -fs = Mash.new + collect_data do + fs = Mash.new -# Grab filesystem data from df -popen4("df") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^Filesystem/ - next - when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ - filesystem = $1 - fs[filesystem] = Mash.new - fs[filesystem]['kb_size'] = $2 - fs[filesystem]['kb_used'] = $3 - fs[filesystem]['kb_available'] = $4 - fs[filesystem]['percent_used'] = $5 - fs[filesystem]['mount'] = $6 + # Grab filesystem data from df + popen4("df") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^Filesystem/ + next + when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ + filesystem = $1 + fs[filesystem] = Mash.new + fs[filesystem]['kb_size'] = $2 + fs[filesystem]['kb_used'] = $3 + fs[filesystem]['kb_available'] = $4 + fs[filesystem]['percent_used'] = $5 + fs[filesystem]['mount'] = $6 + end + end end - end -end -# Grab mount information from mount -popen4("mount -l") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/ - filesystem = $1 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem]['mount'] = $2 - fs[filesystem]['fs_type'] = $3 - fs[filesystem]['mount-options'] = $4.split(/,\s*/) + # Grab mount information from mount + popen4("mount -l") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/ + filesystem = $1 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem]['mount'] = $2 + fs[filesystem]['fs_type'] = $3 + fs[filesystem]['mount-options'] = $4.split(/,\s*/) + end + end end + + # Set the filesystem data + filesystem fs end end - -# Set the filesystem data -filesystem fs diff --git a/lib/ohai/plugins/netbsd/hostname.rb b/lib/ohai/plugins/netbsd/hostname.rb index 337203dd..a25ef821 100644 --- a/lib/ohai/plugins/netbsd/hostname.rb +++ b/lib/ohai/plugins/netbsd/hostname.rb @@ -16,7 +16,11 @@ # limitations under the License. # -provides "hostname", "fqdn" +Ohai.plugin(:Hostname) do + provides "hostname", "fqdn" -hostname from("hostname -s") -fqdn from("hostname") + collect_data do + hostname from("hostname -s") + fqdn from("hostname") + end +end diff --git a/lib/ohai/plugins/netbsd/kernel.rb b/lib/ohai/plugins/netbsd/kernel.rb index d859eef8..204d42e5 100644 --- a/lib/ohai/plugins/netbsd/kernel.rb +++ b/lib/ohai/plugins/netbsd/kernel.rb @@ -16,20 +16,24 @@ # limitations under the License. # -provides "kernel" +Ohai.plugin(:Kernel) do + provides "kernel" -kernel[:os] = kernel[:name] -kernel[:securelevel] = from_with_regex("sysctl kern.securelevel", /kern.securelevel=(.+)$/) + collect_data do + kernel[:os] = kernel[:name] + kernel[:securelevel] = from_with_regex("sysctl kern.securelevel", /kern.securelevel=(.+)$/) -mod = Mash.new -popen4("/usr/bin/modstat") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # 1 7 0xc0400000 97f830 kernel - if line =~ /(\d+)\s+(\d+)\s+([0-9a-fx]+)\s+([0-9a-fx]+)\s+([a-zA-Z0-9\_]+)/ - kld[$5] = { :size => $4, :refcount => $2 } + mod = Mash.new + popen4("/usr/bin/modstat") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # 1 7 0xc0400000 97f830 kernel + if line =~ /(\d+)\s+(\d+)\s+([0-9a-fx]+)\s+([0-9a-fx]+)\s+([a-zA-Z0-9\_]+)/ + kld[$5] = { :size => $4, :refcount => $2 } + end + end end + + kernel[:modules] = mod unless mod.empty? end end - -kernel[:modules] = mod unless mod.empty? diff --git a/lib/ohai/plugins/netbsd/memory.rb b/lib/ohai/plugins/netbsd/memory.rb index 62772d5e..0cf84220 100644 --- a/lib/ohai/plugins/netbsd/memory.rb +++ b/lib/ohai/plugins/netbsd/memory.rb @@ -16,83 +16,87 @@ # limitations under the License. # -provides "memory" +Ohai.plugin(:Memory) do + provides "memory" -memory Mash.new -memory[:swap] = Mash.new + collect_data do + memory Mash.new + memory[:swap] = Mash.new -# $ vmstat -s -# 4096 bytes per page -# 514011 pages managed -# 224519 pages free -# 209339 pages active -# 4647 pages inactive -# 0 pages being paged out -# 5 pages wired -# 0 pages zeroed -# 4 pages reserved for pagedaemon -# 6 pages reserved for kernel -# 262205 swap pages -# 0 swap pages in use -# 0 total anon's in system -# 0 free anon's -# 1192991609 page faults -# 1369579301 traps -# 814549706 interrupts -# 771702498 cpu context switches -# 208810590 fpu context switches -# 492361360 software interrupts -# 1161998825 syscalls -# 0 pagein operations -# 0 swap ins -# 0 swap outs -# 768352 forks -# 16 forks where vmspace is shared -# 1763 kernel map entries -# 0 number of times the pagedaemon woke up -# 0 revolutions of the clock hand -# 0 pages freed by pagedaemon -# 0 pages scanned by pagedaemon -# 0 pages reactivated by pagedaemon -# 0 busy pages found by pagedaemon -# 1096393776 total name lookups -# cache hits (37% pos + 2% neg) system 1% per-directory -# deletions 0%, falsehits 6%, toolong 26% -# 0 select collisions + # $ vmstat -s + # 4096 bytes per page + # 514011 pages managed + # 224519 pages free + # 209339 pages active + # 4647 pages inactive + # 0 pages being paged out + # 5 pages wired + # 0 pages zeroed + # 4 pages reserved for pagedaemon + # 6 pages reserved for kernel + # 262205 swap pages + # 0 swap pages in use + # 0 total anon's in system + # 0 free anon's + # 1192991609 page faults + # 1369579301 traps + # 814549706 interrupts + # 771702498 cpu context switches + # 208810590 fpu context switches + # 492361360 software interrupts + # 1161998825 syscalls + # 0 pagein operations + # 0 swap ins + # 0 swap outs + # 768352 forks + # 16 forks where vmspace is shared + # 1763 kernel map entries + # 0 number of times the pagedaemon woke up + # 0 revolutions of the clock hand + # 0 pages freed by pagedaemon + # 0 pages scanned by pagedaemon + # 0 pages reactivated by pagedaemon + # 0 busy pages found by pagedaemon + # 1096393776 total name lookups + # cache hits (37% pos + 2% neg) system 1% per-directory + # deletions 0%, falsehits 6%, toolong 26% + # 0 select collisions -popen4("vmstat -s") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /(\d+) bytes per page/ - memory[:page_size] = $1 - when /(\d+) pages managed/ - memory[:page_count] = $1 - memory[:total] = memory[:page_size].to_i * memory[:page_count].to_i - when /(\d+) pages free/ - memory[:free] = memory[:page_size].to_i * $1.to_i - when /(\d+) pages active/ - memory[:active] = memory[:page_size].to_i * $1.to_i - when /(\d+) pages inactive/ - memory[:inactive] = memory[:page_size].to_i * $1.to_i - when /(\d+) pages wired/ - memory[:wired] = memory[:page_size].to_i * $1.to_i + popen4("vmstat -s") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /(\d+) bytes per page/ + memory[:page_size] = $1 + when /(\d+) pages managed/ + memory[:page_count] = $1 + memory[:total] = memory[:page_size].to_i * memory[:page_count].to_i + when /(\d+) pages free/ + memory[:free] = memory[:page_size].to_i * $1.to_i + when /(\d+) pages active/ + memory[:active] = memory[:page_size].to_i * $1.to_i + when /(\d+) pages inactive/ + memory[:inactive] = memory[:page_size].to_i * $1.to_i + when /(\d+) pages wired/ + memory[:wired] = memory[:page_size].to_i * $1.to_i + end end - end -end + end -popen4("swapctl -l") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # Device 1024-blocks Used Avail Capacity Priority - # swap_device 1048824 0 1048824 0% 0 - if line =~ /^([\d\w\/]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([\d\%]+)/ - mdev = $1 - memory[:swap][mdev] = Mash.new - memory[:swap][mdev][:total] = $2 - memory[:swap][mdev][:used] = $3 - memory[:swap][mdev][:free] = $4 - memory[:swap][mdev][:percent_free] = $5 + popen4("swapctl -l") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # Device 1024-blocks Used Avail Capacity Priority + # swap_device 1048824 0 1048824 0% 0 + if line =~ /^([\d\w\/]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([\d\%]+)/ + mdev = $1 + memory[:swap][mdev] = Mash.new + memory[:swap][mdev][:total] = $2 + memory[:swap][mdev][:used] = $3 + memory[:swap][mdev][:free] = $4 + memory[:swap][mdev][:percent_free] = $5 + end + end end end end diff --git a/lib/ohai/plugins/netbsd/network.rb b/lib/ohai/plugins/netbsd/network.rb index 55c0c229..e3e5a751 100644 --- a/lib/ohai/plugins/netbsd/network.rb +++ b/lib/ohai/plugins/netbsd/network.rb @@ -16,105 +16,109 @@ # limitations under the License. # -provides "network", "counters/network" +Ohai.plugin(:Network) do + provides "network", "counters/network" -from("route -n get default").split("\n").each do |line| - if line =~ /(\w+): ([\w\.]+)/ - case $1 - when "gateway" - network[:default_gateway] = $2 - when "interface" - network[:default_interface] = $2 - end - end -end - -iface = Mash.new -popen4("/sbin/ifconfig -a") do |pid, stdin, stdout, stderr| - stdin.close - cint = nil - stdout.each do |line| - if line =~ /^([0-9a-zA-Z\.]+):\s+/ - cint = $1 - iface[cint] = Mash.new - if cint =~ /^(\w+)(\d+.*)/ - iface[cint][:type] = $1 - iface[cint][:number] = $2 + collect_data do + from("route -n get default").split("\n").each do |line| + if line =~ /(\w+): ([\w\.]+)/ + case $1 + when "gateway" + network[:default_gateway] = $2 + when "interface" + network[:default_interface] = $2 + end end end - # call the family lladdr to match linux for consistency - if line =~ /\s+address: (.+?)\s/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "lladdr" } - end - if line =~ /\s+inet ([\d.]+) netmask ([\da-fx]+)\s*\w*\s*([\d.]*)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - # convert the netmask to decimal for consistency - netmask = "#{$2[2,2].hex}.#{$2[4,2].hex}.#{$2[6,2].hex}.#{$2[8,2].hex}" - if $3.empty? - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask } - else - # found a broadcast address - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask, "broadcast" => $3 } - end - end - if line =~ /\s+inet6 ([a-f0-9\:]+)%?(\w*)\s+prefixlen\s+(\d+)\s*\w*\s*([\da-fx]*)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - if $4.empty? - iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $3 } - else - #found a zone_id / scope - iface[cint][:addresses][$1] = { "family" => "inet6", "zoneid" => $2, "prefixlen" => $3, "scopeid" => $4 } + + iface = Mash.new + popen4("/sbin/ifconfig -a") do |pid, stdin, stdout, stderr| + stdin.close + cint = nil + stdout.each do |line| + if line =~ /^([0-9a-zA-Z\.]+):\s+/ + cint = $1 + iface[cint] = Mash.new + if cint =~ /^(\w+)(\d+.*)/ + iface[cint][:type] = $1 + iface[cint][:number] = $2 + end + end + # call the family lladdr to match linux for consistency + if line =~ /\s+address: (.+?)\s/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "lladdr" } + end + if line =~ /\s+inet ([\d.]+) netmask ([\da-fx]+)\s*\w*\s*([\d.]*)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + # convert the netmask to decimal for consistency + netmask = "#{$2[2,2].hex}.#{$2[4,2].hex}.#{$2[6,2].hex}.#{$2[8,2].hex}" + if $3.empty? + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask } + else + # found a broadcast address + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask, "broadcast" => $3 } + end + end + if line =~ /\s+inet6 ([a-f0-9\:]+)%?(\w*)\s+prefixlen\s+(\d+)\s*\w*\s*([\da-fx]*)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + if $4.empty? + iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $3 } + else + #found a zone_id / scope + iface[cint][:addresses][$1] = { "family" => "inet6", "zoneid" => $2, "prefixlen" => $3, "scopeid" => $4 } + end + end + if line =~ /flags=\d+<(.+)>/ + flags = $1.split(',') + iface[cint][:flags] = flags if flags.length > 0 + end + if line =~ /metric: (\d+) mtu: (\d+)/ + iface[cint][:metric] = $1 + iface[cint][:mtu] = $2 + end end end - if line =~ /flags=\d+<(.+)>/ - flags = $1.split(',') - iface[cint][:flags] = flags if flags.length > 0 - end - if line =~ /metric: (\d+) mtu: (\d+)/ - iface[cint][:metric] = $1 - iface[cint][:mtu] = $2 - end - end -end -popen4("arp -an") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /\((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) on ([0-9a-zA-Z\.\:\-]+)/ - next unless iface[$3] # this should never happen - iface[$3][:arp] = Mash.new unless iface[$3][:arp] - iface[$3][:arp][$1] = $2.downcase + popen4("arp -an") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /\((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) on ([0-9a-zA-Z\.\:\-]+)/ + next unless iface[$3] # this should never happen + iface[$3][:arp] = Mash.new unless iface[$3][:arp] + iface[$3][:arp][$1] = $2.downcase + end + end end - end -end -network["interfaces"] = iface + network["interfaces"] = iface -net_counters = Mash.new -# From netstat(1), not sure of the implications: -# Show the state of all network interfaces or a single interface -# which have been auto-configured (interfaces statically configured -# into a system, but not located at boot time are not shown). -popen4("netstat -idn") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll Drop - # em0 1500 <Link> 00:11:25:2d:90:be 3719557 0 3369969 0 0 0 - # $1 $2 $3 $4 $5 $6 $7 $8 - if line =~ /^([\w\.\*]+)\s+\d+\s+<Link>\s+([\w:]*)\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ - cint = $1 - net_counters[cint] = Mash.new unless net_counters[cint] - net_counters[cint] = Mash.new unless net_counters[cint]["rx"] - net_counters[cint] = Mash.new unless net_counters[cint]["tx"] - net_counters[cint] = $3 - net_counters[cint] = $4 - net_counters[cint] = $5 - net_counters[cint] = $6 - net_counters[cint] = $7 - net_counters[cint] = $8 + net_counters = Mash.new + # From netstat(1), not sure of the implications: + # Show the state of all network interfaces or a single interface + # which have been auto-configured (interfaces statically configured + # into a system, but not located at boot time are not shown). + popen4("netstat -idn") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll Drop + # em0 1500 <Link> 00:11:25:2d:90:be 3719557 0 3369969 0 0 0 + # $1 $2 $3 $4 $5 $6 $7 $8 + if line =~ /^([\w\.\*]+)\s+\d+\s+<Link>\s+([\w:]*)\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ + cint = $1 + net_counters[cint] = Mash.new unless net_counters[cint] + net_counters[cint] = Mash.new unless net_counters[cint]["rx"] + net_counters[cint] = Mash.new unless net_counters[cint]["tx"] + net_counters[cint] = $3 + net_counters[cint] = $4 + net_counters[cint] = $5 + net_counters[cint] = $6 + net_counters[cint] = $7 + net_counters[cint] = $8 + end + end end + + counters[:network][:interfaces] = net_counters end end - -counters[:network][:interfaces] = net_counters diff --git a/lib/ohai/plugins/netbsd/platform.rb b/lib/ohai/plugins/netbsd/platform.rb index f1c96516..45891989 100644 --- a/lib/ohai/plugins/netbsd/platform.rb +++ b/lib/ohai/plugins/netbsd/platform.rb @@ -16,7 +16,11 @@ # limitations under the License. # -provides "platform", "platform_version" +Ohai.plugin(:Platform) do + provides "platform", "platform_version" -platform from("uname -s").downcase -platform_version from("uname -r") + collect_data do + platform from("uname -s").downcase + platform_version from("uname -r") + end +end diff --git a/lib/ohai/plugins/netbsd/ps.rb b/lib/ohai/plugins/netbsd/ps.rb index dce923cf..84e38e1c 100644 --- a/lib/ohai/plugins/netbsd/ps.rb +++ b/lib/ohai/plugins/netbsd/ps.rb @@ -16,9 +16,13 @@ # limitations under the License. # -provides "command/ps" +Ohai.plugin(:Ps) do + provides "command/ps" -require_plugin 'command' + depends 'command' -# ps -e requires procfs -command[:ps] = 'ps -ax' + collect_data do + # ps -e requires procfs + command[:ps] = 'ps -ax' + end +end diff --git a/lib/ohai/plugins/netbsd/uptime.rb b/lib/ohai/plugins/netbsd/uptime.rb index 75470735..693d0d67 100644 --- a/lib/ohai/plugins/netbsd/uptime.rb +++ b/lib/ohai/plugins/netbsd/uptime.rb @@ -16,16 +16,20 @@ # limitations under the License. # -provides "uptime", "uptime_seconds" +Ohai.plugin(:Uptime) do + provides "uptime", "uptime_seconds" -# kern.boottime: { sec = 1232765114, usec = 823118 } Fri Jan 23 18:45:14 2009 + # kern.boottime: { sec = 1232765114, usec = 823118 } Fri Jan 23 18:45:14 2009 -popen4("/sbin/sysctl kern.boottime") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /kern.boottime:\D+(\d+)/ - uptime_seconds Time.new.to_i - $1.to_i - uptime seconds_to_human(uptime_seconds) + collect_data do + popen4("/sbin/sysctl kern.boottime") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /kern.boottime:\D+(\d+)/ + uptime_seconds Time.new.to_i - $1.to_i + uptime seconds_to_human(uptime_seconds) + end + end end end end diff --git a/lib/ohai/plugins/netbsd/virtualization.rb b/lib/ohai/plugins/netbsd/virtualization.rb index 4e085dea..31b48006 100644 --- a/lib/ohai/plugins/netbsd/virtualization.rb +++ b/lib/ohai/plugins/netbsd/virtualization.rb @@ -16,48 +16,52 @@ # limitations under the License. # -provides "virtualization" +Ohai.plugin(:Virtualization) do + provides "virtualization" -virtualization Mash.new + collect_data do + virtualization Mash.new -# KVM Host support for FreeBSD is in development -# http://feanor.sssup.it/~fabio/freebsd/lkvm/ + # KVM Host support for FreeBSD is in development + # http://feanor.sssup.it/~fabio/freebsd/lkvm/ -# Detect KVM/QEMU from cpu, report as KVM -# hw.model: QEMU Virtual CPU version 0.9.1 -if from("sysctl -n hw.model") =~ /QEMU Virtual CPU/ - virtualization[:system] = "kvm" - virtualization[:role] = "guest" -end + # Detect KVM/QEMU from cpu, report as KVM + # hw.model: QEMU Virtual CPU version 0.9.1 + if from("sysctl -n hw.model") =~ /QEMU Virtual CPU/ + virtualization[:system] = "kvm" + virtualization[:role] = "guest" + end -# http://www.dmo.ca/blog/detecting-virtualization-on-linux -if File.exists?("/usr/pkg/sbin/dmidecode") - popen4("dmidecode") do |pid, stdin, stdout, stderr| - stdin.close - found_virt_manufacturer = nil - found_virt_product = nil - stdout.each do |line| - case line - when /Manufacturer: Microsoft/ - found_virt_manufacturer = "microsoft" - when /Product Name: Virtual Machine/ - found_virt_product = "microsoft" - when /Version: 5.0/ - if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" - virtualization[:system] = "virtualpc" - virtualization[:role] = "guest" - end - when /Version: VS2005R2/ - if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" - virtualization[:system] = "virtualserver" - virtualization[:role] = "guest" - end - when /Manufacturer: VMware/ - found_virt_manufacturer = "vmware" - when /Product Name: VMware Virtual Platform/ - if found_virt_manufacturer == "vmware" - virtualization[:system] = "vmware" - virtualization[:role] = "guest" + # http://www.dmo.ca/blog/detecting-virtualization-on-linux + if File.exists?("/usr/pkg/sbin/dmidecode") + popen4("dmidecode") do |pid, stdin, stdout, stderr| + stdin.close + found_virt_manufacturer = nil + found_virt_product = nil + stdout.each do |line| + case line + when /Manufacturer: Microsoft/ + found_virt_manufacturer = "microsoft" + when /Product Name: Virtual Machine/ + found_virt_product = "microsoft" + when /Version: 5.0/ + if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" + virtualization[:system] = "virtualpc" + virtualization[:role] = "guest" + end + when /Version: VS2005R2/ + if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" + virtualization[:system] = "virtualserver" + virtualization[:role] = "guest" + end + when /Manufacturer: VMware/ + found_virt_manufacturer = "vmware" + when /Product Name: VMware Virtual Platform/ + if found_virt_manufacturer == "vmware" + virtualization[:system] = "vmware" + virtualization[:role] = "guest" + end + end end end end diff --git a/lib/ohai/plugins/network.rb b/lib/ohai/plugins/network.rb index cf572567..93b2d037 100644 --- a/lib/ohai/plugins/network.rb +++ b/lib/ohai/plugins/network.rb @@ -18,158 +18,161 @@ require 'ipaddress' -provides "network", "counters/network" - -network Mash.new unless network -network[:interfaces] = Mash.new unless network[:interfaces] -counters Mash.new unless counters -counters[:network] = Mash.new unless counters[:network] - -require_plugin "hostname" -require_plugin "#{os}::network" - -FAMILIES = { - "inet" => "default", - "inet6" => "default_inet6" -} - -def sorted_ips(family = "inet") - raise "bad family #{family}" unless [ "inet", "inet6" ].include? family - - # going to use that later to sort by scope - scope_prio = [ "global", "site", "link", "host", "node", nil ] - - ipaddresses = [] - # ipaddresses going to hold #{family} ipaddresses and their scope - Mash[network['interfaces']].each do |iface, iface_v| - iface_v['addresses'].each do |addr, addr_v| - next if addr_v.nil? or not addr_v.has_key? "family" or addr_v['family'] != family - ipaddresses << { - :ipaddress => addr_v["prefixlen"] ? IPAddress("#{addr}/#{addr_v["prefixlen"]}") : IPAddress("#{addr}/#{addr_v["netmask"]}"), - :scope => addr_v["scope"].nil? ? nil : addr_v["scope"].downcase, - :iface => iface - } +Ohai.plugin(:Network) do + provides "network", "counters/network" + + depends "hostname" + depends_os "network" + + FAMILIES = { + "inet" => "default", + "inet6" => "default_inet6" + } + + def sorted_ips(family = "inet") + raise "bad family #{family}" unless [ "inet", "inet6" ].include? family + + # going to use that later to sort by scope + scope_prio = [ "global", "site", "link", "host", "node", nil ] + + ipaddresses = [] + # ipaddresses going to hold #{family} ipaddresses and their scope + Mash[network['interfaces']].each do |iface, iface_v| + iface_v['addresses'].each do |addr, addr_v| + next if addr_v.nil? or not addr_v.has_key? "family" or addr_v['family'] != family + ipaddresses << { + :ipaddress => addr_v["prefixlen"] ? IPAddress("#{addr}/#{addr_v["prefixlen"]}") : IPAddress("#{addr}/#{addr_v["netmask"]}"), + :scope => addr_v["scope"].nil? ? nil : addr_v["scope"].downcase, + :iface => iface + } + end end - end - # sort ip addresses by scope, by prefixlen and then by ip address - # 128 - prefixlen: longest prefixes first - ipaddresses.sort_by do |v| - [ ( scope_prio.index(v[:scope]) or 999999 ), - 128 - v[:ipaddress].prefix.to_i, - ( family == "inet" ? v[:ipaddress].to_u32 : v[:ipaddress].to_u128 ) - ] + # sort ip addresses by scope, by prefixlen and then by ip address + # 128 - prefixlen: longest prefixes first + ipaddresses.sort_by do |v| + [ ( scope_prio.index(v[:scope]) or 999999 ), + 128 - v[:ipaddress].prefix.to_i, + ( family == "inet" ? v[:ipaddress].to_u32 : v[:ipaddress].to_u128 ) + ] + end end -end -def find_ip(family = "inet") - ips=sorted_ips(family) + def find_ip(family = "inet") + ips=sorted_ips(family) - # return if there isn't any #{family} address ! - return [ nil, nil ] if ips.empty? + # return if there isn't any #{family} address ! + return [ nil, nil ] if ips.empty? - # shortcuts to access default #{family} interface and gateway - int_attr = FAMILIES[family] +"_interface" - gw_attr = FAMILIES[family] + "_gateway" + # shortcuts to access default #{family} interface and gateway + int_attr = FAMILIES[family] +"_interface" + gw_attr = FAMILIES[family] + "_gateway" - # If we have a default interface that has addresses, - # populate the short-cut attributes ipaddress, ip6address and macaddress - if network[int_attr] + # If we have a default interface that has addresses, + # populate the short-cut attributes ipaddress, ip6address and macaddress + if network[int_attr] - # working with the address(es) of the default network interface - gw_if_ips = ips.select do |v| - v[:iface] == network[int_attr] - end - if gw_if_ips.empty? - Ohai::Log.warn("[#{family}] no ip address on #{network[int_attr]}") - elsif network[gw_attr] and - network["interfaces"][network[int_attr]] and - network["interfaces"][network[int_attr]]["addresses"] - if [ "0.0.0.0", "::" ].include? network[gw_attr] - # link level default route - Ohai::Log.debug("link level default #{family} route, picking ip from #{network[gw_attr]}") - r = gw_if_ips.first - else - # checking network masks - r = gw_if_ips.select do |v| - network_contains_address(network[gw_attr], v[:ipaddress], v[:iface]) - end.first - if r.nil? + # working with the address(es) of the default network interface + gw_if_ips = ips.select do |v| + v[:iface] == network[int_attr] + end + if gw_if_ips.empty? + Ohai::Log.warn("[#{family}] no ip address on #{network[int_attr]}") + elsif network[gw_attr] and + network["interfaces"][network[int_attr]] and + network["interfaces"][network[int_attr]]["addresses"] + if [ "0.0.0.0", "::" ].include? network[gw_attr] + # link level default route + Ohai::Log.debug("link level default #{family} route, picking ip from #{network[gw_attr]}") r = gw_if_ips.first - Ohai::Log.warn("[#{family}] no ipaddress/mask on #{network[int_attr]} matching the gateway #{network[gw_attr]}, picking one anyway") else - Ohai::Log.debug("[#{family}] Using default interface #{network[int_attr]} and default gateway #{network[gw_attr]} to set the default ip to #{r[:ipaddress]}") + # checking network masks + r = gw_if_ips.select do |v| + network_contains_address(network[gw_attr], v[:ipaddress], v[:iface]) + end.first + if r.nil? + r = gw_if_ips.first + Ohai::Log.warn("[#{family}] no ipaddress/mask on #{network[int_attr]} matching the gateway #{network[gw_attr]}, picking one anyway") + else + Ohai::Log.debug("[#{family}] Using default interface #{network[int_attr]} and default gateway #{network[gw_attr]} to set the default ip to #{r[:ipaddress]}") + end end + else + # return the first ip address on network[int_attr] + r = gw_if_ips.first end else - # return the first ip address on network[int_attr] - r = gw_if_ips.first + r = ips.first + Ohai::Log.debug("[#{family}] no default interface, picking the first ipaddress") end - else - r = ips.first - Ohai::Log.debug("[#{family}] no default interface, picking the first ipaddress") - end - return [ nil, nil ] if r.nil? or r.empty? + return [ nil, nil ] if r.nil? or r.empty? - [ r[:ipaddress].to_s, r[:iface] ] -end - -def find_mac_from_iface(iface) - r = network["interfaces"][iface]["addresses"].select{|k,v| v["family"]=="lladdr"} - r.nil? or r.first.nil? ? nil : r.first.first -end + [ r[:ipaddress].to_s, r[:iface] ] + end -def network_contains_address(address_to_match, ipaddress, iface) - # address_to_match: String - # ipaddress: IPAddress - # iface: String - if peer = network["interfaces"][iface]["addresses"][ipaddress.to_s][:peer] - IPAddress(peer) == IPAddress(address_to_match) - else - ipaddress.include? IPAddress(address_to_match) + def find_mac_from_iface(iface) + r = network["interfaces"][iface]["addresses"].select{|k,v| v["family"]=="lladdr"} + r.nil? or r.first.nil? ? nil : r.first.first end -end -# ipaddress, ip6address and macaddress can be set by the #{os}::network plugin -# atm it is expected macaddress is set at the same time than ipaddress -# if ipaddress is set and macaddress is nil, that means the interface -# ipaddress is bound to has the NOARP flag - - -results = {} - -# inet family is treated before inet6 -FAMILIES.keys.sort.each do |family| - r = {} - ( r["ip"], r["iface"] ) = find_ip(family) - r["mac"] = find_mac_from_iface(r["iface"]) unless r["iface"].nil? - # don't overwrite attributes if they've already been set by the "#{os}::network" plugin - if family == "inet" and ipaddress.nil? - if r["ip"].nil? - Ohai::Log.warn("unable to detect ipaddress") - # i don't issue this warning if r["ip"] exists and r["mac"].nil? - # as it could be a valid setup with a NOARP default_interface - Ohai::Log.warn("unable to detect macaddress") + def network_contains_address(address_to_match, ipaddress, iface) + # address_to_match: String + # ipaddress: IPAddress + # iface: String + if peer = network["interfaces"][iface]["addresses"][ipaddress.to_s][:peer] + IPAddress(peer) == IPAddress(address_to_match) else - ipaddress r["ip"] - macaddress r["mac"] + ipaddress.include? IPAddress(address_to_match) end - elsif family == "inet6" and ip6address.nil? - if r["ip"].nil? - Ohai::Log.warn("unable to detect ip6address") - else - ip6address r["ip"] - if r["mac"] and macaddress.nil? and ipaddress.nil? - Ohai::Log.debug("macaddress set to #{r["mac"]} from the ipv6 setup") - macaddress r["mac"] + end + + # ipaddress, ip6address and macaddress can be set by the #{os}::network plugin + # atm it is expected macaddress is set at the same time than ipaddress + # if ipaddress is set and macaddress is nil, that means the interface + # ipaddress is bound to has the NOARP flag + + collect_data do + network Mash.new unless network + network[:interfaces] = Mash.new unless network[:interfaces] + counters Mash.new unless counters + counters[:network] = Mash.new unless counters[:network] + + results = {} + + # inet family is treated before inet6 + FAMILIES.keys.sort.each do |family| + r = {} + ( r["ip"], r["iface"] ) = find_ip(family) + r["mac"] = find_mac_from_iface(r["iface"]) unless r["iface"].nil? + # don't overwrite attributes if they've already been set by the "#{os}::network" plugin + if family == "inet" and ipaddress.nil? + if r["ip"].nil? + Ohai::Log.warn("unable to detect ipaddress") + # i don't issue this warning if r["ip"] exists and r["mac"].nil? + # as it could be a valid setup with a NOARP default_interface + Ohai::Log.warn("unable to detect macaddress") + else + ipaddress r["ip"] + macaddress r["mac"] + end + elsif family == "inet6" and ip6address.nil? + if r["ip"].nil? + Ohai::Log.warn("unable to detect ip6address") + else + ip6address r["ip"] + if r["mac"] and macaddress.nil? and ipaddress.nil? + Ohai::Log.debug("macaddress set to #{r["mac"]} from the ipv6 setup") + macaddress r["mac"] + end + end end + results[family] = r end - end - results[family] = r -end -if results["inet"]["iface"] and results["inet6"]["iface"] and - results["inet"]["iface"] != results["inet6"]["iface"] - Ohai::Log.debug("ipaddress and ip6address are set from different interfaces (#{results["inet"]["iface"]} & #{results["inet6"]["iface"]}), macaddress has been set using the ipaddress interface") + if results["inet"]["iface"] and results["inet6"]["iface"] and + results["inet"]["iface"] != results["inet6"]["iface"] + Ohai::Log.debug("ipaddress and ip6address are set from different interfaces (#{results["inet"]["iface"]} & #{results["inet6"]["iface"]}), macaddress has been set using the ipaddress interface") + end + end end diff --git a/lib/ohai/plugins/network_listeners.rb b/lib/ohai/plugins/network_listeners.rb index 4d4c332f..1f5e521c 100644 --- a/lib/ohai/plugins/network_listeners.rb +++ b/lib/ohai/plugins/network_listeners.rb @@ -18,30 +18,34 @@ require 'sigar' -provides "network/listeners" +Ohai.plugin(:Listeners) do + provides "network/listeners" -require_plugin "network" + depends "network", "counters/network" -flags = Sigar::NETCONN_TCP|Sigar::NETCONN_SERVER + flags = Sigar::NETCONN_TCP|Sigar::NETCONN_SERVER -listeners = Mash.new + collect_data do + listeners = Mash.new -sigar = Sigar.new -sigar.net_connection_list(flags).each do |conn| - port = conn.local_port - addr = conn.local_address.to_s - if addr == "0.0.0.0" || addr == "::" - addr = "*" - end - listeners[port] = Mash.new - listeners[port][:address] = addr - begin - pid = sigar.proc_port(conn.type, port) - listeners[port][:pid] = pid - listeners[port][:name] = sigar.proc_state(pid).name - rescue + sigar = Sigar.new + sigar.net_connection_list(flags).each do |conn| + port = conn.local_port + addr = conn.local_address.to_s + if addr == "0.0.0.0" || addr == "::" + addr = "*" + end + listeners[port] = Mash.new + listeners[port][:address] = addr + begin + pid = sigar.proc_port(conn.type, port) + listeners[port][:pid] = pid + listeners[port][:name] = sigar.proc_state(pid).name + rescue + end + end + + network[:listeners] = Mash.new + network[:listeners][:tcp] = listeners end end - -network[:listeners] = Mash.new -network[:listeners][:tcp] = listeners diff --git a/lib/ohai/plugins/nodejs.rb b/lib/ohai/plugins/nodejs.rb index 05acac09..8cb6adb8 100644 --- a/lib/ohai/plugins/nodejs.rb +++ b/lib/ohai/plugins/nodejs.rb @@ -16,19 +16,23 @@ # limitations under the License. # -provides "languages/nodejs" +Ohai.plugin(:Nodejs) do + provides "languages/nodejs" -require_plugin "languages" + depends "languages" -output = nil + collect_data do + output = nil -nodejs = Mash.new + nodejs = Mash.new -status, stdout, stderr = run_command(:no_status_check => true, :command => "node -v") -if status == 0 - output = stdout.split - if output.length >= 1 - nodejs[:version] = output[0][1..output[0].length] + status, stdout, stderr = run_command(:no_status_check => true, :command => "node -v") + if status == 0 + output = stdout.split + if output.length >= 1 + nodejs[:version] = output[0][1..output[0].length] + end + languages[:nodejs] = nodejs if nodejs[:version] + end end - languages[:nodejs] = nodejs if nodejs[:version] end diff --git a/lib/ohai/plugins/ohai.rb b/lib/ohai/plugins/ohai.rb index 666bdefe..fceffde5 100644 --- a/lib/ohai/plugins/ohai.rb +++ b/lib/ohai/plugins/ohai.rb @@ -17,9 +17,14 @@ # require "ohai" -provides "ohai" -self[:chef_packages] = Mash.new unless self[:chef_packages] -self[:chef_packages][:ohai] = Mash.new -self[:chef_packages][:ohai][:version] = Ohai::VERSION -self[:chef_packages][:ohai][:ohai_root] = Ohai::OHAI_ROOT +Ohai.plugin(:OHAI) do + provides "ohai" + + collect_data do + self[:chef_packages] = Mash.new unless self[:chef_packages] + self[:chef_packages][:ohai] = Mash.new + self[:chef_packages][:ohai][:version] = Ohai::VERSION + self[:chef_packages][:ohai][:ohai_root] = Ohai::OHAI_ROOT + end +end diff --git a/lib/ohai/plugins/ohai_time.rb b/lib/ohai/plugins/ohai_time.rb index 643772b9..9867ec7f 100644 --- a/lib/ohai/plugins/ohai_time.rb +++ b/lib/ohai/plugins/ohai_time.rb @@ -16,6 +16,10 @@ # limitations under the License. # -provides "ohai_time" +Ohai.plugin(:OhaiTime) do + provides "ohai_time" -ohai_time Time.now.to_f
\ No newline at end of file + collect_data do + ohai_time Time.now.to_f + end +end diff --git a/lib/ohai/plugins/openbsd/cpu.rb b/lib/ohai/plugins/openbsd/cpu.rb index d350ada0..392f21af 100644 --- a/lib/ohai/plugins/openbsd/cpu.rb +++ b/lib/ohai/plugins/openbsd/cpu.rb @@ -16,23 +16,27 @@ # limitations under the License. # -provides 'cpu' +Ohai.plugin(:Cpu) do + provides 'cpu' -cpuinfo = Mash.new + collect_data do + cpuinfo = Mash.new -# OpenBSD provides most cpu information via sysctl, the only thing we need to -# to scrape from dmesg.boot is the cpu feature list. -# cpu0: FPU,V86,DE,PSE,TSC,MSR,MCE,CX8,SEP,MTRR,PGE,MCA,CMOV,PAT,CFLUSH,DS,ACPI,MMX,FXSR,SSE,SSE2,SS,TM,SBF,EST,TM2 + # OpenBSD provides most cpu information via sysctl, the only thing we need to + # to scrape from dmesg.boot is the cpu feature list. + # cpu0: FPU,V86,DE,PSE,TSC,MSR,MCE,CX8,SEP,MTRR,PGE,MCA,CMOV,PAT,CFLUSH,DS,ACPI,MMX,FXSR,SSE,SSE2,SS,TM,SBF,EST,TM2 -File.open("/var/run/dmesg.boot").each do |line| - case line - when /cpu\d+:\s+([A-Z]+$|[A-Z]+,.*$)/ - cpuinfo["flags"] = $1.downcase.split(',') - end -end + File.open("/var/run/dmesg.boot").each do |line| + case line + when /cpu\d+:\s+([A-Z]+$|[A-Z]+,.*$)/ + cpuinfo["flags"] = $1.downcase.split(',') + end + end -cpuinfo[:model_name] = from("sysctl -n hw.model") -cpuinfo[:total] = from("sysctl -n hw.ncpu") -cpuinfo[:mhz] = from("sysctl -n hw.cpuspeed") + cpuinfo[:model_name] = from("sysctl -n hw.model") + cpuinfo[:total] = from("sysctl -n hw.ncpu") + cpuinfo[:mhz] = from("sysctl -n hw.cpuspeed") -cpu cpuinfo + cpu cpuinfo + end +end diff --git a/lib/ohai/plugins/openbsd/filesystem.rb b/lib/ohai/plugins/openbsd/filesystem.rb index 90a76498..c50be3b9 100644 --- a/lib/ohai/plugins/openbsd/filesystem.rb +++ b/lib/ohai/plugins/openbsd/filesystem.rb @@ -16,42 +16,46 @@ # limitations under the License. # -provides "filesystem" +Ohai.plugin(:Filesystem) do + provides "filesystem" -fs = Mash.new + collect_data do + fs = Mash.new -# Grab filesystem data from df -popen4("df") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^Filesystem/ - next - when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ - filesystem = $1 - fs[filesystem] = Mash.new - fs[filesystem]['kb_size'] = $2 - fs[filesystem]['kb_used'] = $3 - fs[filesystem]['kb_available'] = $4 - fs[filesystem]['percent_used'] = $5 - fs[filesystem]['mount'] = $6 + # Grab filesystem data from df + popen4("df") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^Filesystem/ + next + when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ + filesystem = $1 + fs[filesystem] = Mash.new + fs[filesystem]['kb_size'] = $2 + fs[filesystem]['kb_used'] = $3 + fs[filesystem]['kb_available'] = $4 + fs[filesystem]['percent_used'] = $5 + fs[filesystem]['mount'] = $6 + end + end end - end -end -# Grab mount information from mount -popen4("mount -l") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/ - filesystem = $1 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem]['mount'] = $2 - fs[filesystem]['fs_type'] = $3 - fs[filesystem]['mount-options'] = $4.split(/,\s*/) + # Grab mount information from mount + popen4("mount -l") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/ + filesystem = $1 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem]['mount'] = $2 + fs[filesystem]['fs_type'] = $3 + fs[filesystem]['mount-options'] = $4.split(/,\s*/) + end + end end + + # Set the filesystem data + filesystem fs end end - -# Set the filesystem data -filesystem fs diff --git a/lib/ohai/plugins/openbsd/hostname.rb b/lib/ohai/plugins/openbsd/hostname.rb index 337203dd..a25ef821 100644 --- a/lib/ohai/plugins/openbsd/hostname.rb +++ b/lib/ohai/plugins/openbsd/hostname.rb @@ -16,7 +16,11 @@ # limitations under the License. # -provides "hostname", "fqdn" +Ohai.plugin(:Hostname) do + provides "hostname", "fqdn" -hostname from("hostname -s") -fqdn from("hostname") + collect_data do + hostname from("hostname -s") + fqdn from("hostname") + end +end diff --git a/lib/ohai/plugins/openbsd/kernel.rb b/lib/ohai/plugins/openbsd/kernel.rb index 38d14e81..02f7da99 100644 --- a/lib/ohai/plugins/openbsd/kernel.rb +++ b/lib/ohai/plugins/openbsd/kernel.rb @@ -16,20 +16,24 @@ # limitations under the License. # -provides "kernel" +Ohai.plugin(:Kernel) do + provides "kernel" -kernel[:os] = kernel[:name] -kernel[:securelevel] = from_with_regex("sysctl kern.securelevel", /kern.securelevel=(.+)$/) + collect_data do + kernel[:os] = kernel[:name] + kernel[:securelevel] = from_with_regex("sysctl kern.securelevel", /kern.securelevel=(.+)$/) -mod = Mash.new -popen4("/usr/bin/modstat") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # 1 7 0xc0400000 97f830 kernel - if line =~ /(\d+)\s+(\d+)\s+([0-9a-fx]+)\s+([0-9a-fx]+)\s+([a-zA-Z0-9\_]+)/ - kld[$5] = { :size => $4, :refcount => $2 } + mod = Mash.new + popen4("/usr/bin/modstat") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # 1 7 0xc0400000 97f830 kernel + if line =~ /(\d+)\s+(\d+)\s+([0-9a-fx]+)\s+([0-9a-fx]+)\s+([a-zA-Z0-9\_]+)/ + kld[$5] = { :size => $4, :refcount => $2 } + end + end end + + kernel[:modules] = mod unless mod.empty? end end - -kernel[:modules] = mod unless mod.empty? diff --git a/lib/ohai/plugins/openbsd/memory.rb b/lib/ohai/plugins/openbsd/memory.rb index 54f554bf..9d8ad197 100644 --- a/lib/ohai/plugins/openbsd/memory.rb +++ b/lib/ohai/plugins/openbsd/memory.rb @@ -16,83 +16,87 @@ # limitations under the License. # -provides "memory" +Ohai.plugin(:Memory) do + provides "memory" -memory Mash.new -memory[:swap] = Mash.new + collect_data do + memory Mash.new + memory[:swap] = Mash.new -# $ vmstat -s -# 4096 bytes per page -# 514011 pages managed -# 224519 pages free -# 209339 pages active -# 4647 pages inactive -# 0 pages being paged out -# 5 pages wired -# 0 pages zeroed -# 4 pages reserved for pagedaemon -# 6 pages reserved for kernel -# 262205 swap pages -# 0 swap pages in use -# 0 total anon's in system -# 0 free anon's -# 1192991609 page faults -# 1369579301 traps -# 814549706 interrupts -# 771702498 cpu context switches -# 208810590 fpu context switches -# 492361360 software interrupts -# 1161998825 syscalls -# 0 pagein operations -# 0 swap ins -# 0 swap outs -# 768352 forks -# 16 forks where vmspace is shared -# 1763 kernel map entries -# 0 number of times the pagedaemon woke up -# 0 revolutions of the clock hand -# 0 pages freed by pagedaemon -# 0 pages scanned by pagedaemon -# 0 pages reactivated by pagedaemon -# 0 busy pages found by pagedaemon -# 1096393776 total name lookups -# cache hits (37% pos + 2% neg) system 1% per-directory -# deletions 0%, falsehits 6%, toolong 26% -# 0 select collisions + # $ vmstat -s + # 4096 bytes per page + # 514011 pages managed + # 224519 pages free + # 209339 pages active + # 4647 pages inactive + # 0 pages being paged out + # 5 pages wired + # 0 pages zeroed + # 4 pages reserved for pagedaemon + # 6 pages reserved for kernel + # 262205 swap pages + # 0 swap pages in use + # 0 total anon's in system + # 0 free anon's + # 1192991609 page faults + # 1369579301 traps + # 814549706 interrupts + # 771702498 cpu context switches + # 208810590 fpu context switches + # 492361360 software interrupts + # 1161998825 syscalls + # 0 pagein operations + # 0 swap ins + # 0 swap outs + # 768352 forks + # 16 forks where vmspace is shared + # 1763 kernel map entries + # 0 number of times the pagedaemon woke up + # 0 revolutions of the clock hand + # 0 pages freed by pagedaemon + # 0 pages scanned by pagedaemon + # 0 pages reactivated by pagedaemon + # 0 busy pages found by pagedaemon + # 1096393776 total name lookups + # cache hits (37% pos + 2% neg) system 1% per-directory + # deletions 0%, falsehits 6%, toolong 26% + # 0 select collisions -popen4("vmstat -s") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /(\d+) bytes per page/ - memory[:page_size] = $1 - when /(\d+) pages managed/ - memory[:page_count] = $1 - memory[:total] = memory[:page_size].to_i * memory[:page_count].to_i - when /(\d+) pages free/ - memory[:free] = memory[:page_size].to_i * $1.to_i - when /(\d+) pages active/ - memory[:active] = memory[:page_size].to_i * $1.to_i - when /(\d+) pages inactive/ - memory[:inactive] = memory[:page_size].to_i * $1.to_i - when /(\d+) pages wired/ - memory[:wired] = memory[:page_size].to_i * $1.to_i + popen4("vmstat -s") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /(\d+) bytes per page/ + memory[:page_size] = $1 + when /(\d+) pages managed/ + memory[:page_count] = $1 + memory[:total] = memory[:page_size].to_i * memory[:page_count].to_i + when /(\d+) pages free/ + memory[:free] = memory[:page_size].to_i * $1.to_i + when /(\d+) pages active/ + memory[:active] = memory[:page_size].to_i * $1.to_i + when /(\d+) pages inactive/ + memory[:inactive] = memory[:page_size].to_i * $1.to_i + when /(\d+) pages wired/ + memory[:wired] = memory[:page_size].to_i * $1.to_i + end end - end -end + end -popen4("swapctl -l") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # Device 1024-blocks Used Avail Capacity Priority - # swap_device 1048824 0 1048824 0% 0 - if line =~ /^([\d\w\/]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([\d\%]+)/ - mdev = $1 - memory[:swap][mdev] = Mash.new - memory[:swap][mdev][:total] = $2 - memory[:swap][mdev][:used] = $3 - memory[:swap][mdev][:free] = $4 - memory[:swap][mdev][:percent_free] = $5 + popen4("swapctl -l") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # Device 1024-blocks Used Avail Capacity Priority + # swap_device 1048824 0 1048824 0% 0 + if line =~ /^([\d\w\/]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([\d\%]+)/ + mdev = $1 + memory[:swap][mdev] = Mash.new + memory[:swap][mdev][:total] = $2 + memory[:swap][mdev][:used] = $3 + memory[:swap][mdev][:free] = $4 + memory[:swap][mdev][:percent_free] = $5 + end + end end end end diff --git a/lib/ohai/plugins/openbsd/network.rb b/lib/ohai/plugins/openbsd/network.rb index 4a3c18ef..08b53919 100644 --- a/lib/ohai/plugins/openbsd/network.rb +++ b/lib/ohai/plugins/openbsd/network.rb @@ -16,105 +16,109 @@ # limitations under the License. # -provides "network", "counters/network" +Ohai.plugin(:Network) do + provides "network", "counters/network" -from("route -n get default").split("\n").each do |line| - if line =~ /(\w+): ([\w\.]+)/ - case $1 - when "gateway" - network[:default_gateway] = $2 - when "interface" - network[:default_interface] = $2 - end - end -end - -iface = Mash.new -popen4("/sbin/ifconfig -a") do |pid, stdin, stdout, stderr| - stdin.close - cint = nil - stdout.each do |line| - if line =~ /^([0-9a-zA-Z\.]+):\s+/ - cint = $1 - iface[cint] = Mash.new - if cint =~ /^(\w+)(\d+.*)/ - iface[cint][:type] = $1 - iface[cint][:number] = $2 + collect_data do + from("route -n get default").split("\n").each do |line| + if line =~ /(\w+): ([\w\.]+)/ + case $1 + when "gateway" + network[:default_gateway] = $2 + when "interface" + network[:default_interface] = $2 + end end end - # call the family lladdr to match linux for consistency - if line =~ /\s+lladdr (.+?)\s/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "lladdr" } - end - if line =~ /\s+inet ([\d.]+) netmask ([\da-fx]+)\s*\w*\s*([\d.]*)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - # convert the netmask to decimal for consistency - netmask = "#{$2[2,2].hex}.#{$2[4,2].hex}.#{$2[6,2].hex}.#{$2[8,2].hex}" - if $3.empty? - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask } - else - # found a broadcast address - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask, "broadcast" => $3 } - end - end - if line =~ /\s+inet6 ([a-f0-9\:]+)%?(\w*)\s+prefixlen\s+(\d+)\s*\w*\s*([\da-fx]*)/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - if $4.empty? - iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $3 } - else - #found a zone_id / scope - iface[cint][:addresses][$1] = { "family" => "inet6", "zoneid" => $2, "prefixlen" => $3, "scopeid" => $4 } + + iface = Mash.new + popen4("/sbin/ifconfig -a") do |pid, stdin, stdout, stderr| + stdin.close + cint = nil + stdout.each do |line| + if line =~ /^([0-9a-zA-Z\.]+):\s+/ + cint = $1 + iface[cint] = Mash.new + if cint =~ /^(\w+)(\d+.*)/ + iface[cint][:type] = $1 + iface[cint][:number] = $2 + end + end + # call the family lladdr to match linux for consistency + if line =~ /\s+lladdr (.+?)\s/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "lladdr" } + end + if line =~ /\s+inet ([\d.]+) netmask ([\da-fx]+)\s*\w*\s*([\d.]*)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + # convert the netmask to decimal for consistency + netmask = "#{$2[2,2].hex}.#{$2[4,2].hex}.#{$2[6,2].hex}.#{$2[8,2].hex}" + if $3.empty? + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask } + else + # found a broadcast address + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => netmask, "broadcast" => $3 } + end + end + if line =~ /\s+inet6 ([a-f0-9\:]+)%?(\w*)\s+prefixlen\s+(\d+)\s*\w*\s*([\da-fx]*)/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + if $4.empty? + iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $3 } + else + #found a zone_id / scope + iface[cint][:addresses][$1] = { "family" => "inet6", "zoneid" => $2, "prefixlen" => $3, "scopeid" => $4 } + end + end + if line =~ /flags=\d+<(.+)>/ + flags = $1.split(',') + iface[cint][:flags] = flags if flags.length > 0 + end + if line =~ /metric: (\d+) mtu: (\d+)/ + iface[cint][:metric] = $1 + iface[cint][:mtu] = $2 + end end end - if line =~ /flags=\d+<(.+)>/ - flags = $1.split(',') - iface[cint][:flags] = flags if flags.length > 0 - end - if line =~ /metric: (\d+) mtu: (\d+)/ - iface[cint][:metric] = $1 - iface[cint][:mtu] = $2 - end - end -end -popen4("arp -an") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /\((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) on ([0-9a-zA-Z\.\:\-]+)/ - next unless iface[$3] # this should never happen - iface[$3][:arp] = Mash.new unless iface[$3][:arp] - iface[$3][:arp][$1] = $2.downcase + popen4("arp -an") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /\((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) on ([0-9a-zA-Z\.\:\-]+)/ + next unless iface[$3] # this should never happen + iface[$3][:arp] = Mash.new unless iface[$3][:arp] + iface[$3][:arp][$1] = $2.downcase + end + end end - end -end -network["interfaces"] = iface + network["interfaces"] = iface -net_counters = Mash.new -# From netstat(1), not sure of the implications: -# Show the state of all network interfaces or a single interface -# which have been auto-configured (interfaces statically configured -# into a system, but not located at boot time are not shown). -popen4("netstat -idn") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - # Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll Drop - # em0 1500 <Link> 00:11:25:2d:90:be 3719557 0 3369969 0 0 0 - # $1 $2 $3 $4 $5 $6 $7 $8 - if line =~ /^([\w\.\*]+)\s+\d+\s+<Link>\s+([\w:]*)\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ - cint = $1 - net_counters[cint] = Mash.new unless net_counters[cint] - net_counters[cint] = Mash.new unless net_counters[cint]["rx"] - net_counters[cint] = Mash.new unless net_counters[cint]["tx"] - net_counters[cint] = $3 - net_counters[cint] = $4 - net_counters[cint] = $5 - net_counters[cint] = $6 - net_counters[cint] = $7 - net_counters[cint] = $8 + net_counters = Mash.new + # From netstat(1), not sure of the implications: + # Show the state of all network interfaces or a single interface + # which have been auto-configured (interfaces statically configured + # into a system, but not located at boot time are not shown). + popen4("netstat -idn") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + # Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll Drop + # em0 1500 <Link> 00:11:25:2d:90:be 3719557 0 3369969 0 0 0 + # $1 $2 $3 $4 $5 $6 $7 $8 + if line =~ /^([\w\.\*]+)\s+\d+\s+<Link>\s+([\w:]*)\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ + cint = $1 + net_counters[cint] = Mash.new unless net_counters[cint] + net_counters[cint] = Mash.new unless net_counters[cint]["rx"] + net_counters[cint] = Mash.new unless net_counters[cint]["tx"] + net_counters[cint] = $3 + net_counters[cint] = $4 + net_counters[cint] = $5 + net_counters[cint] = $6 + net_counters[cint] = $7 + net_counters[cint] = $8 + end + end end + + counters[:network][:interfaces] = net_counters end end - -counters[:network][:interfaces] = net_counters diff --git a/lib/ohai/plugins/openbsd/platform.rb b/lib/ohai/plugins/openbsd/platform.rb index 78697e72..45891989 100644 --- a/lib/ohai/plugins/openbsd/platform.rb +++ b/lib/ohai/plugins/openbsd/platform.rb @@ -16,8 +16,11 @@ # limitations under the License. # -provides "platform", "platform_version" - -platform from("uname -s").downcase -platform_version from("uname -r") +Ohai.plugin(:Platform) do + provides "platform", "platform_version" + collect_data do + platform from("uname -s").downcase + platform_version from("uname -r") + end +end diff --git a/lib/ohai/plugins/openbsd/ps.rb b/lib/ohai/plugins/openbsd/ps.rb index f4823327..876ded11 100644 --- a/lib/ohai/plugins/openbsd/ps.rb +++ b/lib/ohai/plugins/openbsd/ps.rb @@ -16,9 +16,13 @@ # limitations under the License. # -provides "command/ps" +Ohai.plugin(:Ps) do + provides "command/ps" -require_plugin 'command' + depends 'command' -# ps -e requires procfs -command[:ps] = 'ps -ax' + collect_data do + # ps -e requires procfs + command[:ps] = 'ps -ax' + end +end diff --git a/lib/ohai/plugins/openbsd/uptime.rb b/lib/ohai/plugins/openbsd/uptime.rb index 6028d1e7..82f16383 100644 --- a/lib/ohai/plugins/openbsd/uptime.rb +++ b/lib/ohai/plugins/openbsd/uptime.rb @@ -16,17 +16,20 @@ # limitations under the License. # -provides "uptime", "uptime_seconds" +Ohai.plugin(:Uptime) do + provides "uptime", "uptime_seconds" -# kern.boottime=Tue Nov 1 14:45:52 2011 + # kern.boottime=Tue Nov 1 14:45:52 2011 -popen4("/sbin/sysctl kern.boottime") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /kern.boottime=(.+)/ - uptime_seconds Time.new.to_i - Time.parse($1).to_i - uptime seconds_to_human(uptime_seconds) + collect_data do + popen4("/sbin/sysctl kern.boottime") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /kern.boottime=(.+)/ + uptime_seconds Time.new.to_i - Time.parse($1).to_i + uptime seconds_to_human(uptime_seconds) + end + end end end end - diff --git a/lib/ohai/plugins/openbsd/virtualization.rb b/lib/ohai/plugins/openbsd/virtualization.rb index f351e4af..bc3072db 100644 --- a/lib/ohai/plugins/openbsd/virtualization.rb +++ b/lib/ohai/plugins/openbsd/virtualization.rb @@ -16,48 +16,52 @@ # limitations under the License. # -provides "virtualization" +Ohai.plugin(:Virtualization) do + provides "virtualization" -virtualization Mash.new + collect_data do + virtualization Mash.new -# KVM Host support for FreeBSD is in development -# http://feanor.sssup.it/~fabio/freebsd/lkvm/ + # KVM Host support for FreeBSD is in development + # http://feanor.sssup.it/~fabio/freebsd/lkvm/ -# Detect KVM/QEMU from cpu, report as KVM -# hw.model: QEMU Virtual CPU version 0.9.1 -if from("sysctl -n hw.model") =~ /QEMU Virtual CPU/ - virtualization[:system] = "kvm" - virtualization[:role] = "guest" -end + # Detect KVM/QEMU from cpu, report as KVM + # hw.model: QEMU Virtual CPU version 0.9.1 + if from("sysctl -n hw.model") =~ /QEMU Virtual CPU/ + virtualization[:system] = "kvm" + virtualization[:role] = "guest" + end -# http://www.dmo.ca/blog/detecting-virtualization-on-linux -if File.exists?("/usr/local/sbin/dmidecode") - popen4("dmidecode") do |pid, stdin, stdout, stderr| - stdin.close - found_virt_manufacturer = nil - found_virt_product = nil - stdout.each do |line| - case line - when /Manufacturer: Microsoft/ - found_virt_manufacturer = "microsoft" - when /Product Name: Virtual Machine/ - found_virt_product = "microsoft" - when /Version: 5.0/ - if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" - virtualization[:system] = "virtualpc" - virtualization[:role] = "guest" - end - when /Version: VS2005R2/ - if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" - virtualization[:system] = "virtualserver" - virtualization[:role] = "guest" - end - when /Manufacturer: VMware/ - found_virt_manufacturer = "vmware" - when /Product Name: VMware Virtual Platform/ - if found_virt_manufacturer == "vmware" - virtualization[:system] = "vmware" - virtualization[:role] = "guest" + # http://www.dmo.ca/blog/detecting-virtualization-on-linux + if File.exists?("/usr/local/sbin/dmidecode") + popen4("dmidecode") do |pid, stdin, stdout, stderr| + stdin.close + found_virt_manufacturer = nil + found_virt_product = nil + stdout.each do |line| + case line + when /Manufacturer: Microsoft/ + found_virt_manufacturer = "microsoft" + when /Product Name: Virtual Machine/ + found_virt_product = "microsoft" + when /Version: 5.0/ + if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" + virtualization[:system] = "virtualpc" + virtualization[:role] = "guest" + end + when /Version: VS2005R2/ + if found_virt_manufacturer == "microsoft" && found_virt_product == "microsoft" + virtualization[:system] = "virtualserver" + virtualization[:role] = "guest" + end + when /Manufacturer: VMware/ + found_virt_manufacturer = "vmware" + when /Product Name: VMware Virtual Platform/ + if found_virt_manufacturer == "vmware" + virtualization[:system] = "vmware" + virtualization[:role] = "guest" + end + end end end end diff --git a/lib/ohai/plugins/openstack.rb b/lib/ohai/plugins/openstack.rb index 4c9711a7..afe14a1a 100644 --- a/lib/ohai/plugins/openstack.rb +++ b/lib/ohai/plugins/openstack.rb @@ -15,32 +15,35 @@ # See the License for the specific language governing permissions and # limitations under the License. -provides "openstack" - require 'ohai/mixin/ec2_metadata' - extend Ohai::Mixin::Ec2Metadata -# does it matter that it's not hitting latest? -#Ec2Metadata::EC2_METADATA_URL = "/latest/meta-data" +Ohai.plugin(:Openstack) do + provides "openstack" + + # does it matter that it's not hitting latest? + #Ec2Metadata::EC2_METADATA_URL = "/latest/meta-data" -# Adds openstack Mash -if hint?('openstack') || hint?('hp') - Ohai::Log.debug("ohai openstack") - openstack Mash.new - #for now, use the metadata service - if can_metadata_connect?(EC2_METADATA_ADDR,80) - Ohai::Log.debug("connecting to the OpenStack metadata service") - self.fetch_metadata.each {|k, v| openstack[k] = v } - case - when hint?('hp') - openstack['provider'] = 'hp' + collect_data do + # Adds openstack Mash + if hint?('openstack') || hint?('hp') + Ohai::Log.debug("ohai openstack") + openstack Mash.new + #for now, use the metadata service + if can_metadata_connect?(EC2_METADATA_ADDR,80) + Ohai::Log.debug("connecting to the OpenStack metadata service") + self.fetch_metadata.each {|k, v| openstack[k] = v } + case + when hint?('hp') + openstack['provider'] = 'hp' + else + openstack['provider'] = 'openstack' + end + else + Ohai::Log.debug("unable to connect to the OpenStack metadata service") + end else - openstack['provider'] = 'openstack' + Ohai::Log.debug("NOT ohai openstack") end - else - Ohai::Log.debug("unable to connect to the OpenStack metadata service") end -else - Ohai::Log.debug("NOT ohai openstack") end diff --git a/lib/ohai/plugins/os.rb b/lib/ohai/plugins/os.rb index 43846dcd..07a50057 100644 --- a/lib/ohai/plugins/os.rb +++ b/lib/ohai/plugins/os.rb @@ -16,42 +16,15 @@ # limitations under the License. # -Ohai.plugin(:OS) do - provides "os", "os_version" +require 'ohai/os' - require 'rbconfig' +Ohai.plugin(:Os) do + provides "os", "os_version" depends 'kernel' collect_data do - case ::RbConfig::CONFIG['host_os'] - when /aix(.+)$/ - os "aix" - when /darwin(.+)$/ - os "darwin" - when /hpux(.+)$/ - os "hpux" - when /linux/ - os "linux" - when /freebsd(.+)$/ - os "freebsd" - when /openbsd(.+)$/ - os "openbsd" - when /netbsd(.*)$/ - os "netbsd" - when /solaris2/ - os "solaris2" - when /mswin|mingw32|windows/ - # After long discussion in IRC the "powers that be" have come to a concensus - # that there is no other Windows platforms exist that were not based on the - # Windows_NT kernel, so we herby decree that "windows" will refer to all - # platforms built upon the Windows_NT kernel and have access to win32 or win64 - # subsystems. - os "windows" - else - os ::RbConfig::CONFIG['host_os'] - end - + os collect_os os_version kernel[:release] end end diff --git a/lib/ohai/plugins/passwd.rb b/lib/ohai/plugins/passwd.rb index ed63d268..397b15c6 100644 --- a/lib/ohai/plugins/passwd.rb +++ b/lib/ohai/plugins/passwd.rb @@ -1,32 +1,37 @@ -provides 'etc', 'current_user' require 'etc' -def fix_encoding(str) - str.force_encoding(Encoding.default_external) if str.respond_to?(:force_encoding) - str -end +Ohai.plugin(:Passwd) do + provides 'etc', 'current_user' -unless etc - etc Mash.new + def fix_encoding(str) + str.force_encoding(Encoding.default_external) if str.respond_to?(:force_encoding) + str + end - etc[:passwd] = Mash.new - etc[:group] = Mash.new + collect_data do + unless etc + etc Mash.new - Etc.passwd do |entry| - user_passwd_entry = Mash.new(:dir => entry.dir, :gid => entry.gid, :uid => entry.uid, :shell => entry.shell, :gecos => entry.gecos) - user_passwd_entry.each_value {|v| fix_encoding(v)} - etc[:passwd][fix_encoding(entry.name)] = user_passwd_entry - end + etc[:passwd] = Mash.new + etc[:group] = Mash.new - Etc.group do |entry| - group_entry = Mash.new(:gid => entry.gid, - :members => entry.mem.map {|u| fix_encoding(u)}) + Etc.passwd do |entry| + user_passwd_entry = Mash.new(:dir => entry.dir, :gid => entry.gid, :uid => entry.uid, :shell => entry.shell, :gecos => entry.gecos) + user_passwd_entry.each_value {|v| fix_encoding(v)} + etc[:passwd][fix_encoding(entry.name)] = user_passwd_entry + end - etc[:group][fix_encoding(entry.name)] = group_entry - end -end + Etc.group do |entry| + group_entry = Mash.new(:gid => entry.gid, + :members => entry.mem.map {|u| fix_encoding(u)}) + + etc[:group][fix_encoding(entry.name)] = group_entry + end + end -unless current_user - current_user fix_encoding(Etc.getlogin) + unless current_user + current_user fix_encoding(Etc.getlogin) + end + end end diff --git a/lib/ohai/plugins/perl.rb b/lib/ohai/plugins/perl.rb index 00d1e0f0..97d2fbed 100644 --- a/lib/ohai/plugins/perl.rb +++ b/lib/ohai/plugins/perl.rb @@ -16,24 +16,29 @@ # limitations under the License. # -provides "languages/perl" +Ohai.plugin(:Perl) do + provides "languages/perl" -require_plugin "languages" -output = nil + depends "languages" -perl = Mash.new -status, stdout, stderr = run_command(:no_status_check => true, :command => "perl -V:version -V:archname") -if status == 0 - stdout.each_line do |line| - case line - when /^version=\'(.+)\';$/ - perl[:version] = $1 - when /^archname=\'(.+)\';$/ - perl[:archname] = $1 + collect_data do + output = nil + + perl = Mash.new + status, stdout, stderr = run_command(:no_status_check => true, :command => "perl -V:version -V:archname") + if status == 0 + stdout.each_line do |line| + case line + when /^version=\'(.+)\';$/ + perl[:version] = $1 + when /^archname=\'(.+)\';$/ + perl[:archname] = $1 + end + end end - end -end -if status == 0 - languages[:perl] = perl + if status == 0 + languages[:perl] = perl + end + end end diff --git a/lib/ohai/plugins/php.rb b/lib/ohai/plugins/php.rb index 23dbba14..5f8ea92b 100644 --- a/lib/ohai/plugins/php.rb +++ b/lib/ohai/plugins/php.rb @@ -16,21 +16,24 @@ # limitations under the License. # -provides "languages/php" +Ohai.plugin(:Php) do + provides "languages/php" -require_plugin "languages" + depends "languages" -output = nil + collect_data do + output = nil -php = Mash.new + php = Mash.new -status, stdout, stderr = run_command(:no_status_check => true, :command => "php -v") -if status == 0 - output = stdout.split - if output.length >= 6 - php[:version] = output[1] - php[:builddate] = "%s %s %s" % [output[4],output[5],output[6]] + status, stdout, stderr = run_command(:no_status_check => true, :command => "php -v") + if status == 0 + output = stdout.split + if output.length >= 6 + php[:version] = output[1] + php[:builddate] = "%s %s %s" % [output[4],output[5],output[6]] + end + languages[:php] = php if php[:version] + end end - languages[:php] = php if php[:version] end - diff --git a/lib/ohai/plugins/platform.rb b/lib/ohai/plugins/platform.rb index 3c4ab61b..71a37fd9 100644 --- a/lib/ohai/plugins/platform.rb +++ b/lib/ohai/plugins/platform.rb @@ -16,13 +16,16 @@ # limitations under the License. # -provides "platform", "platform_version", "platform_family" +Ohai.plugin(:Platform) do + provides "platform", "platform_version", "platform_family" -require_plugin "#{os}::platform" + depends_os "platform" -platform os unless attribute?("platform") + collect_data do + platform os unless attribute?("platform") -platform_version os_version unless attribute?("platform_version") - -platform_family platform unless attribute?("platform_family") + platform_version os_version unless attribute?("platform_version") + platform_family platform unless attribute?("platform_family") + end +end diff --git a/lib/ohai/plugins/python.rb b/lib/ohai/plugins/python.rb index 1b15f941..ad504bdc 100644 --- a/lib/ohai/plugins/python.rb +++ b/lib/ohai/plugins/python.rb @@ -16,22 +16,26 @@ # limitations under the License. # -provides "languages/python" +Ohai.plugin(:Python) do + provides "languages/python" -require_plugin "languages" + depends "languages" -output = nil + collect_data do + output = nil -python = Mash.new + python = Mash.new -status, stdout, stderr = run_command(:no_status_check => true, :command => "python -c \"import sys; print sys.version\"") + status, stdout, stderr = run_command(:no_status_check => true, :command => "python -c \"import sys; print sys.version\"") -if status == 0 - output = stdout.split - python[:version] = output[0] - if output.length >= 6 - python[:builddate] = "%s %s %s %s" % [output[2],output[3],output[4],output[5].gsub!(/\)/,'')] - end + if status == 0 + output = stdout.split + python[:version] = output[0] + if output.length >= 6 + python[:builddate] = "%s %s %s %s" % [output[2],output[3],output[4],output[5].gsub!(/\)/,'')] + end - languages[:python] = python if python[:version] and python[:builddate] + languages[:python] = python if python[:version] and python[:builddate] + end + end end diff --git a/lib/ohai/plugins/rackspace.rb b/lib/ohai/plugins/rackspace.rb index 5f86866f..85fa0f43 100644 --- a/lib/ohai/plugins/rackspace.rb +++ b/lib/ohai/plugins/rackspace.rb @@ -14,96 +14,100 @@ # See the License for the specific language governing permissions and # limitations under the License. -provides "rackspace" +Ohai.plugin(:Rackspace) do + provides "rackspace" -require_plugin "kernel" -require_plugin "network" + depends "kernel" + depends "network", "counters/network" -# Checks for matching rackspace kernel name -# -# === Return -# true:: If kernel name matches -# false:: Otherwise -def has_rackspace_kernel? - kernel[:release].split('-').last.eql?("rscloud") -end + # Checks for matching rackspace kernel name + # + # === Return + # true:: If kernel name matches + # false:: Otherwise + def has_rackspace_kernel? + kernel[:release].split('-').last.eql?("rscloud") + end -# Checks for rackspace provider attribute -# -# === Return -# true:: If rackspace provider attribute found -# false:: Otherwise -def has_rackspace_metadata? - status, stdout, stderr = run_command(:no_status_check => true, :command => "xenstore-read vm-data/provider_data/provider") - if status == 0 - stdout.strip.downcase == 'rackspace' + # Checks for rackspace provider attribute + # + # === Return + # true:: If rackspace provider attribute found + # false:: Otherwise + def has_rackspace_metadata? + status, stdout, stderr = run_command(:no_status_check => true, :command => "xenstore-read vm-data/provider_data/provider") + if status == 0 + stdout.strip.downcase == 'rackspace' + end + rescue Ohai::Exceptions::Exec + false end -rescue Ohai::Exceptions::Exec - false -end -# Identifies the rackspace cloud -# -# === Return -# true:: If the rackspace cloud can be identified -# false:: Otherwise -def looks_like_rackspace? - hint?('rackspace') || has_rackspace_metadata? || has_rackspace_kernel? -end + # Identifies the rackspace cloud + # + # === Return + # true:: If the rackspace cloud can be identified + # false:: Otherwise + def looks_like_rackspace? + hint?('rackspace') || has_rackspace_metadata? || has_rackspace_kernel? + end -# Names rackspace ip address -# -# === Parameters -# name<Symbol>:: Use :public_ip or :private_ip -# eth<Symbol>:: Interface name of public or private ip -def get_ip_address(name, eth) - network[:interfaces][eth][:addresses].each do |key, info| - if info['family'] == 'inet' - rackspace[name] = key - break # break when we found an address + # Names rackspace ip address + # + # === Parameters + # name<Symbol>:: Use :public_ip or :private_ip + # eth<Symbol>:: Interface name of public or private ip + def get_ip_address(name, eth) + network[:interfaces][eth][:addresses].each do |key, info| + if info['family'] == 'inet' + rackspace[name] = key + break # break when we found an address + end end end -end -# Names rackspace ipv6 address for interface -# -# === Parameters -# name<Symbol>:: Use :public_ip or :private_ip -# eth<Symbol>:: Interface name of public or private ip -def get_global_ipv6_address(name, eth) - network[:interfaces][eth][:addresses].each do |key, info| - # check if we got an ipv6 address and if its in global scope - if info['family'] == 'inet6' && info['scope'] == 'Global' - rackspace[name] = key - break # break when we found an address + # Names rackspace ipv6 address for interface + # + # === Parameters + # name<Symbol>:: Use :public_ip or :private_ip + # eth<Symbol>:: Interface name of public or private ip + def get_global_ipv6_address(name, eth) + network[:interfaces][eth][:addresses].each do |key, info| + # check if we got an ipv6 address and if its in global scope + if info['family'] == 'inet6' && info['scope'] == 'Global' + rackspace[name] = key + break # break when we found an address + end end end -end -# Get the rackspace region -# -def get_region() - status, stdout, stderr = run_command(:no_status_check => true, :command => "xenstore-ls vm-data/provider_data") - if status == 0 - stdout.split("\n").each do |line| - rackspace[:region] = line.split[2].delete('\"') if line =~ /^region/ + # Get the rackspace region + # + def get_region() + status, stdout, stderr = run_command(:no_status_check => true, :command => "xenstore-ls vm-data/provider_data") + if status == 0 + stdout.split("\n").each do |line| + rackspace[:region] = line.split[2].delete('\"') if line =~ /^region/ + end end + rescue Ohai::Exceptions::Exec + Ohai::Log.debug("Unable to find xenstore-ls, cannot capture region information for Rackspace cloud") end -rescue Ohai::Exceptions::Exec - Ohai::Log.debug("Unable to find xenstore-ls, cannot capture region information for Rackspace cloud") -end -# Adds rackspace Mash -if looks_like_rackspace? - rackspace Mash.new - get_ip_address(:public_ip, :eth0) - get_ip_address(:private_ip, :eth1) - get_region() - # public_ip + private_ip are deprecated in favor of public_ipv4 and local_ipv4 to standardize. - rackspace[:public_ipv4] = rackspace[:public_ip] - get_global_ipv6_address(:public_ipv6, :eth0) - rackspace[:public_hostname] = "#{rackspace[:public_ip].gsub('.','-')}.static.cloud-ips.com" - rackspace[:local_ipv4] = rackspace[:private_ip] - get_global_ipv6_address(:local_ipv6, :eth1) - rackspace[:local_hostname] = hostname + collect_data do + # Adds rackspace Mash + if looks_like_rackspace? + rackspace Mash.new + get_ip_address(:public_ip, :eth0) + get_ip_address(:private_ip, :eth1) + get_region() + # public_ip + private_ip are deprecated in favor of public_ipv4 and local_ipv4 to standardize. + rackspace[:public_ipv4] = rackspace[:public_ip] + get_global_ipv6_address(:public_ipv6, :eth0) + rackspace[:public_hostname] = "#{rackspace[:public_ip].gsub('.','-')}.static.cloud-ips.com" + rackspace[:local_ipv4] = rackspace[:private_ip] + get_global_ipv6_address(:local_ipv6, :eth1) + rackspace[:local_hostname] = hostname + end + end end diff --git a/lib/ohai/plugins/root_group.rb b/lib/ohai/plugins/root_group.rb index c74bcb0e..1e5145e9 100644 --- a/lib/ohai/plugins/root_group.rb +++ b/lib/ohai/plugins/root_group.rb @@ -15,14 +15,18 @@ # See the License for the specific language governing permissions and # limitations under the License. -provides 'root_group' +Ohai.plugin(:RootGroup) do + provides 'root_group' -case ::RbConfig::CONFIG['host_os'] -when /mswin|mingw32|windows/ - # TODO: OHAI-491 - # http://tickets.opscode.com/browse/OHAI-491 - # The windows implementation of this plugin has been removed because of - # performance considerations (see: OHAI-490). -else - root_group Etc.getgrgid(Etc.getpwnam('root').gid).name + collect_data do + case ::RbConfig::CONFIG['host_os'] + when /mswin|mingw32|windows/ + # TODO: OHAI-491 + # http://tickets.opscode.com/browse/OHAI-491 + # The windows implementation of this plugin has been removed because of + # performance considerations (see: OHAI-490). + else + root_group Etc.getgrgid(Etc.getpwnam('root').gid).name + end + end end diff --git a/lib/ohai/plugins/ruby.rb b/lib/ohai/plugins/ruby.rb index 2bd0e840..05b7642c 100644 --- a/lib/ohai/plugins/ruby.rb +++ b/lib/ohai/plugins/ruby.rb @@ -21,14 +21,13 @@ Ohai.plugin(:Ruby) do depends "languages" - collect_data do - def run_ruby(command) - cmd = "ruby -e \"require 'rbconfig'; #{command}\"" - status, stdout, stderr = run_command(:no_status_check => true, :command => cmd) - stdout.strip - end - + def run_ruby(command) + cmd = "ruby -e \"require 'rbconfig'; #{command}\"" + status, stdout, stderr = run_command(:no_status_check => true, :command => cmd) + stdout.strip + end + collect_data do languages[:ruby] = Mash.new values = { diff --git a/lib/ohai/plugins/sigar/cpu.rb b/lib/ohai/plugins/sigar/cpu.rb index 89cb14c9..e6214f6c 100644 --- a/lib/ohai/plugins/sigar/cpu.rb +++ b/lib/ohai/plugins/sigar/cpu.rb @@ -18,23 +18,27 @@ require "sigar" -sigar = Sigar.new +Ohai.plugin(:Cpu) do + provides "cpu" -provides "cpu" + collect_data do + sigar = Sigar.new -cpuinfo = Mash.new -ix = 0 + cpuinfo = Mash.new + ix = 0 -sigar.cpu_info_list.each do |info| - current_cpu = ix.to_s - ix += 1 - cpuinfo[current_cpu] = Mash.new - cpuinfo[current_cpu]["vendor_id"] = info.vendor - cpuinfo[current_cpu]["model"] = info.model - cpuinfo[current_cpu]["mhz"] = info.mhz.to_s - cpuinfo[current_cpu]["cache_size"] = info.cache_size.to_s - cpuinfo[:total] = info.total_cores - cpuinfo[:real] = info.total_sockets -end + sigar.cpu_info_list.each do |info| + current_cpu = ix.to_s + ix += 1 + cpuinfo[current_cpu] = Mash.new + cpuinfo[current_cpu]["vendor_id"] = info.vendor + cpuinfo[current_cpu]["model"] = info.model + cpuinfo[current_cpu]["mhz"] = info.mhz.to_s + cpuinfo[current_cpu]["cache_size"] = info.cache_size.to_s + cpuinfo[:total] = info.total_cores + cpuinfo[:real] = info.total_sockets + end -cpu cpuinfo + cpu cpuinfo + end +end diff --git a/lib/ohai/plugins/sigar/filesystem.rb b/lib/ohai/plugins/sigar/filesystem.rb index 283414c1..d392dcd5 100644 --- a/lib/ohai/plugins/sigar/filesystem.rb +++ b/lib/ohai/plugins/sigar/filesystem.rb @@ -16,32 +16,36 @@ # limitations under the License. # -provides "filesystem" - require "sigar" -fs = Mash.new +Ohai.plugin(:Filesystem) do + provides "filesystem" + + collect_data do + fs = Mash.new -sigar = Sigar.new + sigar = Sigar.new -sigar.file_system_list.each do |fsys| - filesystem = fsys.dev_name - fs[filesystem] = Mash.new - fs[filesystem][:mount] = fsys.dir_name - fs[filesystem][:fs_type] = fsys.sys_type_name - fs[filesystem][:mount_options] = fsys.options - begin - usage = sigar.file_system_usage(fsys.dir_name) - fs[filesystem][:kb_size] = (usage.total / 1024).to_s - fs[filesystem][:kb_used] = ((usage.total - usage.free) / 1024).to_s - fs[filesystem][:kb_available] = (usage.free / 1024).to_s - fs[filesystem][:percent_used] = (usage.use_percent * 100).to_s + '%' - rescue SystemExit => e - raise - rescue Exception => e - #e.g. floppy or cdrom drive + sigar.file_system_list.each do |fsys| + filesystem = fsys.dev_name + fs[filesystem] = Mash.new + fs[filesystem][:mount] = fsys.dir_name + fs[filesystem][:fs_type] = fsys.sys_type_name + fs[filesystem][:mount_options] = fsys.options + begin + usage = sigar.file_system_usage(fsys.dir_name) + fs[filesystem][:kb_size] = (usage.total / 1024).to_s + fs[filesystem][:kb_used] = ((usage.total - usage.free) / 1024).to_s + fs[filesystem][:kb_available] = (usage.free / 1024).to_s + fs[filesystem][:percent_used] = (usage.use_percent * 100).to_s + '%' + rescue SystemExit => e + raise + rescue Exception => e + #e.g. floppy or cdrom drive + end + end + + # Set the filesystem data + filesystem fs end end - -# Set the filesystem data -filesystem fs diff --git a/lib/ohai/plugins/sigar/hostname.rb b/lib/ohai/plugins/sigar/hostname.rb index 5c563293..ec8bc00e 100644 --- a/lib/ohai/plugins/sigar/hostname.rb +++ b/lib/ohai/plugins/sigar/hostname.rb @@ -18,11 +18,15 @@ require 'sigar' -provides "hostname", "fqdn" +Ohai.plugin(:Hostname) do + provides "hostname", "fqdn" -sigar = Sigar.new + collect_data do + sigar = Sigar.new -hostname sigar.net_info.host_name + hostname sigar.net_info.host_name -fqdn sigar.fqdn + fqdn sigar.fqdn + end +end diff --git a/lib/ohai/plugins/sigar/memory.rb b/lib/ohai/plugins/sigar/memory.rb index 9c3fee48..ae446de2 100644 --- a/lib/ohai/plugins/sigar/memory.rb +++ b/lib/ohai/plugins/sigar/memory.rb @@ -18,19 +18,23 @@ require "sigar" -sigar = Sigar.new +Ohai.plugin(:Memory) do + provides "memory" -provides "memory" + collect_data do + sigar = Sigar.new -memory Mash.new -memory[:swap] = Mash.new + memory Mash.new + memory[:swap] = Mash.new -mem = sigar.mem -swap = sigar.swap + mem = sigar.mem + swap = sigar.swap -memory[:total] = (mem.total / 1024).to_s + "kB" -memory[:free] = (mem.free / 1024).to_s + "kB" -memory[:used] = (mem.used / 1024).to_s + "kB" -memory[:swap][:total] = (swap.total / 1024).to_s + "kB" -memory[:swap][:free] = (swap.free / 1024).to_s + "kB" -memory[:swap][:used] = (swap.used / 1024).to_s + "kB" + memory[:total] = (mem.total / 1024).to_s + "kB" + memory[:free] = (mem.free / 1024).to_s + "kB" + memory[:used] = (mem.used / 1024).to_s + "kB" + memory[:swap][:total] = (swap.total / 1024).to_s + "kB" + memory[:swap][:free] = (swap.free / 1024).to_s + "kB" + memory[:swap][:used] = (swap.used / 1024).to_s + "kB" + end +end diff --git a/lib/ohai/plugins/sigar/network.rb b/lib/ohai/plugins/sigar/network.rb index 2b5c0265..0f63b62d 100644 --- a/lib/ohai/plugins/sigar/network.rb +++ b/lib/ohai/plugins/sigar/network.rb @@ -20,83 +20,87 @@ require "sigar" -sigar = Sigar.new +Ohai.plugin(:Network) do + provides "network", "counters/network" -provides "network", "counters/network" + def encaps_lookup(encap) + return "Loopback" if encap.eql?("Local Loopback") + return "PPP" if encap.eql?("Point-to-Point Protocol") + return "SLIP" if encap.eql?("Serial Line IP") + return "VJSLIP" if encap.eql?("VJ Serial Line IP") + return "IPIP" if encap.eql?("IPIP Tunnel") + return "6to4" if encap.eql?("IPv6-in-IPv4") + encap + end -ninfo = sigar.net_info + collect_data do + sigar = Sigar.new -network[:default_interface] = ninfo.default_gateway_interface + ninfo = sigar.net_info -network[:default_gateway] = ninfo.default_gateway + network[:default_interface] = ninfo.default_gateway_interface -def encaps_lookup(encap) - return "Loopback" if encap.eql?("Local Loopback") - return "PPP" if encap.eql?("Point-to-Point Protocol") - return "SLIP" if encap.eql?("Serial Line IP") - return "VJSLIP" if encap.eql?("VJ Serial Line IP") - return "IPIP" if encap.eql?("IPIP Tunnel") - return "6to4" if encap.eql?("IPv6-in-IPv4") - encap -end + network[:default_gateway] = ninfo.default_gateway -iface = Mash.new + iface = Mash.new -net_counters = Mash.new + net_counters = Mash.new -sigar.net_interface_list.each do |cint| - iface[cint] = Mash.new - if cint =~ /^(\w+)(\d+.*)/ - iface[cint][:type] = $1 - iface[cint][:number] = $2 - end - ifconfig = sigar.net_interface_config(cint) - iface[cint][:encapsulation] = encaps_lookup(ifconfig.type) - iface[cint][:addresses] = Mash.new - # Backwards compat: loopback has no hwaddr - if (ifconfig.flags & Sigar::IFF_LOOPBACK) == 0 - iface[cint][:addresses][ifconfig.hwaddr] = { "family" => "lladdr" } - end - if ifconfig.address != "0.0.0.0" - iface[cint][:addresses][ifconfig.address] = { "family" => "inet" } - # Backwards compat: no broadcast on tunnel or loopback dev - if (((ifconfig.flags & Sigar::IFF_POINTOPOINT) == 0) && - ((ifconfig.flags & Sigar::IFF_LOOPBACK) == 0)) - iface[cint][:addresses][ifconfig.address]["broadcast"] = ifconfig.broadcast + sigar.net_interface_list.each do |cint| + iface[cint] = Mash.new + if cint =~ /^(\w+)(\d+.*)/ + iface[cint][:type] = $1 + iface[cint][:number] = $2 + end + ifconfig = sigar.net_interface_config(cint) + iface[cint][:encapsulation] = encaps_lookup(ifconfig.type) + iface[cint][:addresses] = Mash.new + # Backwards compat: loopback has no hwaddr + if (ifconfig.flags & Sigar::IFF_LOOPBACK) == 0 + iface[cint][:addresses][ifconfig.hwaddr] = { "family" => "lladdr" } + end + if ifconfig.address != "0.0.0.0" + iface[cint][:addresses][ifconfig.address] = { "family" => "inet" } + # Backwards compat: no broadcast on tunnel or loopback dev + if (((ifconfig.flags & Sigar::IFF_POINTOPOINT) == 0) && + ((ifconfig.flags & Sigar::IFF_LOOPBACK) == 0)) + iface[cint][:addresses][ifconfig.address]["broadcast"] = ifconfig.broadcast + end + iface[cint][:addresses][ifconfig.address]["netmask"] = ifconfig.netmask + end + iface[cint][:flags] = Sigar.net_interface_flags_to_s(ifconfig.flags).split(' ') + iface[cint][:mtu] = ifconfig.mtu.to_s + iface[cint][:queuelen] = ifconfig.tx_queue_len.to_s + if ifconfig.prefix6_length != 0 + iface[cint][:addresses][ifconfig.address6] = { "family" => "inet6" } + iface[cint][:addresses][ifconfig.address6]["prefixlen"] = ifconfig.prefix6_length.to_s + iface[cint][:addresses][ifconfig.address6]["scope"] = Sigar.net_scope_to_s(ifconfig.scope6) + end + net_counters[cint] = Mash.new unless net_counters[cint] + if (!cint.include?(":")) + ifstat = sigar.net_interface_stat(cint) + net_counters[cint][:rx] = { "packets" => ifstat.rx_packets.to_s, "errors" => ifstat.rx_errors.to_s, + "drop" => ifstat.rx_dropped.to_s, "overrun" => ifstat.rx_overruns.to_s, + "frame" => ifstat.rx_frame.to_s, "bytes" => ifstat.rx_bytes.to_s } + net_counters[cint][:tx] = { "packets" => ifstat.tx_packets.to_s, "errors" => ifstat.tx_errors.to_s, + "drop" => ifstat.tx_dropped.to_s, "overrun" => ifstat.tx_overruns.to_s, + "carrier" => ifstat.tx_carrier.to_s, "collisions" => ifstat.tx_collisions.to_s, + "bytes" => ifstat.tx_bytes.to_s } + end end - iface[cint][:addresses][ifconfig.address]["netmask"] = ifconfig.netmask - end - iface[cint][:flags] = Sigar.net_interface_flags_to_s(ifconfig.flags).split(' ') - iface[cint][:mtu] = ifconfig.mtu.to_s - iface[cint][:queuelen] = ifconfig.tx_queue_len.to_s - if ifconfig.prefix6_length != 0 - iface[cint][:addresses][ifconfig.address6] = { "family" => "inet6" } - iface[cint][:addresses][ifconfig.address6]["prefixlen"] = ifconfig.prefix6_length.to_s - iface[cint][:addresses][ifconfig.address6]["scope"] = Sigar.net_scope_to_s(ifconfig.scope6) - end - net_counters[cint] = Mash.new unless net_counters[cint] - if (!cint.include?(":")) - ifstat = sigar.net_interface_stat(cint) - net_counters[cint][:rx] = { "packets" => ifstat.rx_packets.to_s, "errors" => ifstat.rx_errors.to_s, - "drop" => ifstat.rx_dropped.to_s, "overrun" => ifstat.rx_overruns.to_s, - "frame" => ifstat.rx_frame.to_s, "bytes" => ifstat.rx_bytes.to_s } - net_counters[cint][:tx] = { "packets" => ifstat.tx_packets.to_s, "errors" => ifstat.tx_errors.to_s, - "drop" => ifstat.tx_dropped.to_s, "overrun" => ifstat.tx_overruns.to_s, - "carrier" => ifstat.tx_carrier.to_s, "collisions" => ifstat.tx_collisions.to_s, - "bytes" => ifstat.tx_bytes.to_s } - end -end -begin - sigar.arp_list.each do |arp| - next unless iface[arp.ifname] # this should never happen - iface[arp.ifname][:arp] = Mash.new unless iface[arp.ifname][:arp] - iface[arp.ifname][:arp][arp.address] = arp.hwaddr - end -rescue - #64-bit AIX for example requires 64-bit caller -end + begin + sigar.arp_list.each do |arp| + next unless iface[arp.ifname] # this should never happen + iface[arp.ifname][:arp] = Mash.new unless iface[arp.ifname][:arp] + iface[arp.ifname][:arp][arp.address] = arp.hwaddr + end + rescue + #64-bit AIX for example requires 64-bit caller + end -counters[:network][:interfaces] = net_counters + counters[:network][:interfaces] = net_counters -network["interfaces"] = iface + network["interfaces"] = iface + end +end diff --git a/lib/ohai/plugins/sigar/network_route.rb b/lib/ohai/plugins/sigar/network_route.rb index b13c1235..4cf2908a 100644 --- a/lib/ohai/plugins/sigar/network_route.rb +++ b/lib/ohai/plugins/sigar/network_route.rb @@ -17,38 +17,43 @@ # require "sigar" -require_plugin "network" -provides "network" +Ohai.plugin(:NetworkRoute) do + depends "network" -def flags(flags) - f = "" - if (flags & Sigar::RTF_UP) != 0 - f += "U" - end - if (flags & Sigar::RTF_GATEWAY) != 0 - f += "G" - end - if (flags & Sigar::RTF_HOST) != 0 - f += "H" + provides "network" + + def flags(flags) + f = "" + if (flags & Sigar::RTF_UP) != 0 + f += "U" + end + if (flags & Sigar::RTF_GATEWAY) != 0 + f += "G" + end + if (flags & Sigar::RTF_HOST) != 0 + f += "H" + end + f end - f -end -# From sigar: include/sigar.h sigar_net_route_t -SIGAR_ROUTE_METHODS = [:destination, :gateway, :mask, :flags, :refcnt, :use, :metric, :mtu, :window, :irtt, :ifname] + # From sigar: include/sigar.h sigar_net_route_t + SIGAR_ROUTE_METHODS = [:destination, :gateway, :mask, :flags, :refcnt, :use, :metric, :mtu, :window, :irtt, :ifname] -sigar=Sigar.new -sigar.net_route_list.each do |route| - next unless network[:interfaces][route.ifname] # this should never happen - network[:interfaces][route.ifname][:route] = Mash.new unless network[:interfaces][route.ifname][:route] - route_data={} - SIGAR_ROUTE_METHODS.each do |m| - if(m == :flags) - route_data[m]=flags(route.send(m)) - else - route_data[m]=route.send(m) + collect_data do + sigar=Sigar.new + sigar.net_route_list.each do |route| + next unless network[:interfaces][route.ifname] # this should never happen + network[:interfaces][route.ifname][:route] = Mash.new unless network[:interfaces][route.ifname][:route] + route_data={} + SIGAR_ROUTE_METHODS.each do |m| + if(m == :flags) + route_data[m]=flags(route.send(m)) + else + route_data[m]=route.send(m) + end + end + network[:interfaces][route.ifname][:route][route.destination] = route_data end end - network[:interfaces][route.ifname][:route][route.destination] = route_data end diff --git a/lib/ohai/plugins/sigar/platform.rb b/lib/ohai/plugins/sigar/platform.rb index 1fedb564..4a1d55fd 100644 --- a/lib/ohai/plugins/sigar/platform.rb +++ b/lib/ohai/plugins/sigar/platform.rb @@ -18,9 +18,13 @@ require "sigar" -provides "platform", "platform_version" +Ohai.plugin(:Platform) do + provides "platform", "platform_version" -sys = Sigar.new.sys_info + collect_data do + sys = Sigar.new.sys_info -platform sys.name.downcase -platform_version sys.version + platform sys.name.downcase + platform_version sys.version + end +end diff --git a/lib/ohai/plugins/sigar/uptime.rb b/lib/ohai/plugins/sigar/uptime.rb index 8d43d73a..68676677 100644 --- a/lib/ohai/plugins/sigar/uptime.rb +++ b/lib/ohai/plugins/sigar/uptime.rb @@ -18,10 +18,13 @@ require "sigar" -sigar = Sigar.new +Ohai.plugin(:Uptime) do + provides "uptime", "uptime_seconds" -provides "uptime", "uptime_seconds" - -uptime = sigar.uptime.uptime -uptime_seconds uptime.to_i * 1000 -uptime seconds_to_human(uptime.to_i) + collect_data do + sigar = Sigar.new + uptime = sigar.uptime.uptime + uptime_seconds uptime.to_i * 1000 + uptime seconds_to_human(uptime.to_i) + end +end diff --git a/lib/ohai/plugins/solaris2/dmi.rb b/lib/ohai/plugins/solaris2/dmi.rb index 87d00fb3..b374ce53 100644 --- a/lib/ohai/plugins/solaris2/dmi.rb +++ b/lib/ohai/plugins/solaris2/dmi.rb @@ -16,161 +16,165 @@ # limitations under the License. # -require_plugin "dmi" +Ohai.plugin(:Dmi) do + depends "dmi" -# if we already have a "dmi" with keys (presumably from dmidecode), don't try smbios -# note that a single key just means dmidecode exited with its version -if (dmi.class.to_s == 'Mash') and (dmi.keys.length > 1) - Ohai::Log.debug('skipping smbios output, since DMI information has already been provided') - return -end + collect_data do + # if we already have a "dmi" with keys (presumably from dmidecode), don't try smbios + # note that a single key just means dmidecode exited with its version + if (dmi.class.to_s == 'Mash') and (dmi.keys.length > 1) + Ohai::Log.debug('skipping smbios output, since DMI information has already been provided') + return + end -dmi Mash.new + dmi Mash.new -# bad Solaris shows strings defined by system instead of SMB IDs -# this is what the *real* IDs are: -# pulled from http://src.opensolaris.org/source/xref/nwam/nwam1/usr/src/uts/common/sys/smbios.h -smb_to_id = { - 'SMB_TYPE_BIOS' => 0, # BIOS information (R) - 'SMB_TYPE_SYSTEM' => 1, # system information (R) - 'SMB_TYPE_BASEBOARD' => 2, # base board - 'SMB_TYPE_CHASSIS' => 3, # system enclosure or chassis (R) - 'SMB_TYPE_PROCESSOR' => 4, # processor (R) - 'SMB_TYPE_MEMCTL' => 5, # memory controller (O) - 'SMB_TYPE_MEMMOD' => 6, # memory module (O) - 'SMB_TYPE_CACHE' => 7, # processor cache (R) - 'SMB_TYPE_PORT' => 8, # port connector - 'SMB_TYPE_SLOT' => 9, # upgradeable system slot (R) - 'SMB_TYPE_OBDEVS' => 10, # on-board devices - 'SMB_TYPE_OEMSTR' => 11, # OEM string table - 'SMB_TYPE_SYSCONFSTR' => 12, # system configuration string table - 'SMB_TYPE_LANG' => 13, # BIOS language information - 'SMB_TYPE_GROUP' => 14, # group associations - 'SMB_TYPE_EVENTLOG' => 15, # system event log - 'SMB_TYPE_MEMARRAY' => 16, # physical memory array (R) - 'SMB_TYPE_MEMDEVICE' => 17, # memory device (R) - 'SMB_TYPE_MEMERR32' => 18, # 32-bit memory error information - 'SMB_TYPE_MEMARRAYMAP' => 19, # memory array mapped address (R) - 'SMB_TYPE_MEMDEVICEMAP' => 20, # memory device mapped address (R) - 'SMB_TYPE_POINTDEV' => 21, # built-in pointing device - 'SMB_TYPE_BATTERY' => 22, # portable battery - 'SMB_TYPE_RESET' => 23, # system reset settings - 'SMB_TYPE_SECURITY' => 24, # hardware security settings - 'SMB_TYPE_POWERCTL' => 25, # system power controls - 'SMB_TYPE_VPROBE' => 26, # voltage probe - 'SMB_TYPE_COOLDEV' => 27, # cooling device - 'SMB_TYPE_TPROBE' => 28, # temperature probe - 'SMB_TYPE_IPROBE' => 29, # current probe - 'SMB_TYPE_OOBRA' => 30, # out-of-band remote access facility - 'SMB_TYPE_BIS' => 31, # boot integrity services - 'SMB_TYPE_BOOT' => 32, # system boot status (R) - 'SMB_TYPE_MEMERR64' => 33, # 64-bit memory error information - 'SMB_TYPE_MGMTDEV' => 34, # management device - 'SMB_TYPE_MGMTDEVCP' => 35, # management device component - 'SMB_TYPE_MGMTDEVDATA' => 36, # management device threshold data - 'SMB_TYPE_MEMCHAN' => 37, # memory channel - 'SMB_TYPE_IPMIDEV' => 38, # IPMI device information - 'SMB_TYPE_POWERSUP' => 39, # system power supply - 'SMB_TYPE_INACTIVE' => 126, # inactive table entry - 'SMB_TYPE_EOT' => 127, # end of table - 'SMB_TYPE_OEM_LO' => 128, # start of OEM-specific type range - 'SUN_OEM_EXT_PROCESSOR' => 132, # processor extended info - 'SUN_OEM_PCIEXRC' => 138, # PCIE RootComplex/RootPort info - 'SUN_OEM_EXT_MEMARRAY' => 144, # phys memory array extended info - 'SUN_OEM_EXT_MEMDEVICE' => 145, # memory device extended info - 'SMB_TYPE_OEM_HI' => 256, # end of OEM-specific type range -} + # bad Solaris shows strings defined by system instead of SMB IDs + # this is what the *real* IDs are: + # pulled from http://src.opensolaris.org/source/xref/nwam/nwam1/usr/src/uts/common/sys/smbios.h + smb_to_id = { + 'SMB_TYPE_BIOS' => 0, # BIOS information (R) + 'SMB_TYPE_SYSTEM' => 1, # system information (R) + 'SMB_TYPE_BASEBOARD' => 2, # base board + 'SMB_TYPE_CHASSIS' => 3, # system enclosure or chassis (R) + 'SMB_TYPE_PROCESSOR' => 4, # processor (R) + 'SMB_TYPE_MEMCTL' => 5, # memory controller (O) + 'SMB_TYPE_MEMMOD' => 6, # memory module (O) + 'SMB_TYPE_CACHE' => 7, # processor cache (R) + 'SMB_TYPE_PORT' => 8, # port connector + 'SMB_TYPE_SLOT' => 9, # upgradeable system slot (R) + 'SMB_TYPE_OBDEVS' => 10, # on-board devices + 'SMB_TYPE_OEMSTR' => 11, # OEM string table + 'SMB_TYPE_SYSCONFSTR' => 12, # system configuration string table + 'SMB_TYPE_LANG' => 13, # BIOS language information + 'SMB_TYPE_GROUP' => 14, # group associations + 'SMB_TYPE_EVENTLOG' => 15, # system event log + 'SMB_TYPE_MEMARRAY' => 16, # physical memory array (R) + 'SMB_TYPE_MEMDEVICE' => 17, # memory device (R) + 'SMB_TYPE_MEMERR32' => 18, # 32-bit memory error information + 'SMB_TYPE_MEMARRAYMAP' => 19, # memory array mapped address (R) + 'SMB_TYPE_MEMDEVICEMAP' => 20, # memory device mapped address (R) + 'SMB_TYPE_POINTDEV' => 21, # built-in pointing device + 'SMB_TYPE_BATTERY' => 22, # portable battery + 'SMB_TYPE_RESET' => 23, # system reset settings + 'SMB_TYPE_SECURITY' => 24, # hardware security settings + 'SMB_TYPE_POWERCTL' => 25, # system power controls + 'SMB_TYPE_VPROBE' => 26, # voltage probe + 'SMB_TYPE_COOLDEV' => 27, # cooling device + 'SMB_TYPE_TPROBE' => 28, # temperature probe + 'SMB_TYPE_IPROBE' => 29, # current probe + 'SMB_TYPE_OOBRA' => 30, # out-of-band remote access facility + 'SMB_TYPE_BIS' => 31, # boot integrity services + 'SMB_TYPE_BOOT' => 32, # system boot status (R) + 'SMB_TYPE_MEMERR64' => 33, # 64-bit memory error information + 'SMB_TYPE_MGMTDEV' => 34, # management device + 'SMB_TYPE_MGMTDEVCP' => 35, # management device component + 'SMB_TYPE_MGMTDEVDATA' => 36, # management device threshold data + 'SMB_TYPE_MEMCHAN' => 37, # memory channel + 'SMB_TYPE_IPMIDEV' => 38, # IPMI device information + 'SMB_TYPE_POWERSUP' => 39, # system power supply + 'SMB_TYPE_INACTIVE' => 126, # inactive table entry + 'SMB_TYPE_EOT' => 127, # end of table + 'SMB_TYPE_OEM_LO' => 128, # start of OEM-specific type range + 'SUN_OEM_EXT_PROCESSOR' => 132, # processor extended info + 'SUN_OEM_PCIEXRC' => 138, # PCIE RootComplex/RootPort info + 'SUN_OEM_EXT_MEMARRAY' => 144, # phys memory array extended info + 'SUN_OEM_EXT_MEMDEVICE' => 145, # memory device extended info + 'SMB_TYPE_OEM_HI' => 256, # end of OEM-specific type range + } -# all output lines should fall within one of these patterns -header_type_line = /^ID\s+SIZE\s+TYPE/ -header_information_line = /^(\d+)\s+(\d+)\s+(\S+)\s+\(([^\)]+)\)/ -blank_line = /^\s*$/ -data_key_value_line = /^ ([^:]+): (.*)/ -data_key_only_line = /^ (\S.*)(:\s*)?$/ -extended_data_line = /^\t(\S+) \((.+)\)/ + # all output lines should fall within one of these patterns + header_type_line = /^ID\s+SIZE\s+TYPE/ + header_information_line = /^(\d+)\s+(\d+)\s+(\S+)\s+\(([^\)]+)\)/ + blank_line = /^\s*$/ + data_key_value_line = /^ ([^:]+): (.*)/ + data_key_only_line = /^ (\S.*)(:\s*)?$/ + extended_data_line = /^\t(\S+) \((.+)\)/ -dmi_record = nil -field = nil + dmi_record = nil + field = nil -popen4("smbios") do |pid, stdin, stdout, stderr| - stdin.close - - # ==== EXAMPLE: ==== - # ID SIZE TYPE - # 0 40 SMB_TYPE_BIOS (BIOS information) - # - # Vendor: HP - # Version String: 2.16 - # ... similar lines trimmed - # Characteristics: 0x7fc9da80 - # SMB_BIOSFL_PCI (PCI is supported) - # ... similar lines trimmed - # note the second level of indentation is via a *tab* - stdout.each do |raw_line| - next if header_type_line.match(raw_line) - next if blank_line.match(raw_line) + popen4("smbios") do |pid, stdin, stdout, stderr| + stdin.close + + # ==== EXAMPLE: ==== + # ID SIZE TYPE + # 0 40 SMB_TYPE_BIOS (BIOS information) + # + # Vendor: HP + # Version String: 2.16 + # ... similar lines trimmed + # Characteristics: 0x7fc9da80 + # SMB_BIOSFL_PCI (PCI is supported) + # ... similar lines trimmed + # note the second level of indentation is via a *tab* + stdout.each do |raw_line| + next if header_type_line.match(raw_line) + next if blank_line.match(raw_line) - # remove/replace any characters that don't fall inside permissible ASCII range, or whitespace - line = raw_line.gsub(/[^\x20-\x7E\n\t\r]/, '.') - if (line != raw_line) - Ohai::Log.debug("converted characters from line:\n#{raw_line}") - end + # remove/replace any characters that don't fall inside permissible ASCII range, or whitespace + line = raw_line.gsub(/[^\x20-\x7E\n\t\r]/, '.') + if (line != raw_line) + Ohai::Log.debug("converted characters from line:\n#{raw_line}") + end - if header_information = header_information_line.match(line) - dmi_record = {} + if header_information = header_information_line.match(line) + dmi_record = {} - # look up SMB ID - if smb_to_id.has_key?(header_information[3]) - dmi_record[:type] = DMI.id_lookup(smb_to_id[header_information[3]]) + # look up SMB ID + if smb_to_id.has_key?(header_information[3]) + dmi_record[:type] = DMI.id_lookup(smb_to_id[header_information[3]]) - else - dmi_record[:type] = header_information[3].downcase - Ohai::Log.debug("unrecognized header type; falling back to #{dmi_record[:type]}") - end + else + dmi_record[:type] = header_information[3].downcase + Ohai::Log.debug("unrecognized header type; falling back to #{dmi_record[:type]}") + end - dmi[dmi_record[:type]] = Mash.new unless dmi.has_key?(dmi_record[:type]) - dmi[dmi_record[:type]][:all_records] = [] unless dmi[dmi_record[:type]].has_key?(:all_records) - dmi_record[:position] = dmi[dmi_record[:type]][:all_records].length - dmi[dmi_record[:type]][:all_records].push(Mash.new) - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:record_id] = header_information[1] - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:size] = header_information[2] - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:application_identifier] = header_information[4] - field = nil - - elsif data = data_key_value_line.match(line) - if dmi_record == nil - Ohai::Log.debug("unexpected data line found before header; discarding:\n#{line}") - next - end - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][data[1]] = data[2] - field = data[1] - - elsif data = data_key_only_line.match(line) - if dmi_record == nil - Ohai::Log.debug("unexpected data line found before header; discarding:\n#{line}") - next - end - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][data[1]] = '' - field = data[1] - - elsif extended_data = extended_data_line.match(line) - if dmi_record == nil - Ohai::Log.debug("unexpected extended data line found before header; discarding:\n#{line}") - next - end - if field == nil - Ohai::Log.debug("unexpected extended data line found outside data section; discarding:\n#{line}") - next - end - # overwrite "raw" value with a new Mash - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field] = Mash.new unless dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field].class.to_s == 'Mash' - dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field][extended_data[1]] = extended_data[2] + dmi[dmi_record[:type]] = Mash.new unless dmi.has_key?(dmi_record[:type]) + dmi[dmi_record[:type]][:all_records] = [] unless dmi[dmi_record[:type]].has_key?(:all_records) + dmi_record[:position] = dmi[dmi_record[:type]][:all_records].length + dmi[dmi_record[:type]][:all_records].push(Mash.new) + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:record_id] = header_information[1] + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:size] = header_information[2] + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][:application_identifier] = header_information[4] + field = nil + + elsif data = data_key_value_line.match(line) + if dmi_record == nil + Ohai::Log.debug("unexpected data line found before header; discarding:\n#{line}") + next + end + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][data[1]] = data[2] + field = data[1] + + elsif data = data_key_only_line.match(line) + if dmi_record == nil + Ohai::Log.debug("unexpected data line found before header; discarding:\n#{line}") + next + end + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][data[1]] = '' + field = data[1] + + elsif extended_data = extended_data_line.match(line) + if dmi_record == nil + Ohai::Log.debug("unexpected extended data line found before header; discarding:\n#{line}") + next + end + if field == nil + Ohai::Log.debug("unexpected extended data line found outside data section; discarding:\n#{line}") + next + end + # overwrite "raw" value with a new Mash + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field] = Mash.new unless dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field].class.to_s == 'Mash' + dmi[dmi_record[:type]][:all_records][dmi_record[:position]][field][extended_data[1]] = extended_data[2] - else - Ohai::Log.debug("unrecognized output line; discarding:\n#{line}") + else + Ohai::Log.debug("unrecognized output line; discarding:\n#{line}") + end + end end + + DMI.convenience_keys(dmi) end end - -DMI.convenience_keys(dmi) diff --git a/lib/ohai/plugins/solaris2/filesystem.rb b/lib/ohai/plugins/solaris2/filesystem.rb index ddc7d7a9..02ca98ee 100644 --- a/lib/ohai/plugins/solaris2/filesystem.rb +++ b/lib/ohai/plugins/solaris2/filesystem.rb @@ -16,86 +16,90 @@ # limitations under the License. # -provides "filesystem" +Ohai.plugin(:Filesystem) do + provides "filesystem" -fs = Mash.new + collect_data do + fs = Mash.new -# Grab filesystem data from df -popen4("df -Pka") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^Filesystem\s+kbytes/ - next - when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ - filesystem = $1 - fs[filesystem] = Mash.new - fs[filesystem][:kb_size] = $2 - fs[filesystem][:kb_used] = $3 - fs[filesystem][:kb_available] = $4 - fs[filesystem][:percent_used] = $5 - fs[filesystem][:mount] = $6 - end - end -end + # Grab filesystem data from df + popen4("df -Pka") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^Filesystem\s+kbytes/ + next + when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/ + filesystem = $1 + fs[filesystem] = Mash.new + fs[filesystem][:kb_size] = $2 + fs[filesystem][:kb_used] = $3 + fs[filesystem][:kb_available] = $4 + fs[filesystem][:percent_used] = $5 + fs[filesystem][:mount] = $6 + end + end + end -# Grab file system type from df (must be done separately) -popen4("df -na") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - next unless (line =~ /^(.+?)\s*: (\S+)\s*$/) - mount = $1 - fs.each { |filesystem,fs_attributes| - next unless (fs_attributes[:mount] == mount) - fs[filesystem][:fs_type] = $2 - } - end -end + # Grab file system type from df (must be done separately) + popen4("df -na") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + next unless (line =~ /^(.+?)\s*: (\S+)\s*$/) + mount = $1 + fs.each { |filesystem,fs_attributes| + next unless (fs_attributes[:mount] == mount) + fs[filesystem][:fs_type] = $2 + } + end + end -# Grab mount information from /bin/mount -popen4("mount") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - next unless (line =~ /^(.+?) on (.+?) (.+?) on (.+?)$/) - filesystem = $2 - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem][:mount] = $1 - fs[filesystem][:mount_time] = $4 # $4 must come before "split", else it becomes nil - fs[filesystem][:mount_options] = $3.split("/") - end -end + # Grab mount information from /bin/mount + popen4("mount") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + next unless (line =~ /^(.+?) on (.+?) (.+?) on (.+?)$/) + filesystem = $2 + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem][:mount] = $1 + fs[filesystem][:mount_time] = $4 # $4 must come before "split", else it becomes nil + fs[filesystem][:mount_options] = $3.split("/") + end + end -# Grab any zfs data from "zfs get" -zfs = Mash.new -popen4("zfs get -p -H all") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - next unless (line =~ /^([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)$/) - filesystem = $1 - zfs[filesystem] = Mash.new unless zfs.has_key?(filesystem) - zfs[filesystem][:values] = Mash.new unless zfs[filesystem].has_key?('values') - zfs[filesystem][:sources] = Mash.new unless zfs[filesystem].has_key?('sources') - zfs[filesystem][:values][$2] = $3 - zfs[filesystem][:sources][$2] = $4.chomp - end -end -zfs.each { |filesystem, attributes| - fs[filesystem] = Mash.new unless fs.has_key?(filesystem) - fs[filesystem][:fs_type] = 'zfs' - fs[filesystem][:mount] = attributes[:values][:mountpoint] if attributes[:values].has_key?('mountpoint') - fs[filesystem][:zfs_values] = attributes[:values] - fs[filesystem][:zfs_sources] = attributes[:sources] - # find all zfs parents - parents = filesystem.split('/') - zfs_parents = [] - (0 .. parents.length - 1).to_a.each { |parent_indexes| - next_parent = parents[0 .. parent_indexes].join('/') - zfs_parents.push(next_parent) - } - zfs_parents.pop - fs[filesystem][:zfs_parents] = zfs_parents - fs[filesystem][:zfs_zpool] = (zfs_parents.length == 0) -} + # Grab any zfs data from "zfs get" + zfs = Mash.new + popen4("zfs get -p -H all") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + next unless (line =~ /^([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)$/) + filesystem = $1 + zfs[filesystem] = Mash.new unless zfs.has_key?(filesystem) + zfs[filesystem][:values] = Mash.new unless zfs[filesystem].has_key?('values') + zfs[filesystem][:sources] = Mash.new unless zfs[filesystem].has_key?('sources') + zfs[filesystem][:values][$2] = $3 + zfs[filesystem][:sources][$2] = $4.chomp + end + end + zfs.each { |filesystem, attributes| + fs[filesystem] = Mash.new unless fs.has_key?(filesystem) + fs[filesystem][:fs_type] = 'zfs' + fs[filesystem][:mount] = attributes[:values][:mountpoint] if attributes[:values].has_key?('mountpoint') + fs[filesystem][:zfs_values] = attributes[:values] + fs[filesystem][:zfs_sources] = attributes[:sources] + # find all zfs parents + parents = filesystem.split('/') + zfs_parents = [] + (0 .. parents.length - 1).to_a.each { |parent_indexes| + next_parent = parents[0 .. parent_indexes].join('/') + zfs_parents.push(next_parent) + } + zfs_parents.pop + fs[filesystem][:zfs_parents] = zfs_parents + fs[filesystem][:zfs_zpool] = (zfs_parents.length == 0) + } -# Set the filesystem data -filesystem fs + # Set the filesystem data + filesystem fs + end +end diff --git a/lib/ohai/plugins/solaris2/hostname.rb b/lib/ohai/plugins/solaris2/hostname.rb index 9c1b4272..8dbeb77a 100644 --- a/lib/ohai/plugins/solaris2/hostname.rb +++ b/lib/ohai/plugins/solaris2/hostname.rb @@ -17,18 +17,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # + require 'socket' -provides "hostname", "fqdn" +Ohai.plugin(:Hostname) do + provides "hostname", "fqdn" -hostname from("hostname") + collect_data do + hostname from("hostname") -fqdn_lookup = Socket.getaddrinfo(hostname, nil, nil, nil, nil, Socket::AI_CANONNAME).first[2] + fqdn_lookup = Socket.getaddrinfo(hostname, nil, nil, nil, nil, Socket::AI_CANONNAME).first[2] -if fqdn_lookup.split('.').length > 1 - # we recieved an fqdn - fqdn fqdn_lookup -else - # default to assembling one - fqdn(from("hostname") + "." + from("domainname")) + if fqdn_lookup.split('.').length > 1 + # we recieved an fqdn + fqdn fqdn_lookup + else + # default to assembling one + fqdn(from("hostname") + "." + from("domainname")) + end + end end diff --git a/lib/ohai/plugins/solaris2/kernel.rb b/lib/ohai/plugins/solaris2/kernel.rb index e981f1f4..50d71170 100644 --- a/lib/ohai/plugins/solaris2/kernel.rb +++ b/lib/ohai/plugins/solaris2/kernel.rb @@ -16,25 +16,28 @@ # limitations under the License. # -provides "kernel/os" +Ohai.plugin(:Kernel) do + provides "kernel/os" -kernel[:os] = from("uname -s") + collect_data do + kernel[:os] = from("uname -s") -modules = Mash.new + modules = Mash.new -popen4("modinfo") do |pid, stdin, stdout, stderr| - stdin.close - - # EXAMPLE: - # Id Loadaddr Size Info Rev Module Name - # 6 1180000 4623 1 1 specfs (filesystem for specfs) - module_description = /[\s]*([\d]+)[\s]+([a-f\d]+)[\s]+([a-f\d]+)[\s]+(?:[\-\d]+)[\s]+(?:[\d]+)[\s]+([\S]+)[\s]+\((.+)\)$/ - stdout.each do |line| - if mod = module_description.match(line) - modules[mod[4]] = { :id => mod[1].to_i, :loadaddr => mod[2], :size => mod[3].to_i(16), :description => mod[5]} + popen4("modinfo") do |pid, stdin, stdout, stderr| + stdin.close + + # EXAMPLE: + # Id Loadaddr Size Info Rev Module Name + # 6 1180000 4623 1 1 specfs (filesystem for specfs) + module_description = /[\s]*([\d]+)[\s]+([a-f\d]+)[\s]+([a-f\d]+)[\s]+(?:[\-\d]+)[\s]+(?:[\d]+)[\s]+([\S]+)[\s]+\((.+)\)$/ + stdout.each do |line| + if mod = module_description.match(line) + modules[mod[4]] = { :id => mod[1].to_i, :loadaddr => mod[2], :size => mod[3].to_i(16), :description => mod[5]} + end + end end + + kernel[:modules] = modules end end - -kernel[:modules] = modules - diff --git a/lib/ohai/plugins/solaris2/network.rb b/lib/ohai/plugins/solaris2/network.rb index 6a9da9bb..9939de19 100644 --- a/lib/ohai/plugins/solaris2/network.rb +++ b/lib/ohai/plugins/solaris2/network.rb @@ -53,108 +53,111 @@ # srcof qfe1 # inet6 fe80::203:baff:fe17:4444/128 -provides "network" - require 'scanf' -def encaps_lookup(ifname) - return "Ethernet" if ifname.eql?("e1000g") - return "Ethernet" if ifname.eql?("eri") - return "Ethernet" if ifname.eql?("net") - return "Loopback" if ifname.eql?("lo") - "Unknown" -end +Ohai.plugin(:Network) do + provides "network" -def arpname_to_ifname(iface, arpname) - iface.keys.each do |ifn| - return ifn if ifn.split(':')[0].eql?(arpname) + def encaps_lookup(ifname) + return "Ethernet" if ifname.eql?("e1000g") + return "Ethernet" if ifname.eql?("eri") + return "Ethernet" if ifname.eql?("net") + return "Loopback" if ifname.eql?("lo") + "Unknown" end - nil -end - -iface = Mash.new -popen4("ifconfig -a") do |pid, stdin, stdout, stderr| - stdin.close - cint = nil - stdout.each do |line| - if line =~ /^([0-9a-zA-Z\.\:\-]+): \S+ mtu (\d+) index (\d+)/ - cint = $1 - iface[cint] = Mash.new unless iface[cint] - iface[cint][:mtu] = $2 - iface[cint][:index] = $3 - if line =~ / flags\=\d+\<((ADDRCONF|ANYCAST|BROADCAST|CoS|DEPRECATED|DHCP|DUPLICATE|FAILED|FIXEDMTU|INACTIVE|L3PROTECT|LOOPBACK|MIP|MULTI_BCAST|MULTICAST|NOARP|NOFAILOVER|NOLOCAL|NONUD|NORTEXCH|NOXMIT|OFFLINE|POINTOPOINT|PREFERRED|PRIVATE|ROUTER|RUNNING|STANDBY|TEMPORARY|UNNUMBERED|UP|VIRTUAL|XRESOLV|IPv4|IPv6|,)+)\>\s/ - flags = $1.split(',') - else - flags = Array.new - end - iface[cint][:flags] = flags.flatten - if cint =~ /^(\w+)(\d+.*)/ - iface[cint][:type] = $1 - iface[cint][:number] = $2 - iface[cint][:encapsulation] = encaps_lookup($1) - end - end - if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask (([0-9a-f]){1,8})\s*$/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => $2.scanf('%2x'*4)*"."} - end - if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask (([0-9a-f]){1,8}) broadcast (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => $2.scanf('%2x'*4)*".", "broadcast" => $4 } - end - if line =~ /\s+inet6 ([a-f0-9\:]+)(\s*|(\%[a-z0-9]+)\s*)\/(\d+)\s*$/ - iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] - iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $4 } + def arpname_to_ifname(iface, arpname) + iface.keys.each do |ifn| + return ifn if ifn.split(':')[0].eql?(arpname) end + + nil end -end -popen4("arp -an") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /([0-9a-zA-Z]+)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\w+)\s+([a-zA-Z0-9\.\:\-]+)/ - next unless iface[arpname_to_ifname(iface, $1)] # this should never happen, except on solaris because sun hates you. - iface[arpname_to_ifname(iface, $1)][:arp] = Mash.new unless iface[arpname_to_ifname(iface, $1)][:arp] - iface[arpname_to_ifname(iface, $1)][:arp][$2] = $5 + collect_data do + iface = Mash.new + popen4("ifconfig -a") do |pid, stdin, stdout, stderr| + stdin.close + cint = nil + stdout.each do |line| + if line =~ /^([0-9a-zA-Z\.\:\-]+): \S+ mtu (\d+) index (\d+)/ + cint = $1 + iface[cint] = Mash.new unless iface[cint] + iface[cint][:mtu] = $2 + iface[cint][:index] = $3 + if line =~ / flags\=\d+\<((ADDRCONF|ANYCAST|BROADCAST|CoS|DEPRECATED|DHCP|DUPLICATE|FAILED|FIXEDMTU|INACTIVE|L3PROTECT|LOOPBACK|MIP|MULTI_BCAST|MULTICAST|NOARP|NOFAILOVER|NOLOCAL|NONUD|NORTEXCH|NOXMIT|OFFLINE|POINTOPOINT|PREFERRED|PRIVATE|ROUTER|RUNNING|STANDBY|TEMPORARY|UNNUMBERED|UP|VIRTUAL|XRESOLV|IPv4|IPv6|,)+)\>\s/ + flags = $1.split(',') + else + flags = Array.new + end + iface[cint][:flags] = flags.flatten + if cint =~ /^(\w+)(\d+.*)/ + iface[cint][:type] = $1 + iface[cint][:number] = $2 + iface[cint][:encapsulation] = encaps_lookup($1) + end + end + if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask (([0-9a-f]){1,8})\s*$/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => $2.scanf('%2x'*4)*"."} + end + if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask (([0-9a-f]){1,8}) broadcast (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet", "netmask" => $2.scanf('%2x'*4)*".", "broadcast" => $4 } + end + if line =~ /\s+inet6 ([a-f0-9\:]+)(\s*|(\%[a-z0-9]+)\s*)\/(\d+)\s*$/ + iface[cint][:addresses] = Mash.new unless iface[cint][:addresses] + iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $4 } + end + end end - end -end -iface.keys.each do |ifn| - iaddr = nil - if iface[ifn][:encapsulation].eql?("Ethernet") - iface[ifn][:addresses].keys.each do |addr| - if iface[ifn][:addresses][addr]["family"].eql?("inet") - iaddr = addr - break + popen4("arp -an") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /([0-9a-zA-Z]+)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\w+)\s+([a-zA-Z0-9\.\:\-]+)/ + next unless iface[arpname_to_ifname(iface, $1)] # this should never happen, except on solaris because sun hates you. + iface[arpname_to_ifname(iface, $1)][:arp] = Mash.new unless iface[arpname_to_ifname(iface, $1)][:arp] + iface[arpname_to_ifname(iface, $1)][:arp][$2] = $5 + end end end - if iface[ifn][:arp] - iface[ifn][:arp].keys.each do |addr| - if addr.eql?(iaddr) - iface[ifn][:addresses][iface[ifn][:arp][iaddr]] = { "family" => "lladdr" } - break + + iface.keys.each do |ifn| + iaddr = nil + if iface[ifn][:encapsulation].eql?("Ethernet") + iface[ifn][:addresses].keys.each do |addr| + if iface[ifn][:addresses][addr]["family"].eql?("inet") + iaddr = addr + break + end + end + if iface[ifn][:arp] + iface[ifn][:arp].keys.each do |addr| + if addr.eql?(iaddr) + iface[ifn][:addresses][iface[ifn][:arp][iaddr]] = { "family" => "lladdr" } + break + end + end end end end - end -end -network[:interfaces] = iface + network[:interfaces] = iface -popen4("route -n get default") do |pid, stdin, stdout, stderr| - stdin.close - route_get = stdout.read - matches = /interface: (\S+)/.match(route_get) - if matches - Ohai::Log.debug("found gateway device: #{$1}") - network[:default_interface] = matches[1] - end - matches = /gateway: (\S+)/.match(route_get) - if matches - Ohai::Log.debug("found gateway: #{$1}") - network[:default_gateway] = matches[1] + popen4("route -n get default") do |pid, stdin, stdout, stderr| + stdin.close + route_get = stdout.read + matches = /interface: (\S+)/.match(route_get) + if matches + Ohai::Log.debug("found gateway device: #{$1}") + network[:default_interface] = matches[1] + end + matches = /gateway: (\S+)/.match(route_get) + if matches + Ohai::Log.debug("found gateway: #{$1}") + network[:default_gateway] = matches[1] + end + end end end - diff --git a/lib/ohai/plugins/solaris2/platform.rb b/lib/ohai/plugins/solaris2/platform.rb index 5f21e00a..062983ee 100644 --- a/lib/ohai/plugins/solaris2/platform.rb +++ b/lib/ohai/plugins/solaris2/platform.rb @@ -16,46 +16,50 @@ # limitations under the License. # -provides "platform", "platform_version", "platform_build" +Ohai.plugin(:Platform) do + provides "platform", "platform_version", "platform_build" -if File.exists?("/sbin/uname") - uname_exec = "/sbin/uname" -else - uname_exec = "uname" -end + collect_data do + if File.exists?("/sbin/uname") + uname_exec = "/sbin/uname" + else + uname_exec = "uname" + end -popen4("#{uname_exec} -X") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^Release =\s+(.+)$/ - platform_version $1 - when /^KernelID =\s+(.+)$/ - platform_build $1 + popen4("#{uname_exec} -X") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^Release =\s+(.+)$/ + platform_version $1 + when /^KernelID =\s+(.+)$/ + platform_build $1 + end + end end - end -end -File.open("/etc/release") do |file| - while line = file.gets - case line - when /^.*(SmartOS).*$/ - platform "smartos" - when /^\s*(OmniOS).*r(\d+).*$/ - platform "omnios" - platform_version $2 - when /^\s*(OpenIndiana).*oi_(\d+).*$/ - platform "openindiana" - platform_version $2 - when /^\s*(OpenSolaris).*snv_(\d+).*$/ - platform "opensolaris" - platform_version $2 - when /^\s*(Oracle Solaris) (\d+)\s.*$/ - platform "solaris2" - when /^\s*(Solaris)\s.*$/ - platform "solaris2" - when /^\s*(NexentaCore)\s.*$/ - platform "nexentacore" + File.open("/etc/release") do |file| + while line = file.gets + case line + when /^.*(SmartOS).*$/ + platform "smartos" + when /^\s*(OmniOS).*r(\d+).*$/ + platform "omnios" + platform_version $2 + when /^\s*(OpenIndiana).*oi_(\d+).*$/ + platform "openindiana" + platform_version $2 + when /^\s*(OpenSolaris).*snv_(\d+).*$/ + platform "opensolaris" + platform_version $2 + when /^\s*(Oracle Solaris) (\d+)\s.*$/ + platform "solaris2" + when /^\s*(Solaris)\s.*$/ + platform "solaris2" + when /^\s*(NexentaCore)\s.*$/ + platform "nexentacore" + end + end end end end diff --git a/lib/ohai/plugins/solaris2/ps.rb b/lib/ohai/plugins/solaris2/ps.rb index c1546a63..7fb57ddb 100644 --- a/lib/ohai/plugins/solaris2/ps.rb +++ b/lib/ohai/plugins/solaris2/ps.rb @@ -16,8 +16,12 @@ # limitations under the License. # -provides "command/ps" +Ohai.plugin(:Ps) do + provides "command/ps" -require_plugin 'command' + depends 'command' -command[:ps] = 'ps -ef'
\ No newline at end of file + collect_data do + command[:ps] = 'ps -ef' + end +end diff --git a/lib/ohai/plugins/solaris2/uptime.rb b/lib/ohai/plugins/solaris2/uptime.rb index 804e9da5..9f2be48b 100644 --- a/lib/ohai/plugins/solaris2/uptime.rb +++ b/lib/ohai/plugins/solaris2/uptime.rb @@ -19,18 +19,22 @@ require 'date' # It would be far better if we could include sys/uptime from sys-uptime RubyGem # It would also be good if we could pull idle time; how do we do this on Solaris? -provides "uptime", "uptime_seconds" +Ohai.plugin(:Uptime) do + provides "uptime", "uptime_seconds" -# Example output: -# $ who -b -# . system boot Jul 9 17:51 -popen4('who -b') do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - if line =~ /.* boot (.+)/ - uptime_seconds Time.now.to_i - DateTime.parse($1).strftime('%s').to_i - uptime seconds_to_human(uptime_seconds) - break + collect_data do + # Example output: + # $ who -b + # . system boot Jul 9 17:51 + popen4('who -b') do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + if line =~ /.* boot (.+)/ + uptime_seconds Time.now.to_i - DateTime.parse($1).strftime('%s').to_i + uptime seconds_to_human(uptime_seconds) + break + end + end end end end diff --git a/lib/ohai/plugins/solaris2/virtualization.rb b/lib/ohai/plugins/solaris2/virtualization.rb index fee8358d..111977e9 100644 --- a/lib/ohai/plugins/solaris2/virtualization.rb +++ b/lib/ohai/plugins/solaris2/virtualization.rb @@ -18,74 +18,78 @@ # limitations under the License. # -provides "virtualization" +Ohai.plugin(:Virtualization) do + provides "virtualization" -virtualization Mash.new + collect_data do + virtualization Mash.new -# Detect KVM/QEMU from cpuinfo, report as KVM -psrinfo_path="/usr/sbin/psrinfo" -if File.exists?(psrinfo_path) - popen4(psrinfo_path + " -pv") do |pid, stdin, stdout, stderr| - stdin.close - psr_info = stdout.read - if psr_info =~ /QEMU Virtual CPU/ - virtualization[:system] = "kvm" - virtualization[:role] = "guest" + # Detect KVM/QEMU from cpuinfo, report as KVM + psrinfo_path="/usr/sbin/psrinfo" + if File.exists?(psrinfo_path) + popen4(psrinfo_path + " -pv") do |pid, stdin, stdout, stderr| + stdin.close + psr_info = stdout.read + if psr_info =~ /QEMU Virtual CPU/ + virtualization[:system] = "kvm" + virtualization[:role] = "guest" + end + end end - end -end -# http://www.dmo.ca/blog/detecting-virtualization-on-linux -smbios_path="/usr/sbin/smbios" -if File.exists?(smbios_path) - popen4(smbios_path) do |pid, stdin, stdout, stderr| - stdin.close - dmi_info = stdout.read - case dmi_info - when /Manufacturer: Microsoft/ - if dmi_info =~ /Product: Virtual Machine/ - virtualization[:system] = "virtualpc" - virtualization[:role] = "guest" - end - when /Manufacturer: VMware/ - if dmi_info =~ /Product: VMware Virtual Platform/ - virtualization[:system] = "vmware" - virtualization[:role] = "guest" + # http://www.dmo.ca/blog/detecting-virtualization-on-linux + smbios_path="/usr/sbin/smbios" + if File.exists?(smbios_path) + popen4(smbios_path) do |pid, stdin, stdout, stderr| + stdin.close + dmi_info = stdout.read + case dmi_info + when /Manufacturer: Microsoft/ + if dmi_info =~ /Product: Virtual Machine/ + virtualization[:system] = "virtualpc" + virtualization[:role] = "guest" + end + when /Manufacturer: VMware/ + if dmi_info =~ /Product: VMware Virtual Platform/ + virtualization[:system] = "vmware" + virtualization[:role] = "guest" + end + else + nil + end end - else - nil end - end -end -if File.executable?('/usr/sbin/zoneadm') - zones = Mash.new + if File.executable?('/usr/sbin/zoneadm') + zones = Mash.new - popen4("zoneadm list -pc") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each{ |line| - info = line.chomp.split(/:/) - zones[info[1]] = { - 'id' => info[0], - 'state' => info[2], - 'root' => info[3], - 'uuid' => info[4], - 'brand' => info[5], - 'ip' => info[6], - } - } - - if (zones.length == 1) - first_zone = zones.keys[0] - unless( first_zone == 'global') - virtualization[:system] = 'zone' - virtualization[:role] = 'guest' - virtualization[:guest_uuid] = zones[first_zone]['uuid'] + popen4("zoneadm list -pc") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each{ |line| + info = line.chomp.split(/:/) + zones[info[1]] = { + 'id' => info[0], + 'state' => info[2], + 'root' => info[3], + 'uuid' => info[4], + 'brand' => info[5], + 'ip' => info[6], + } + } + + if (zones.length == 1) + first_zone = zones.keys[0] + unless( first_zone == 'global') + virtualization[:system] = 'zone' + virtualization[:role] = 'guest' + virtualization[:guest_uuid] = zones[first_zone]['uuid'] + end + elsif (zones.length > 1) + virtualization[:system] = 'zone' + virtualization[:role] = 'host' + virtualization[:guests] = zones + end end - elsif (zones.length > 1) - virtualization[:system] = 'zone' - virtualization[:role] = 'host' - virtualization[:guests] = zones end end end diff --git a/lib/ohai/plugins/solaris2/zpools.rb b/lib/ohai/plugins/solaris2/zpools.rb index 3e2420d8..7adc4f86 100644 --- a/lib/ohai/plugins/solaris2/zpools.rb +++ b/lib/ohai/plugins/solaris2/zpools.rb @@ -16,49 +16,53 @@ # limitations under the License. # -provides "zpools" +Ohai.plugin(:Zpools) do + provides "zpools" -pools = Mash.new + collect_data do + pools = Mash.new -# Grab ZFS zpools overall health and attributes -popen4("zpool list -H -o name,size,alloc,free,cap,dedup,health,version") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^([-_0-9A-Za-z]*)\s+([.0-9]+[MGTPE])\s+([.0-9]+[MGTPE])\s+([.0-9]+[MGTPE])\s+(\d+%)\s+([.0-9]+x)\s+([-_0-9A-Za-z]+)\s+(\d+)$/ - pools[$1] = Mash.new - pools[$1][:pool_size] = $2 - pools[$1][:pool_allocated] = $3 - pools[$1][:pool_free] = $4 - pools[$1][:capacity_used] = $5 - pools[$1][:dedup_factor] = $6 - pools[$1][:health] = $7 - pools[$1][:zpool_version] = $8 + # Grab ZFS zpools overall health and attributes + popen4("zpool list -H -o name,size,alloc,free,cap,dedup,health,version") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^([-_0-9A-Za-z]*)\s+([.0-9]+[MGTPE])\s+([.0-9]+[MGTPE])\s+([.0-9]+[MGTPE])\s+(\d+%)\s+([.0-9]+x)\s+([-_0-9A-Za-z]+)\s+(\d+)$/ + pools[$1] = Mash.new + pools[$1][:pool_size] = $2 + pools[$1][:pool_allocated] = $3 + pools[$1][:pool_free] = $4 + pools[$1][:capacity_used] = $5 + pools[$1][:dedup_factor] = $6 + pools[$1][:health] = $7 + pools[$1][:zpool_version] = $8 + end + end end - end -end -# Grab individual health for devices in the zpools -for pool in pools.keys - pools[pool][:devices] = Mash.new - # Run "zpool status" as non-root user (adm) so that - # the command won't try to open() each device which can - # hang the command if any of the disks are bad. - popen4("su adm -c \"zpool status #{pool}\"") do |pid, stdin, stdout, stderr| - stdin.close - stdout.each do |line| - case line - when /^\s+(c[-_a-zA-Z0-9]+)\s+([-_a-zA-Z0-9]+)\s+(\d+)\s+(\d+)\s+(\d+)$/ - pools[pool][:devices][$1] = Mash.new - pools[pool][:devices][$1][:state] = $2 - pools[pool][:devices][$1][:errors] = Mash.new - pools[pool][:devices][$1][:errors][:read] = $3 - pools[pool][:devices][$1][:errors][:write] = $4 - pools[pool][:devices][$1][:errors][:checksum] = $5 + # Grab individual health for devices in the zpools + for pool in pools.keys + pools[pool][:devices] = Mash.new + # Run "zpool status" as non-root user (adm) so that + # the command won't try to open() each device which can + # hang the command if any of the disks are bad. + popen4("su adm -c \"zpool status #{pool}\"") do |pid, stdin, stdout, stderr| + stdin.close + stdout.each do |line| + case line + when /^\s+(c[-_a-zA-Z0-9]+)\s+([-_a-zA-Z0-9]+)\s+(\d+)\s+(\d+)\s+(\d+)$/ + pools[pool][:devices][$1] = Mash.new + pools[pool][:devices][$1][:state] = $2 + pools[pool][:devices][$1][:errors] = Mash.new + pools[pool][:devices][$1][:errors][:read] = $3 + pools[pool][:devices][$1][:errors][:write] = $4 + pools[pool][:devices][$1][:errors][:checksum] = $5 + end + end end end + + # Set the zpools data + zpools pools end end - -# Set the zpools data -zpools pools
\ No newline at end of file diff --git a/lib/ohai/plugins/ssh_host_key.rb b/lib/ohai/plugins/ssh_host_key.rb index 6fb7f57a..69e4edc2 100644 --- a/lib/ohai/plugins/ssh_host_key.rb +++ b/lib/ohai/plugins/ssh_host_key.rb @@ -16,58 +16,62 @@ # limitations under the License. # -provides "keys/ssh" -require_plugin "keys" +Ohai.plugin(:SshHostKey) do + provides "keys/ssh" + depends "keys" -keys[:ssh] = Mash.new - -def extract_keytype?(content) - case content[0] - when "ssh-dss" - [ "dsa", nil ] - when "ssh-rsa" - [ "rsa", nil ] - when /^ecdsa/ - [ "ecdsa", content[0] ] - else - [ nil, nil ] + def extract_keytype?(content) + case content[0] + when "ssh-dss" + [ "dsa", nil ] + when "ssh-rsa" + [ "rsa", nil ] + when /^ecdsa/ + [ "ecdsa", content[0] ] + else + [ nil, nil ] + end end -end -sshd_config = if File.exists?("/etc/ssh/sshd_config") - "/etc/ssh/sshd_config" - elsif File.exists?("/etc/sshd_config") - # Darwin - "/etc/sshd_config" - else - Ohai::Log.debug("Failed to find sshd configuration file") - nil - end + collect_data do + keys[:ssh] = Mash.new -if sshd_config - File.open(sshd_config) do |conf| - conf.each_line do |line| - if line.match(/^hostkey\s/i) - pub_file = "#{line.split[1]}.pub" - content = IO.read(pub_file).split - key_type, key_subtype = extract_keytype?(content) - keys[:ssh]["host_#{key_type}_public"] = content[1] unless key_type.nil? - keys[:ssh]["host_#{key_type}_type"] = key_subtype unless key_subtype.nil? + sshd_config = if File.exists?("/etc/ssh/sshd_config") + "/etc/ssh/sshd_config" + elsif File.exists?("/etc/sshd_config") + # Darwin + "/etc/sshd_config" + else + Ohai::Log.debug("Failed to find sshd configuration file") + nil + end + + if sshd_config + File.open(sshd_config) do |conf| + conf.each_line do |line| + if line.match(/^hostkey\s/i) + pub_file = "#{line.split[1]}.pub" + content = IO.read(pub_file).split + key_type, key_subtype = extract_keytype?(content) + keys[:ssh]["host_#{key_type}_public"] = content[1] unless key_type.nil? + keys[:ssh]["host_#{key_type}_type"] = key_subtype unless key_subtype.nil? + end + end end end - end -end -if keys[:ssh][:host_dsa_public].nil? && File.exists?("/etc/ssh/ssh_host_dsa_key.pub") - keys[:ssh][:host_dsa_public] = IO.read("/etc/ssh/ssh_host_dsa_key.pub").split[1] -end + if keys[:ssh][:host_dsa_public].nil? && File.exists?("/etc/ssh/ssh_host_dsa_key.pub") + keys[:ssh][:host_dsa_public] = IO.read("/etc/ssh/ssh_host_dsa_key.pub").split[1] + end -if keys[:ssh][:host_rsa_public].nil? && File.exists?("/etc/ssh/ssh_host_rsa_key.pub") - keys[:ssh][:host_rsa_public] = IO.read("/etc/ssh/ssh_host_rsa_key.pub").split[1] -end + if keys[:ssh][:host_rsa_public].nil? && File.exists?("/etc/ssh/ssh_host_rsa_key.pub") + keys[:ssh][:host_rsa_public] = IO.read("/etc/ssh/ssh_host_rsa_key.pub").split[1] + end -if keys[:ssh][:host_ecdsa_public].nil? && File.exists?("/etc/ssh/ssh_host_ecdsa_key.pub") - content = IO.read("/etc/ssh/ssh_host_ecdsa_key.pub") - keys[:ssh][:host_ecdsa_public] = content.split[1] - keys[:ssh][:host_ecdsa_type] = content.split[0] + if keys[:ssh][:host_ecdsa_public].nil? && File.exists?("/etc/ssh/ssh_host_ecdsa_key.pub") + content = IO.read("/etc/ssh/ssh_host_ecdsa_key.pub") + keys[:ssh][:host_ecdsa_public] = content.split[1] + keys[:ssh][:host_ecdsa_type] = content.split[0] + end + end end diff --git a/lib/ohai/plugins/virtualization.rb b/lib/ohai/plugins/virtualization.rb index a1b62737..052e542c 100644 --- a/lib/ohai/plugins/virtualization.rb +++ b/lib/ohai/plugins/virtualization.rb @@ -16,71 +16,75 @@ # limitations under the License. # -provides "virtualization" +Ohai.plugin(:Virtualization) do + provides "virtualization" -require_plugin "#{os}::virtualization" + depends_os "virtualization" -unless virtualization.nil? || !(virtualization[:role].eql?("host")) - begin - require 'libvirt' - require 'hpricot' + collect_data do + unless virtualization.nil? || !(virtualization[:role].eql?("host")) + begin + require 'libvirt' + require 'hpricot' - emu = (virtualization[:system].eql?('kvm') ? 'qemu' : virtualization[:system]) - virtualization[:libvirt_version] = Libvirt::version(emu)[0].to_s + emu = (virtualization[:system].eql?('kvm') ? 'qemu' : virtualization[:system]) + virtualization[:libvirt_version] = Libvirt::version(emu)[0].to_s - virtconn = Libvirt::open_read_only("#{emu}:///system") + virtconn = Libvirt::open_read_only("#{emu}:///system") - virtualization[:uri] = virtconn.uri - virtualization[:capabilities] = Mash.new - virtualization[:capabilities][:xml_desc] = (virtconn.capabilities.split("\n").collect {|line| line.strip}).join - #xdoc = Hpricot virtualization[:capabilities][:xml_desc] - - virtualization[:nodeinfo] = Mash.new - ni = virtconn.node_get_info - ['cores','cpus','memory','mhz','model','nodes','sockets','threads'].each {|a| virtualization[:nodeinfo][a] = ni.send(a)} + virtualization[:uri] = virtconn.uri + virtualization[:capabilities] = Mash.new + virtualization[:capabilities][:xml_desc] = (virtconn.capabilities.split("\n").collect {|line| line.strip}).join + #xdoc = Hpricot virtualization[:capabilities][:xml_desc] + + virtualization[:nodeinfo] = Mash.new + ni = virtconn.node_get_info + ['cores','cpus','memory','mhz','model','nodes','sockets','threads'].each {|a| virtualization[:nodeinfo][a] = ni.send(a)} - virtualization[:domains] = Mash.new - virtconn.list_domains.each do |d| - dv = virtconn.lookup_domain_by_id d - virtualization[:domains][dv.name] = Mash.new - virtualization[:domains][dv.name][:id] = d - virtualization[:domains][dv.name][:xml_desc] = (dv.xml_desc.split("\n").collect {|line| line.strip}).join - ['os_type','uuid'].each {|a| virtualization[:domains][dv.name][a] = dv.send(a)} - ['cpu_time','max_mem','memory','nr_virt_cpu','state'].each {|a| virtualization[:domains][dv.name][a] = dv.info.send(a)} - #xdoc = Hpricot virtualization[:domains][dv.name][:xml_desc] - - end + virtualization[:domains] = Mash.new + virtconn.list_domains.each do |d| + dv = virtconn.lookup_domain_by_id d + virtualization[:domains][dv.name] = Mash.new + virtualization[:domains][dv.name][:id] = d + virtualization[:domains][dv.name][:xml_desc] = (dv.xml_desc.split("\n").collect {|line| line.strip}).join + ['os_type','uuid'].each {|a| virtualization[:domains][dv.name][a] = dv.send(a)} + ['cpu_time','max_mem','memory','nr_virt_cpu','state'].each {|a| virtualization[:domains][dv.name][a] = dv.info.send(a)} + #xdoc = Hpricot virtualization[:domains][dv.name][:xml_desc] + + end - virtualization[:networks] = Mash.new - virtconn.list_networks.each do |n| - nv = virtconn.lookup_network_by_name n - virtualization[:networks][n] = Mash.new - virtualization[:networks][n][:xml_desc] = (nv.xml_desc.split("\n").collect {|line| line.strip}).join - ['bridge_name','uuid'].each {|a| virtualization[:networks][n][a] = nv.send(a)} - #xdoc = Hpricot virtualization[:networks][n][:xml_desc] - - end + virtualization[:networks] = Mash.new + virtconn.list_networks.each do |n| + nv = virtconn.lookup_network_by_name n + virtualization[:networks][n] = Mash.new + virtualization[:networks][n][:xml_desc] = (nv.xml_desc.split("\n").collect {|line| line.strip}).join + ['bridge_name','uuid'].each {|a| virtualization[:networks][n][a] = nv.send(a)} + #xdoc = Hpricot virtualization[:networks][n][:xml_desc] + + end - virtualization[:storage] = Mash.new - virtconn.list_storage_pools.each do |pool| - sp = virtconn.lookup_storage_pool_by_name pool - virtualization[:storage][pool] = Mash.new - virtualization[:storage][pool][:xml_desc] = (sp.xml_desc.split("\n").collect {|line| line.strip}).join - ['autostart','uuid'].each {|a| virtualization[:storage][pool][a] = sp.send(a)} - ['allocation','available','capacity','state'].each {|a| virtualization[:storage][pool][a] = sp.info.send(a)} - #xdoc = Hpricot virtualization[:storage][pool][:xml_desc] + virtualization[:storage] = Mash.new + virtconn.list_storage_pools.each do |pool| + sp = virtconn.lookup_storage_pool_by_name pool + virtualization[:storage][pool] = Mash.new + virtualization[:storage][pool][:xml_desc] = (sp.xml_desc.split("\n").collect {|line| line.strip}).join + ['autostart','uuid'].each {|a| virtualization[:storage][pool][a] = sp.send(a)} + ['allocation','available','capacity','state'].each {|a| virtualization[:storage][pool][a] = sp.info.send(a)} + #xdoc = Hpricot virtualization[:storage][pool][:xml_desc] - virtualization[:storage][pool][:volumes] = Mash.new - sp.list_volumes.each do |v| - virtualization[:storage][pool][:volumes][v] = Mash.new - sv = sp.lookup_volume_by_name v - ['key','name','path'].each {|a| virtualization[:storage][pool][:volumes][v][a] = sv.send(a)} - ['allocation','capacity','type'].each {|a| virtualization[:storage][pool][:volumes][v][a] = sv.info.send(a)} + virtualization[:storage][pool][:volumes] = Mash.new + sp.list_volumes.each do |v| + virtualization[:storage][pool][:volumes][v] = Mash.new + sv = sp.lookup_volume_by_name v + ['key','name','path'].each {|a| virtualization[:storage][pool][:volumes][v][a] = sv.send(a)} + ['allocation','capacity','type'].each {|a| virtualization[:storage][pool][:volumes][v][a] = sv.info.send(a)} + end + end + + virtconn.close + rescue LoadError => e + Ohai::Log.debug("Can't load gem: #{e}. virtualization plugin is disabled.") end end - - virtconn.close - rescue LoadError => e - Ohai::Log.debug("Can't load gem: #{e}. virtualization plugin is disabled.") end end diff --git a/lib/ohai/plugins/windows/cpu.rb b/lib/ohai/plugins/windows/cpu.rb index 4fb1f4fe..17b7879a 100644 --- a/lib/ohai/plugins/windows/cpu.rb +++ b/lib/ohai/plugins/windows/cpu.rb @@ -18,47 +18,51 @@ require 'ruby-wmi' -provides "cpu" +Ohai.plugin(:Cpu) do + provides "cpu" -cpuinfo = Mash.new -cpu_number = 0 -index = 0 + collect_data do + cpuinfo = Mash.new + cpu_number = 0 + index = 0 -WMI::Win32_Processor.find(:all).each do |processor| - # - # On Windows Server 2003 R2 (i.e. 5.2.*), numberofcores property - # doesn't exist on the Win32_Processor class unless the user has - # patched their system with: - # http://support.microsoft.com/kb/932370 - # - # We're returning nil for cpu["cores"] and cpu["count"] - # when we don't see numberofcores property - # + WMI::Win32_Processor.find(:all).each do |processor| + # + # On Windows Server 2003 R2 (i.e. 5.2.*), numberofcores property + # doesn't exist on the Win32_Processor class unless the user has + # patched their system with: + # http://support.microsoft.com/kb/932370 + # + # We're returning nil for cpu["cores"] and cpu["count"] + # when we don't see numberofcores property + # - number_of_cores = nil - begin - number_of_cores = processor.numberofcores - cpu_number += number_of_cores - rescue NoMethodError => e - Ohai::Log.info("Can not find numberofcores property on Win32_Processor. Consider applying this patch: http://support.microsoft.com/kb/932370") - end + number_of_cores = nil + begin + number_of_cores = processor.numberofcores + cpu_number += number_of_cores + rescue NoMethodError => e + Ohai::Log.info("Can not find numberofcores property on Win32_Processor. Consider applying this patch: http://support.microsoft.com/kb/932370") + end - current_cpu = index.to_s - index += 1 - cpuinfo[current_cpu] = Mash.new - cpuinfo[current_cpu]["vendor_id"] = processor.manufacturer - cpuinfo[current_cpu]["family"] = processor.family.to_s - cpuinfo[current_cpu]["model"] = processor.revision.to_s - cpuinfo[current_cpu]["stepping"] = processor.stepping - cpuinfo[current_cpu]["physical_id"] = processor.deviceid - #cpuinfo[current_cpu]["core_id"] = XXX - cpuinfo[current_cpu]["cores"] = number_of_cores - cpuinfo[current_cpu]["model_name"] = processor.description - cpuinfo[current_cpu]["mhz"] = processor.maxclockspeed.to_s - cpuinfo[current_cpu]["cache_size"] = "#{processor.l2cachesize} KB" - #cpuinfo[current_cpu]["flags"] = XXX -end + current_cpu = index.to_s + index += 1 + cpuinfo[current_cpu] = Mash.new + cpuinfo[current_cpu]["vendor_id"] = processor.manufacturer + cpuinfo[current_cpu]["family"] = processor.family.to_s + cpuinfo[current_cpu]["model"] = processor.revision.to_s + cpuinfo[current_cpu]["stepping"] = processor.stepping + cpuinfo[current_cpu]["physical_id"] = processor.deviceid + #cpuinfo[current_cpu]["core_id"] = XXX + cpuinfo[current_cpu]["cores"] = number_of_cores + cpuinfo[current_cpu]["model_name"] = processor.description + cpuinfo[current_cpu]["mhz"] = processor.maxclockspeed.to_s + cpuinfo[current_cpu]["cache_size"] = "#{processor.l2cachesize} KB" + #cpuinfo[current_cpu]["flags"] = XXX + end -cpu cpuinfo -cpu[:total] = (cpu_number == 0) ? nil : cpu_number -cpu[:real] = index + cpu cpuinfo + cpu[:total] = (cpu_number == 0) ? nil : cpu_number + cpu[:real] = index + end +end diff --git a/lib/ohai/plugins/windows/filesystem.rb b/lib/ohai/plugins/windows/filesystem.rb index efec6f0c..f2077bd8 100644 --- a/lib/ohai/plugins/windows/filesystem.rb +++ b/lib/ohai/plugins/windows/filesystem.rb @@ -18,27 +18,33 @@ require 'ruby-wmi' -fs = Mash.new -ld_info = Mash.new +Ohai.plugin(:Filesystem) do + provides "filesystem" -# Grab filesystem data from WMI -# Note: we should really be parsing Win32_Volume and Win32_Mapped drive -disks = WMI::Win32_LogicalDisk.find(:all) -disks.each do |disk| - filesystem = disk.DeviceID - fs[filesystem] = Mash.new - ld_info[filesystem] = Mash.new - disk.properties_.each do |p| - ld_info[filesystem][p.name.wmi_underscore.to_sym] = disk.send(p.name) + collect_data do + fs = Mash.new + ld_info = Mash.new + + # Grab filesystem data from WMI + # Note: we should really be parsing Win32_Volume and Win32_Mapped drive + disks = WMI::Win32_LogicalDisk.find(:all) + disks.each do |disk| + filesystem = disk.DeviceID + fs[filesystem] = Mash.new + ld_info[filesystem] = Mash.new + disk.properties_.each do |p| + ld_info[filesystem][p.name.wmi_underscore.to_sym] = disk.send(p.name) + end + fs[filesystem][:kb_size] = ld_info[filesystem][:size].to_i / 1000 + fs[filesystem][:kb_available] = ld_info[filesystem][:free_space].to_i / 1000 + fs[filesystem][:kb_used] = fs[filesystem][:kb_size].to_i - fs[filesystem][:kb_available].to_i + fs[filesystem][:percent_used] = (fs[filesystem][:kb_size].to_i != 0 ? fs[filesystem][:kb_used].to_i * 100 / fs[filesystem][:kb_size].to_i : 0) + fs[filesystem][:mount] = ld_info[filesystem][:name] + fs[filesystem][:fs_type] = ld_info[filesystem][:file_system].downcase unless ld_info[filesystem][:file_system] == nil + fs[filesystem][:volume_name] = ld_info[filesystem][:volume_name] end - fs[filesystem][:kb_size] = ld_info[filesystem][:size].to_i / 1000 - fs[filesystem][:kb_available] = ld_info[filesystem][:free_space].to_i / 1000 - fs[filesystem][:kb_used] = fs[filesystem][:kb_size].to_i - fs[filesystem][:kb_available].to_i - fs[filesystem][:percent_used] = (fs[filesystem][:kb_size].to_i != 0 ? fs[filesystem][:kb_used].to_i * 100 / fs[filesystem][:kb_size].to_i : 0) - fs[filesystem][:mount] = ld_info[filesystem][:name] - fs[filesystem][:fs_type] = ld_info[filesystem][:file_system].downcase unless ld_info[filesystem][:file_system] == nil - fs[filesystem][:volume_name] = ld_info[filesystem][:volume_name] -end -# Set the filesystem data -filesystem fs + # Set the filesystem data + filesystem fs + end +end diff --git a/lib/ohai/plugins/windows/hostname.rb b/lib/ohai/plugins/windows/hostname.rb index 66a8cdf6..20d9a781 100644 --- a/lib/ohai/plugins/windows/hostname.rb +++ b/lib/ohai/plugins/windows/hostname.rb @@ -19,15 +19,21 @@ require 'ruby-wmi' require 'socket' -host = WMI::Win32_ComputerSystem.find(:first) -hostname "#{host.Name}" +Ohai.plugin(:Hostname) do + provides "hostname" + provides "fqdn" -info = Socket.gethostbyname(Socket.gethostname) -if info.first =~ /.+?\.(.*)/ - fqdn info.first -else - #host is not in dns. optionally use: - #C:\WINDOWS\system32\drivers\etc\hosts - fqdn Socket.gethostbyaddr(info.last).first -end + collect_data do + host = WMI::Win32_ComputerSystem.find(:first) + hostname "#{host.Name}" + info = Socket.gethostbyname(Socket.gethostname) + if info.first =~ /.+?\.(.*)/ + fqdn info.first + else + #host is not in dns. optionally use: + #C:\WINDOWS\system32\drivers\etc\hosts + fqdn Socket.gethostbyaddr(info.last).first + end + end +end diff --git a/lib/ohai/plugins/windows/kernel.rb b/lib/ohai/plugins/windows/kernel.rb index ad45f4b2..d41789ea 100644 --- a/lib/ohai/plugins/windows/kernel.rb +++ b/lib/ohai/plugins/windows/kernel.rb @@ -18,41 +18,47 @@ require 'ruby-wmi' -WIN32OLE.codepage = WIN32OLE::CP_UTF8 +Ohai.plugin(:Kernel) do + provides "kernel" -def machine_lookup(sys_type) - return "i386" if sys_type.eql?("X86-based PC") - return "x86_64" if sys_type.eql?("x64-based PC") - sys_type -end + WIN32OLE.codepage = WIN32OLE::CP_UTF8 -def os_lookup(sys_type) - return "Unknown" if sys_type.to_s.eql?("0") - return "Other" if sys_type.to_s.eql?("1") - return "MSDOS" if sys_type.to_s.eql?("14") - return "WIN3x" if sys_type.to_s.eql?("15") - return "WIN95" if sys_type.to_s.eql?("16") - return "WIN98" if sys_type.to_s.eql?("17") - return "WINNT" if sys_type.to_s.eql?("18") - return "WINCE" if sys_type.to_s.eql?("19") - return nil -end + def machine_lookup(sys_type) + return "i386" if sys_type.eql?("X86-based PC") + return "x86_64" if sys_type.eql?("x64-based PC") + sys_type + end -host = WMI::Win32_OperatingSystem.find(:first) -kernel[:os_info] = Mash.new -host.properties_.each do |p| - kernel[:os_info][p.name.wmi_underscore.to_sym] = host.send(p.name) -end + def os_lookup(sys_type) + return "Unknown" if sys_type.to_s.eql?("0") + return "Other" if sys_type.to_s.eql?("1") + return "MSDOS" if sys_type.to_s.eql?("14") + return "WIN3x" if sys_type.to_s.eql?("15") + return "WIN95" if sys_type.to_s.eql?("16") + return "WIN98" if sys_type.to_s.eql?("17") + return "WINNT" if sys_type.to_s.eql?("18") + return "WINCE" if sys_type.to_s.eql?("19") + return nil + end -kernel[:name] = "#{kernel[:os_info][:caption]}" -kernel[:release] = "#{kernel[:os_info][:version]}" -kernel[:version] = "#{kernel[:os_info][:version]} #{kernel[:os_info][:csd_version]} Build #{kernel[:os_info][:build_number]}" -kernel[:os] = os_lookup(kernel[:os_info][:os_type]) || languages[:ruby][:host_os] + collect_data do + host = WMI::Win32_OperatingSystem.find(:first) + kernel[:os_info] = Mash.new + host.properties_.each do |p| + kernel[:os_info][p.name.wmi_underscore.to_sym] = host.send(p.name) + end -host = WMI::Win32_ComputerSystem.find(:first) -kernel[:cs_info] = Mash.new -host.properties_.each do |p| - kernel[:cs_info][p.name.wmi_underscore.to_sym] = host.send(p.name) -end + kernel[:name] = "#{kernel[:os_info][:caption]}" + kernel[:release] = "#{kernel[:os_info][:version]}" + kernel[:version] = "#{kernel[:os_info][:version]} #{kernel[:os_info][:csd_version]} Build #{kernel[:os_info][:build_number]}" + kernel[:os] = os_lookup(kernel[:os_info][:os_type]) || languages[:ruby][:host_os] + + host = WMI::Win32_ComputerSystem.find(:first) + kernel[:cs_info] = Mash.new + host.properties_.each do |p| + kernel[:cs_info][p.name.wmi_underscore.to_sym] = host.send(p.name) + end -kernel[:machine] = machine_lookup("#{kernel[:cs_info][:system_type]}") + kernel[:machine] = machine_lookup("#{kernel[:cs_info][:system_type]}") + end +end diff --git a/lib/ohai/plugins/windows/kernel_devices.rb b/lib/ohai/plugins/windows/kernel_devices.rb index 69da6c39..2284ff4f 100644 --- a/lib/ohai/plugins/windows/kernel_devices.rb +++ b/lib/ohai/plugins/windows/kernel_devices.rb @@ -17,23 +17,29 @@ # require 'ruby-wmi' -WIN32OLE.codepage = WIN32OLE::CP_UTF8 +Ohai.plugin(:KernelDevices) do + provides "kernel" + + WIN32OLE.codepage = WIN32OLE::CP_UTF8 -kext = Mash.new -pnp_drivers = Mash.new + collect_data do + kext = Mash.new + pnp_drivers = Mash.new -drivers = WMI::Win32_PnPSignedDriver.find(:all) -drivers.each do |driver| - pnp_drivers[driver.DeviceID] = Mash.new - driver.properties_.each do |p| - pnp_drivers[driver.DeviceID][p.name.wmi_underscore.to_sym] = driver.send(p.name) + drivers = WMI::Win32_PnPSignedDriver.find(:all) + drivers.each do |driver| + pnp_drivers[driver.DeviceID] = Mash.new + driver.properties_.each do |p| + pnp_drivers[driver.DeviceID][p.name.wmi_underscore.to_sym] = driver.send(p.name) + end + if driver.DeviceName + kext[driver.DeviceName] = pnp_drivers[driver.DeviceID] + kext[driver.DeviceName][:version] = pnp_drivers[driver.DeviceID][:driver_version] + kext[driver.DeviceName][:date] = pnp_drivers[driver.DeviceID][:driver_date] ? pnp_drivers[driver.DeviceID][:driver_date].to_s[0..7] : nil + end + end + + kernel[:pnp_drivers] = pnp_drivers + kernel[:modules] = kext end - if driver.DeviceName - kext[driver.DeviceName] = pnp_drivers[driver.DeviceID] - kext[driver.DeviceName][:version] = pnp_drivers[driver.DeviceID][:driver_version] - kext[driver.DeviceName][:date] = pnp_drivers[driver.DeviceID][:driver_date] ? pnp_drivers[driver.DeviceID][:driver_date].to_s[0..7] : nil - end end - -kernel[:pnp_drivers] = pnp_drivers -kernel[:modules] = kext diff --git a/lib/ohai/plugins/windows/network.rb b/lib/ohai/plugins/windows/network.rb index bf25c2f0..3150aa4a 100644 --- a/lib/ohai/plugins/windows/network.rb +++ b/lib/ohai/plugins/windows/network.rb @@ -16,98 +16,102 @@ # limitations under the License. # -provides "network" - require 'ruby-wmi' -def encaps_lookup(encap) - return "Ethernet" if encap.eql?("Ethernet 802.3") - encap -end +Ohai.plugin(:Network) do + provides "network" -iface = Mash.new -iface_config = Mash.new -iface_instance = Mash.new + def encaps_lookup(encap) + return "Ethernet" if encap.eql?("Ethernet 802.3") + encap + end -# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394217%28v=vs.85%29.aspx -adapters = WMI::Win32_NetworkAdapterConfiguration.find(:all) -adapters.each do |adapter| - i = adapter.Index - iface_config[i] = Mash.new - adapter.properties_.each do |p| - iface_config[i][p.name.wmi_underscore.to_sym] = adapter.invoke(p.name) + collect_data do + iface = Mash.new + iface_config = Mash.new + iface_instance = Mash.new + + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394217%28v=vs.85%29.aspx + adapters = WMI::Win32_NetworkAdapterConfiguration.find(:all) + adapters.each do |adapter| + i = adapter.Index + iface_config[i] = Mash.new + adapter.properties_.each do |p| + iface_config[i][p.name.wmi_underscore.to_sym] = adapter.invoke(p.name) + end end -end -# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216(v=vs.85).aspx -adapters = WMI::Win32_NetworkAdapter.find(:all) -adapters.each do |adapter| - i = adapter.Index - iface_instance[i] = Mash.new - adapter.properties_.each do |p| - iface_instance[i][p.name.wmi_underscore.to_sym] = adapter.invoke(p.name) + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216(v=vs.85).aspx + adapters = WMI::Win32_NetworkAdapter.find(:all) + adapters.each do |adapter| + i = adapter.Index + iface_instance[i] = Mash.new + adapter.properties_.each do |p| + iface_instance[i][p.name.wmi_underscore.to_sym] = adapter.invoke(p.name) + end end -end -iface_instance.keys.each do |i| - if iface_config[i][:ip_enabled] and iface_instance[i][:net_connection_id] - cint = sprintf("0x%x", iface_instance[i][:interface_index] ? iface_instance[i][:interface_index] : iface_instance[i][:index] ).downcase - iface[cint] = Mash.new - iface[cint][:configuration] = iface_config[i] - iface[cint][:instance] = iface_instance[i] + iface_instance.keys.each do |i| + if iface_config[i][:ip_enabled] and iface_instance[i][:net_connection_id] + cint = sprintf("0x%x", iface_instance[i][:interface_index] ? iface_instance[i][:interface_index] : iface_instance[i][:index] ).downcase + iface[cint] = Mash.new + iface[cint][:configuration] = iface_config[i] + iface[cint][:instance] = iface_instance[i] - iface[cint][:counters] = Mash.new - iface[cint][:addresses] = Mash.new - iface[cint][:configuration][:ip_address].each_index do |i| - ip = iface[cint][:configuration][:ip_address][i] - _ip = IPAddress("#{ip}/#{iface[cint][:configuration][:ip_subnet][i]}") - iface[cint][:addresses][ip] = Mash.new( - :prefixlen => _ip.prefix - ) - if _ip.ipv6? - # inet6 address - iface[cint][:addresses][ip][:family] = "inet6" - iface[cint][:addresses][ip][:scope] = "Link" if ip =~ /^fe80/i - else - # should be an inet4 address - iface[cint][:addresses][ip][:netmask] = _ip.netmask.to_s - if iface[cint][:configuration][:ip_use_zero_broadcast] - iface[cint][:addresses][ip][:broadcast] = _ip.network.to_s - else - iface[cint][:addresses][ip][:broadcast] = _ip.broadcast.to_s + iface[cint][:counters] = Mash.new + iface[cint][:addresses] = Mash.new + iface[cint][:configuration][:ip_address].each_index do |i| + ip = iface[cint][:configuration][:ip_address][i] + _ip = IPAddress("#{ip}/#{iface[cint][:configuration][:ip_subnet][i]}") + iface[cint][:addresses][ip] = Mash.new( + :prefixlen => _ip.prefix + ) + if _ip.ipv6? + # inet6 address + iface[cint][:addresses][ip][:family] = "inet6" + iface[cint][:addresses][ip][:scope] = "Link" if ip =~ /^fe80/i + else + # should be an inet4 address + iface[cint][:addresses][ip][:netmask] = _ip.netmask.to_s + if iface[cint][:configuration][:ip_use_zero_broadcast] + iface[cint][:addresses][ip][:broadcast] = _ip.network.to_s + else + iface[cint][:addresses][ip][:broadcast] = _ip.broadcast.to_s + end + iface[cint][:addresses][ip][:family] = "inet" + end + end + # Apparently you can have more than one mac_address? Odd. + [iface[cint][:configuration][:mac_address]].flatten.each do |mac_addr| + iface[cint][:addresses][mac_addr] = { + "family" => "lladdr" + } + end + iface[cint][:mtu] = iface[cint][:configuration][:mtu] + iface[cint][:type] = iface[cint][:instance][:adapter_type] + iface[cint][:arp] = {} + iface[cint][:encapsulation] = encaps_lookup(iface[cint][:instance][:adapter_type]) + if iface[cint][:configuration][:default_ip_gateway] != nil and iface[cint][:configuration][:default_ip_gateway].size > 0 + network[:default_gateway] = iface[cint][:configuration][:default_ip_gateway].first + network[:default_interface] = cint end - iface[cint][:addresses][ip][:family] = "inet" end end - # Apparently you can have more than one mac_address? Odd. - [iface[cint][:configuration][:mac_address]].flatten.each do |mac_addr| - iface[cint][:addresses][mac_addr] = { - "family" => "lladdr" - } - end - iface[cint][:mtu] = iface[cint][:configuration][:mtu] - iface[cint][:type] = iface[cint][:instance][:adapter_type] - iface[cint][:arp] = {} - iface[cint][:encapsulation] = encaps_lookup(iface[cint][:instance][:adapter_type]) - if iface[cint][:configuration][:default_ip_gateway] != nil and iface[cint][:configuration][:default_ip_gateway].size > 0 - network[:default_gateway] = iface[cint][:configuration][:default_ip_gateway].first - network[:default_interface] = cint - end - end -end -cint=nil -status, stdout, stderr = run_command(:command => "arp -a") -if status == 0 - stdout.split("\n").each do |line| - if line =~ /^Interface:\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+[-]+\s+(0x\S+)/ - cint = $2.downcase - end - next unless iface[cint] - if line =~ /^\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+([a-fA-F0-9\:-]+)/ - iface[cint][:arp][$1] = $2.gsub("-",":").downcase + cint=nil + status, stdout, stderr = run_command(:command => "arp -a") + if status == 0 + stdout.split("\n").each do |line| + if line =~ /^Interface:\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+[-]+\s+(0x\S+)/ + cint = $2.downcase + end + next unless iface[cint] + if line =~ /^\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+([a-fA-F0-9\:-]+)/ + iface[cint][:arp][$1] = $2.gsub("-",":").downcase + end + end end + + network["interfaces"] = iface end end - -network["interfaces"] = iface diff --git a/lib/ohai/plugins/windows/platform.rb b/lib/ohai/plugins/windows/platform.rb index c0947c25..15520cea 100644 --- a/lib/ohai/plugins/windows/platform.rb +++ b/lib/ohai/plugins/windows/platform.rb @@ -21,7 +21,14 @@ # Windows_NT kernel, so we herby decree that "windows" will refer to all # platforms built upon the Windows_NT kernel and have access to win32 or win64 # subsystems. -platform os -platform_version kernel['release'] -platform_family "windows" + +Ohai.plugin(:Platform) do + provides "platform" + + collect_data do + platform os + platform_version kernel['release'] + platform_family "windows" + end +end diff --git a/lib/ohai/plugins/windows/uptime.rb b/lib/ohai/plugins/windows/uptime.rb index 2dcc0e48..8187b1b7 100644 --- a/lib/ohai/plugins/windows/uptime.rb +++ b/lib/ohai/plugins/windows/uptime.rb @@ -17,7 +17,11 @@ # require 'ruby-wmi' -provides "uptime", "uptime_seconds" +Ohai.plugin(:Uptime) do + provides "uptime", "uptime_seconds" -uptime_seconds ::WMI::Win32_PerfFormattedData_PerfOS_System.find(:first).SystemUpTime.to_i -uptime seconds_to_human(uptime_seconds) + collect_data do + uptime_seconds ::WMI::Win32_PerfFormattedData_PerfOS_System.find(:first).SystemUpTime.to_i + uptime seconds_to_human(uptime_seconds) + end +end diff --git a/lib/ohai/system.rb b/lib/ohai/system.rb index c7b706ff..00a7e61d 100644 --- a/lib/ohai/system.rb +++ b/lib/ohai/system.rb @@ -16,9 +16,10 @@ # limitations under the License. # -require 'ohai/mash' require 'ohai/loader' require 'ohai/log' +require 'ohai/mash' +require 'ohai/os' require 'ohai/dsl/plugin' require 'ohai/mixin/from_file' require 'ohai/mixin/command' @@ -30,18 +31,16 @@ require 'yajl' module Ohai class System attr_accessor :data - attr_reader :metadata - attr_reader :seen_plugins - attr_reader :loaded_plugins + attr_reader :attributes + attr_reader :plugins attr_reader :hints def initialize @data = Mash.new - @metadata = Mash.new - @seen_plugins = Hash.new - @loaded_plugins = Hash.new - @plugin_path = "" + @attributes = Hash.new + @plugins = Mash.new @hints = Hash.new + @plugin_path = "" end def [](key) @@ -51,23 +50,20 @@ module Ohai def load_plugins loader = Ohai::Loader.new(self) - # in all_plugins, we run 'os' and all the plugins it requires (kernel, - # ruby, languages) before running the remaining plugins. this - # helps find the correct plugins based on the operating system - # and os version. we can take a similar approach here by loading - # os, kernel, ruby, and languages plugins and collecting their - # data first - - # @todo: a better way of marking these plugins for pre-loading - %w{ languages ruby kernel os }.each do |plgn| - loader.load_plugin(plgn) - end - - %w{ languages ruby kernel os }.each do |plgn| - @loaded_plugins[plgn].new(self).run + Ohai::Config[:plugin_path].each do |path| + [ + Dir[File.join(path, '*')], + Dir[File.join(path, Ohai::OS.collect_os, '**', '*')] + ].flatten.each do |file| + file_regex = Regexp.new("#{File.expand_path(path)}#{File::SEPARATOR}(.+).rb$") + md = file_regex.match(file) + if md + plugin_path = md[0] + plugin_name = md[1] + loader.load_plugin(plugin_path, plugin_name) unless @plugins.has_key?(plugin_name) + end + end end - - # @todo: use the data collected above to load the remaining plugins end def all_plugins @@ -115,10 +111,10 @@ module Ohai def refresh_plugins(path = '/') parts = path.split('/') if parts.length == 0 - h = @metadata + h = @providers else parts.shift if parts[0].length == 0 - h = @metadata + h = @providers parts.each do |part| break unless h.has_key?(part) h = h[part] @@ -172,7 +168,7 @@ module Ohai Ohai::Config[:plugin_path].each do |path| check_path = File.expand_path(File.join(path, filename)) if File.exist?(check_path) - plugin = DSL::Plugin.new(self, filename.split('.')[0], check_path) + plugin = DSL::Plugin.new(self, check_path) break else next |