Commit 4545a136 authored by Stefano Rivera's avatar Stefano Rivera

New upstream version 13.8.0

parent 28fd944f
......@@ -2,12 +2,27 @@ source "https://rubygems.org"
gemspec
# NOTE: do not submit PRs to add pry as a dep, add to your Gemfile.local
group :development do
gem "sigar", :platform => "ruby"
gem "chefstyle"
gem "rake", ">= 10.1.0"
gem "rspec-core", "~> 3.0"
gem "rspec-expectations", "~> 3.0"
gem "rspec-mocks", "~> 3.0"
gem "rspec-collection_matchers", "~> 1.0"
gem "ipaddr_extensions"
end
group :ci do
gem "rspec_junit_formatter"
end
gem "chefstyle", "= 0.4.0"
gem "overcommit", ">= 0.34.1"
gem "pry-byebug"
gem "pry-stack_explorer"
gem "rb-readline"
group :changelog do
gem "github_changelog_generator", git: "https://github.com/chef/github-changelog-generator"
end
instance_eval(ENV["GEMFILE_MOD"]) if ENV["GEMFILE_MOD"]
# If you want to load debugging tools into the bundle exec sandbox,
# add these additional dependencies into Gemfile.local
eval_gemfile(__FILE__ + ".local") if File.exist?(__FILE__ + ".local")
......@@ -23,11 +23,13 @@ RuboCop::RakeTask.new(:style) do |task|
task.options += ["--display-cop-names", "--no-color"]
end
require "github_changelog_generator/task"
begin
require "github_changelog_generator/task"
GitHubChangelogGenerator::RakeTask.new :changelog do |config|
config.future_release = Ohai::VERSION
config.enhancement_labels = "enhancement,Enhancement,New Feature,Feature".split(",")
config.bug_labels = "bug,Bug,Improvement,Upstream Bug".split(",")
config.exclude_labels = "duplicate,question,invalid,wontfix,no_changelog,Exclude From Changelog,Question,Discussion".split(",")
GitHubChangelogGenerator::RakeTask.new :changelog do |config|
config.future_release = Ohai::VERSION
config.max_issues = 0
config.add_issues_wo_labels = false
end
rescue LoadError
end
......@@ -19,23 +19,8 @@
# limitations under the License.
#
begin
require "rubygems"
rescue LoadError
# must be debian! ;)
missing_rubygems = true
end
begin
# if we're in a source code checkout, we want to run the code from that.
# have to do this *after* rubygems is loaded.
$:.unshift File.expand_path("../../lib", __FILE__)
require "ohai/application"
rescue LoadError
if missing_rubygems
STDERR.puts "rubygems previously failed to load - is it installed?"
end
raise
end
# if we're in a source code checkout, we want to run the code from that.
$:.unshift File.expand_path("../../lib", __FILE__)
require "ohai/application"
Ohai::Application.new.run
......@@ -20,6 +20,7 @@ require "chef-config/workstation_config_loader"
require "ohai"
require "ohai/log"
require "mixlib/cli"
require "benchmark"
class Ohai::Application
include Mixlib::CLI
......@@ -74,8 +75,11 @@ class Ohai::Application
end
def run
configure_ohai
run_application
elapsed = Benchmark.measure do
configure_ohai
run_application
end
Ohai::Log.debug("Ohai took #{elapsed.total} total seconds to run.")
end
def configure_ohai
......@@ -83,9 +87,12 @@ class Ohai::Application
@attributes = nil if @attributes.empty?
load_workstation_config
Ohai::Log.init(Ohai.config[:log_location])
end
def run_application
config[:invoked_from_cli] = true
ohai = Ohai::System.new(config)
ohai.all_plugins(@attributes)
......
......@@ -65,6 +65,9 @@ module Ohai
37 => "memory_channel",
38 => "ipmi_device",
39 => "power_supply",
40 => "additional_information",
41 => "onboard_devices_extended_information",
42 => "management_controller_host_interfaces",
126 => "disabled_entries",
127 => "end_of_table_marker",
}
......@@ -75,20 +78,18 @@ module Ohai
# look up DMI ID
def id_lookup(id)
begin
id = id.to_i
if (id >= 128) && (id <= 255)
id = "oem_data_#{id}"
elsif DMI::ID_TO_DESCRIPTION.has_key?(id)
id = DMI::ID_TO_DESCRIPTION[id]
else
Ohai::Log.debug("unrecognized header id; falling back to 'unknown'")
id = "unknown"
end
rescue
Ohai::Log.debug("failed to look up id #{id}, returning unchanged")
id
id = id.to_i
if (id >= 128) && (id <= 255)
id = "oem_data_#{id}"
elsif DMI::ID_TO_DESCRIPTION.has_key?(id)
id = DMI::ID_TO_DESCRIPTION[id]
else
Ohai::Log.debug("unrecognized header id; falling back to 'unknown'")
id = "unknown"
end
rescue
Ohai::Log.debug("failed to look up id #{id}, returning unchanged")
id
end
# create simplified convenience access keys for each record type
......@@ -115,7 +116,7 @@ module Ohai
end
end
in_common.each do |field, value|
next if value == nil
next if value.nil?
dmi[type][field] = value.strip
end
end
......
......@@ -19,7 +19,6 @@
require "chef-config/config"
require "ohai/exception"
require "ohai/log"
require "ohai/plugin_config"
module Ohai
......@@ -28,98 +27,15 @@ module Ohai
# Reopens ChefConfig::Config to add Ohai configuration settings.
# see: https://github.com/chef/chef/blob/master/lib/chef/config.rb
class Config
# These methods need to be defined before they are used as config defaults,
# otherwise they will get method_missing'd to nil.
class << self
def merge_deprecated_config
[ :hints_path, :plugin_path ].each do |option|
if has_key?(option) && send(option) != send("default_#{option}".to_sym)
Ohai::Log.warn(option_deprecated(option))
end
end
ohai.merge!(configuration)
end
def default_hints_path
[ ChefConfig::Config.platform_specific_path("/etc/chef/ohai/hints") ]
end
def default_plugin_path
[ File.expand_path(File.join(File.dirname(__FILE__), "plugins")) ]
end
end
# Copy deprecated configuration options into the ohai config context.
# Keep "old" config defaults around so anyone calling Ohai::Config[:key]
# won't be broken. Also allows users to append to configuration options
# (e.g., Ohai::Config[:plugin_path] << some_path) in their config files.
default :disabled_plugins, []
default :hints_path, default_hints_path
default :log_level, :auto
default :log_location, STDERR
default :plugin_path, default_plugin_path
# Log deprecation warning when a top-level configuration option is set.
# TODO: Should we implement a config_attr_reader so that deprecation
# warnings will be generatd on read?
[
:directory,
:disabled_plugins,
:log_level,
:log_location,
:version,
].each do |option|
# https://docs.chef.io/config_rb_client.html#ohai-settings
# hints_path and plugin_path are intentionally excluded here; warnings for
# setting these attributes are generated in merge_deprecated_config since
# append (<<) operations bypass the config writer.
config_attr_writer option do |value|
# log_level and log_location are common configuration options for chef
# and other chef applications. When configuration files are read there
# is no distinction between log_level and Ohai::Config[:log_level] and
# we may emit a false deprecation warning. The deprecation warnings for
# these settings reflect that possibility.
# Furthermore, when the top-level config settings are removed we will
# need to ensure that Ohai.config[:log_level] can be set by writing
# log_level in a configuration file for consistent behavior with chef.
deprecation_warning = if [ :log_level, :log_location ].include?(value)
option_might_be_deprecated(option)
else
option_deprecated(option)
end
Ohai::Log.warn(deprecation_warning)
value
end
end
config_context :ohai do
default :disabled_plugins, []
default :hints_path, Ohai::Config.default_hints_path
default :hints_path, [ ChefConfig::Config.platform_specific_path("/etc/chef/ohai/hints") ]
default :log_level, :auto
default :log_location, STDERR
default :plugin, Ohai::PluginConfig.new { |h, k| h[k] = Ohai::PluginConfig.new }
default :plugin_path, Ohai::Config.default_plugin_path
end
class << self
def option_deprecated(option)
<<-EOM.chomp!.tr("\n", " ")
Ohai::Config[:#{option}] is set. Ohai::Config[:#{option}] is deprecated and will
be removed in future releases of ohai. Use ohai.#{option} in your configuration
file to configure :#{option} for ohai.
EOM
end
def option_might_be_deprecated(option)
option_deprecated(option) + <<-EOM.chomp!.tr("\n", " ")
If your configuration file is used with other applications which configure
:#{option}, and you have not configured Ohai::Config[:#{option}], you may
disregard this warning.
EOM
end
default :plugin_path, [ File.expand_path(File.join(File.dirname(__FILE__), "plugins")), ChefConfig::Config.platform_specific_path("/etc/chef/ohai/plugins") ]
default :critical_plugins, []
end
end
......
......@@ -85,10 +85,12 @@ module Ohai
include Ohai::Util::FileHelper
attr_reader :data
attr_reader :failed
def initialize(data)
@data = data
@has_run = false
@failed = false
end
def run
......@@ -154,8 +156,19 @@ module Ohai
end
end
def set_attribute(name, *values)
@data[name] = Array18(*values)
def set_attribute(name, *attrs, value)
# Initialize the path in the @data Mash with new Mashes, if needed.
# Will raise a TypeError if we hit a subattribute that is not a
# Hash, Mash, or Array.
keys = [name] + attrs
attribute = keys[0..-2].inject(@data) do |attrs, key|
attrs[key] ||= Mash.new
attrs[key]
end
# Set the subattribute to the value.
attr_name = attrs.empty? ? name : attrs[-1]
attribute[attr_name] = value
@data[name]
end
......@@ -169,14 +182,14 @@ module Ohai
# emulates the old plugin loading behavior
def safe_run
begin
self.run
rescue Ohai::Exceptions::Error => e
raise e
rescue => e
Ohai::Log.debug("Plugin #{self.name} threw #{e.inspect}")
e.backtrace.each { |line| Ohai::Log.debug( line ) }
end
run
rescue Ohai::Exceptions::Error => e
@failed = true
raise e
rescue => e
@failed = true
Ohai::Log.debug("Plugin #{name} threw #{e.inspect}")
e.backtrace.each { |line| Ohai::Log.debug( line ) }
end
def method_missing(name, *args)
......@@ -198,12 +211,6 @@ module Ohai
# NoMethodError occurs when trying to access a key on nil
nil
end
def Array18(*args)
return nil if args.empty?
return args.first if args.length == 1
return *args
end
end
end
end
......@@ -44,7 +44,7 @@ module Ohai
end
def self.collect_contents(contents)
define_method(:run_plugin) { self.instance_eval(contents) }
define_method(:run_plugin) { instance_eval(contents) }
end
def provides(*paths)
......
......@@ -85,11 +85,11 @@ module Ohai
platform = collect_os
if collector.has_key?(platform)
self.instance_eval(&collector[platform])
instance_eval(&collector[platform])
elsif collector.has_key?(:default)
self.instance_eval(&collector[:default])
instance_eval(&collector[:default])
else
Ohai::Log.debug("Plugin #{self.name}: No data to collect. Skipping...")
Ohai::Log.debug("Plugin #{name}: No data to collect. Skipping...")
end
end
......@@ -122,7 +122,7 @@ module Ohai
# Memory => ["", "Memory"]
# NetworkListeners => ["", "Network", "", "Listeners"]
# SSHHostKey => ["SSH", "Host", "", "Key"]
parts = self.name.to_s.split(/([A-Z][a-z]+)/)
parts = name.to_s.split(/([A-Z][a-z]+)/)
# ["DMI"] => ["DMI"]
# ["", "Memory"] => ["Memory"]
# ["", "Network", "", "Listeners"] => ["Network", "Listeners"]
......
......@@ -29,5 +29,6 @@ module Ohai
class DependencyNotFound < Error; end
class AttributeSyntaxError < Error; end
class PluginConfigError < Error; end
class CriticalPluginFailure < Error; end
end
end
......@@ -40,7 +40,7 @@ module Ohai
# Finds all the *.rb files under the configured paths in :plugin_path
def self.find_all_in(plugin_dir)
unless Dir.exist?(plugin_dir)
Ohai::Log.warn("The plugin path #{plugin_dir} does not exist. Skipping...")
Ohai::Log.info("The plugin path #{plugin_dir} does not exist. Skipping...")
return []
end
......@@ -70,8 +70,8 @@ module Ohai
# Searches all plugin paths and returns an Array of PluginFile objects
# representing each plugin file.
def plugin_files_by_dir
Array(Ohai.config[:plugin_path]).inject([]) do |plugin_files, plugin_path|
def plugin_files_by_dir(dir = Ohai.config[:plugin_path])
Array(dir).inject([]) do |plugin_files, plugin_path|
plugin_files + PluginFile.find_all_in(plugin_path)
end
end
......@@ -85,6 +85,15 @@ module Ohai
collect_v7_plugins
end
def load_additional(from)
from = [ Ohai.config[:plugin_path], from].flatten
plugin_files_by_dir(from).collect do |plugin_file|
Ohai::Log.debug "Loading additional plugin: #{plugin_file}"
plugin = load_plugin_class(plugin_file.path, plugin_file.plugin_root)
load_v7_plugin(plugin)
end
end
# Load a specified file as an ohai plugin and creates an instance of it.
# Not used by ohai itself, but can be used to load a plugin for testing
# purposes.
......@@ -124,8 +133,8 @@ module Ohai
load_v7_plugin_class(contents, plugin_path)
else
Ohai::Log.warn("[DEPRECATION] Plugin at #{plugin_path} is a version 6 plugin. \
Version 6 plugins will not be supported in future releases of Ohai. \
Please upgrade your plugin to version 7 plugin syntax. \
Version 6 plugins will not be supported in Chef/Ohai 14. \
Please upgrade your plugin to version 7 plugin format. \
For more information visit here: docs.chef.io/ohai_custom.html")
load_v6_plugin_class(contents, plugin_path, plugin_dir_path)
......
#
# Author:: Adam Jacob (<adam@chef.io>)
# Copyright:: Copyright (c) 2008-2016 Chef Software, Inc.
# Copyright:: Copyright (c) 2008-2017, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
......@@ -22,6 +22,8 @@ module Ohai
class Log
extend Mixlib::Log
# this class loading initalization is so that we don't lose early logger
# messages when run from the CLI?
init(STDERR)
level = :info
......
......@@ -135,7 +135,7 @@ class Mash < Hash
#
# @return [Mash] A new mash with the hash values merged in.
def merge(hash)
self.dup.update(hash)
dup.update(hash)
end
# @param key<Object>
......
#
# Author:: Toomas Pelberg (<toomas.pelberg@playtech.com>)
# Copyright:: Copyright (c) 2011-2016 Chef Software, Inc.
# Author:: Tim Smith (<tsmith@chef.io>)
# Copyright:: Copyright 2017 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "ohai/mixin/network_constants"
Ohai.plugin(:NetworkRoutes) do
begin
require "sigar"
require "net/http"
include Ohai::Mixin::NetworkConstants
module Ohai
module Mixin
module AzureMetadata
provides "network/interfaces/adapters/route"
depends "network/interfaces"
AZURE_METADATA_ADDR = "169.254.169.254" unless defined?(AZURE_METADATA_ADDR)
AZURE_METADATA_URL = "/metadata/instance?api-version=2017-04-02" unless defined?(AZURE_METADATA_URL)
def flags(flags)
f = ""
if (flags & Sigar::RTF_UP) != 0
f += "U"
end
if (flags & Sigar::RTF_GATEWAY) != 0
f += "G"
# fetch the meta content with a timeout and the required header
def http_get(uri)
conn = Net::HTTP.start(AZURE_METADATA_ADDR)
conn.read_timeout = 6
conn.get(uri, initheader = { "Metadata" => "true" })
end
if (flags & Sigar::RTF_HOST) != 0
f += "H"
end
f
end
collect_data(:default) 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 = {}
Ohai::Mixin::NetworkConstants::SIGAR_ROUTE_METHODS.each do |m|
if m == :flags
route_data[m] = flags(route.send(m))
else
route_data[m] = route.send(m)
def fetch_metadata
Ohai::Log.debug("Mixin AzureMetadata: Fetching metadata from host #{AZURE_METADATA_ADDR} at #{AZURE_METADATA_URL}")
response = http_get(AZURE_METADATA_URL)
if response.code == "200"
begin
data = StringIO.new(response.body)
parser = FFI_Yajl::Parser.new
parser.parse(data)
rescue FFI_Yajl::ParseError
Ohai::Log.warn("Mixin AzureMetadata: Metadata response is NOT valid JSON")
nil
end
else
Ohai::Log.warn("Mixin AzureMetadata: Received response code #{response.code} requesting metadata")
nil
end
network[:interfaces][route.ifname][:route][route.destination] = route_data
end
end
rescue LoadError
Ohai::Log.debug("Could not load sigar gem. Skipping NetworkRoutes plugin")
end
end
This diff is collapsed.
......@@ -42,8 +42,10 @@ module ::Ohai::Mixin::DmiDecode
return "kvm"
when /Product.*: BHYVE/
return "bhyve"
when /Manufacturer: Veertu/
return "veertu"
end
end
return nil
nil
end
end
#
# Author:: Doug MacEachern <dougm@vmware.com>
# Copyright:: Copyright (c) 2010 VMware, Inc.
# Author:: Dylan Page (<dpage@digitalocean.com>)
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
Ohai.plugin(:Memory) do
provides "memory"
require "net/http"
module Ohai
module Mixin
module DOMetadata
collect_data(:hpux, :default) do
require "sigar"
sigar = Sigar.new
DO_METADATA_ADDR = "169.254.169.254" unless defined?(DO_METADATA_ADDR)
DO_METADATA_URL = "/metadata/v1.json" unless defined?(DO_METADATA_URL)
memory Mash.new
memory[:swap] = Mash.new
def http_client
Net::HTTP.start(DO_METADATA_ADDR).tap { |h| h.read_timeout = 6 }
end
mem = sigar.mem
swap = sigar.swap
def fetch_metadata
uri = "#{DO_METADATA_URL}"
response = http_client.get(uri)
case response.code
when "200"
parser = FFI_Yajl::Parser.new
parser.parse(response.body)
when "404"
Ohai::Log.debug("Mixin DOMetadata: Encountered 404 response retrieving Digital Ocean metadata: #{uri} ; continuing.")
{}
else
raise "Mixin DOMetadata: Encountered error retrieving Digital Ocean metadata (#{uri} returned #{response.code} response)"
end
end
memory[:total] = (mem.total / 1024).to_s + "kB"
memory[:free] = (mem.free / 1024).to_s + "kB"