diff options
author | danielsdeleo <dan@getchef.com> | 2014-09-03 12:45:04 -0700 |
---|---|---|
committer | danielsdeleo <dan@getchef.com> | 2014-09-03 12:45:04 -0700 |
commit | 4aac7e9981dce28e800ecbb42d3c580ef96d4ba4 (patch) | |
tree | 9e604c4addd201246863e401defbe303a75f00f5 | |
parent | d762b7ba7483378439737f14b9b8b3b1a9cb727e (diff) | |
parent | 789462db340758a205e19f0339a7b2e7361d11d6 (diff) | |
download | chef-4aac7e9981dce28e800ecbb42d3c580ef96d4ba4.tar.gz |
Merge branch 'just-config-rb'
-rw-r--r-- | CHANGELOG.md | 2 | ||||
-rw-r--r-- | DOC_CHANGES.md | 13 | ||||
-rw-r--r-- | RELEASE_NOTES.md | 13 | ||||
-rw-r--r-- | lib/chef/application.rb | 3 | ||||
-rw-r--r-- | lib/chef/application/client.rb | 14 | ||||
-rw-r--r-- | lib/chef/config.rb | 6 | ||||
-rw-r--r-- | lib/chef/config_fetcher.rb | 27 | ||||
-rw-r--r-- | lib/chef/knife.rb | 157 | ||||
-rw-r--r-- | lib/chef/null_logger.rb | 72 | ||||
-rw-r--r-- | lib/chef/workstation_config_loader.rb | 177 | ||||
-rw-r--r-- | spec/integration/client/client_spec.rb | 12 | ||||
-rw-r--r-- | spec/unit/config_fetcher_spec.rb | 4 | ||||
-rw-r--r-- | spec/unit/knife/config_file_selection_spec.rb | 135 | ||||
-rw-r--r-- | spec/unit/knife_spec.rb | 33 | ||||
-rw-r--r-- | spec/unit/workstation_config_loader_spec.rb | 277 |
15 files changed, 614 insertions, 331 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 016bde47f1..c160fae749 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,8 @@ ### Chef Contributions +* `knife` now prefers to load `config.rb` in preference to `knife.rb`; +`knife.rb` will be used if `config.rb` is not found. * Fixed Config[:cache_path] to use path_join() * Updated chef-zero to 3.0. * knife cookbook site download/list/search/share/show/unshare now uses diff --git a/DOC_CHANGES.md b/DOC_CHANGES.md index 1ef0a7830c..c08ab0097a 100644 --- a/DOC_CHANGES.md +++ b/DOC_CHANGES.md @@ -6,6 +6,19 @@ Example Doc Change: Description of the required change. --> +### Knife now prefers to use `config.rb` rather than `knife.rb` + +Knife will now look for `config.rb` in preference to `knife.rb` for its +configuration file. The syntax and configuration options available in +`config.rb` are identical to `knife.rb`. Also, the search path for +configuration files is unchanged. + +At this time, it is _recommended_ that users use `config.rb` instead of +`knife.rb`, but `knife.rb` is not deprecated; no warning will be emitted +when using `knife.rb`. Once third-party application developers have had +sufficient time to adapt to the change, `knife.rb` will become +deprecated and config.rb will be preferred. + ### value_for_platform Method - where <code>"platform"</code> can be a comma-separated list, each specifying a platform, such as Red Hat, openSUSE, or Fedora, <code>version</code> specifies the version of that platform, and <code>value</code> specifies the value that will be used if the node's platform matches the <code>value_for_platform</code> method. If each value only has a single platform, then the syntax is like the following: diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 33e405d273..30c5d0893e 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,5 +1,18 @@ # Chef Client Release Notes 12.0.0: +## Knife Prefers `config.rb` to `knife.rb`. + +Knife will now look for `config.rb` in preference to `knife.rb` for its +configuration file. The syntax and configuration options available in +`config.rb` are identical to `knife.rb`. Also, the search path for +configuration files is unchanged. + +At this time, it is _recommended_ that users use `config.rb` instead of +`knife.rb`, but `knife.rb` is not deprecated; no warning will be emitted +when using `knife.rb`. Once third-party application developers have had +sufficient time to adapt to the change, `knife.rb` will become +deprecated and config.rb will be preferred. + ## Boostrap Changes Chef Client 12 introduces a set of changes to `knife bootstrap`. Here is the list of changes: diff --git a/lib/chef/application.rb b/lib/chef/application.rb index 7a80b700d6..5b1d53d741 100644 --- a/lib/chef/application.rb +++ b/lib/chef/application.rb @@ -81,10 +81,11 @@ class Chef::Application # Parse the config file def load_config_file - config_fetcher = Chef::ConfigFetcher.new(config[:config_file], Chef::Config.config_file_jail) + config_fetcher = Chef::ConfigFetcher.new(config[:config_file]) if config[:config_file].nil? Chef::Log.warn("No config file found or specified on command line, using command line options.") elsif config_fetcher.config_missing? + pp config_missing: true Chef::Log.warn("*****************************************") Chef::Log.warn("Did not find config file: #{config[:config_file]}, using command line options.") Chef::Log.warn("*****************************************") diff --git a/lib/chef/application/client.rb b/lib/chef/application/client.rb index c581bb0da0..6c06ad656d 100644 --- a/lib/chef/application/client.rb +++ b/lib/chef/application/client.rb @@ -24,6 +24,7 @@ require 'chef/daemon' require 'chef/log' require 'chef/config_fetcher' require 'chef/handler/error_report' +require 'chef/workstation_config_loader' class Chef::Application::Client < Chef::Application @@ -219,9 +220,10 @@ class Chef::Application::Client < Chef::Application :long => "--chef-zero-port PORT", :description => "Port (or port range) to start chef-zero on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works." - option :config_file_jail, - :long => "--config-file-jail PATH", - :description => "Directory under which config files are allowed to be loaded (no client.rb or knife.rb outside this path will be loaded)." + option :disable_config, + :long => "--disable-config", + :description => "Refuse to load a config file and use defaults. This is for development and not a stable API", + :boolean => true option :run_lock_timeout, :long => "--run-lock-timeout SECONDS", @@ -273,11 +275,9 @@ class Chef::Application::Client < Chef::Application end def load_config_file - Chef::Config.config_file_jail = config[:config_file_jail] if config[:config_file_jail] - if !config.has_key?(:config_file) + if !config.has_key?(:config_file) && !config[:disable_config] if config[:local_mode] - require 'chef/knife' - config[:config_file] = Chef::Knife.locate_config_file + config[:config_file] = Chef::WorkstationConfigLoader.new(nil, Chef::Log).config_location else config[:config_file] = Chef::Config.platform_specific_path("/etc/chef/client.rb") end diff --git a/lib/chef/config.rb b/lib/chef/config.rb index e8a9839d71..4e71645dcc 100644 --- a/lib/chef/config.rb +++ b/lib/chef/config.rb @@ -87,10 +87,6 @@ class Chef end end - # No config file (client.rb / knife.rb / etc.) will be loaded outside this path. - # Major use case is tests, where we don't want to load the user's config files. - configurable(:config_file_jail) - default :formatters, [] # Override the config dispatch to set the value of multiple server options simultaneously @@ -527,7 +523,7 @@ class Chef end def self.windows_home_path - windows_home_path = env['SYSTEMDRIVE'] + env['HOMEPATH'] if env['SYSTEMDRIVE'] && env['HOMEPATH'] + env['SYSTEMDRIVE'] + env['HOMEPATH'] if env['SYSTEMDRIVE'] && env['HOMEPATH'] end # returns a platform specific path to the user home dir if set, otherwise default to current directory. diff --git a/lib/chef/config_fetcher.rb b/lib/chef/config_fetcher.rb index 1d0693eaa2..a8aad0740d 100644 --- a/lib/chef/config_fetcher.rb +++ b/lib/chef/config_fetcher.rb @@ -7,11 +7,9 @@ class Chef class ConfigFetcher attr_reader :config_location - attr_reader :config_file_jail - def initialize(config_location, config_file_jail=nil) + def initialize(config_location) @config_location = config_location - @config_file_jail = config_file_jail end def fetch_json @@ -48,24 +46,11 @@ class Chef def config_missing? return false if remote_config? - # Check if the config file exists, and check if it is underneath the config file jail - begin - real_config_file = Pathname.new(config_location).realpath.to_s - rescue Errno::ENOENT - return true - end - - # If realpath succeeded, the file exists - return false if !config_file_jail - - begin - real_jail = Pathname.new(config_file_jail).realpath.to_s - rescue Errno::ENOENT - Chef::Log.warn("Config file jail #{config_file_jail} does not exist: will not load any config file.") - return true - end - - !Chef::ChefFS::PathUtils.descendant_of?(real_config_file, real_jail) + # Check if the config file exists + Pathname.new(config_location).realpath.to_s + false + rescue Errno::ENOENT + return true end def http diff --git a/lib/chef/knife.rb b/lib/chef/knife.rb index 038ab61715..6421384f01 100644 --- a/lib/chef/knife.rb +++ b/lib/chef/knife.rb @@ -20,7 +20,7 @@ require 'forwardable' require 'chef/version' require 'mixlib/cli' -require 'chef/config_fetcher' +require 'chef/workstation_config_loader' require 'chef/mixin/convert_to_class_name' require 'chef/mixin/path_sanity' require 'chef/knife/core/subcommand_loader' @@ -159,6 +159,27 @@ class Chef end end + # Shared with subclasses + @@chef_config_dir = nil + + def self.load_config(explicit_config_file) + config_loader = WorkstationConfigLoader.new(explicit_config_file, Chef::Log) + Chef::Log.debug("Using configuration from #{config_loader.config_location}") + config_loader.load + + ui.warn("No knife configuration file found") if config_loader.no_config_found? + @@chef_config_dir = config_loader.chef_config_dir + + config_loader + rescue Exceptions::ConfigurationError => e + ui.error(ui.color("CONFIGURATION ERROR:", :red) + e.message) + exit 1 + end + + def self.chef_config_dir + @@chef_config_dir + end + # Run knife for the given +args+ (ARGV), adding +options+ to the list of # CLI options that the subcommand knows how to handle. # ===Arguments @@ -166,6 +187,16 @@ class Chef # options::: A Mixlib::CLI option parser hash. These +options+ are how # subcommands know about global knife CLI options def self.run(args, options={}) + # Fallback debug logging. Normally the logger isn't configured until we + # read the config, but this means any logging that happens before the + # config file is read may be lost. If the KNIFE_DEBUG variable is set, we + # setup the logger for debug logging to stderr immediately to catch info + # from early in the setup process. + if ENV['KNIFE_DEBUG'] + Chef::Log.init($stderr) + Chef::Log.level(:debug) + end + load_commands subcommand_class = subcommand_class_from(args) subcommand_class.options = options.merge!(subcommand_class.options) @@ -239,40 +270,12 @@ class Chef exit 10 end - def self.working_directory - a = if Chef::Platform.windows? - ENV['CD'] - else - ENV['PWD'] - end || Dir.pwd - - a - end - def self.reset_config_path! @@chef_config_dir = nil end reset_config_path! - - # search upward from current_dir until .chef directory is found - def self.chef_config_dir - if @@chef_config_dir.nil? # share this with subclasses - @@chef_config_dir = false - full_path = working_directory.split(File::SEPARATOR) - (full_path.length - 1).downto(0) do |i| - candidate_directory = File.join(full_path[0..i] + [".chef" ]) - if File.exist?(candidate_directory) && File.directory?(candidate_directory) - @@chef_config_dir = candidate_directory - break - end - end - end - @@chef_config_dir - end - - public # Create a new instance of the current class configured for the given @@ -322,39 +325,6 @@ class Chef config_file_settings end - def self.config_fetcher(candidate_config) - Chef::ConfigFetcher.new(candidate_config, Chef::Config.config_file_jail) - end - - def self.locate_config_file - candidate_configs = [] - - # Look for $KNIFE_HOME/knife.rb (allow multiple knives config on same machine) - if ENV['KNIFE_HOME'] - candidate_configs << File.join(ENV['KNIFE_HOME'], 'knife.rb') - end - # Look for $PWD/knife.rb - if Dir.pwd - candidate_configs << File.join(Dir.pwd, 'knife.rb') - end - # Look for $UPWARD/.chef/knife.rb - if chef_config_dir - candidate_configs << File.join(chef_config_dir, 'knife.rb') - end - # Look for $HOME/.chef/knife.rb - if ENV['HOME'] - candidate_configs << File.join(ENV['HOME'], '.chef', 'knife.rb') - end - - candidate_configs.each do | candidate_config | - fetcher = config_fetcher(candidate_config) - if !fetcher.config_missing? - return candidate_config - end - end - return nil - end - # Apply Config in this order: # defaults from mixlib-cli # settings from config file, via Chef::Config[:knife] @@ -386,6 +356,8 @@ class Chef Chef::Config[:log_level] = :debug end + Chef::Config[:log_level] = :debug if ENV['KNIFE_DEBUG'] + Chef::Config[:node_name] = config[:node_name] if config[:node_name] Chef::Config[:client_key] = config[:client_key] if config[:client_key] Chef::Config[:chef_server_url] = config[:chef_server_url] if config[:chef_server_url] @@ -416,70 +388,13 @@ class Chef end def configure_chef - if !config[:config_file] - located_config_file = self.class.locate_config_file - config[:config_file] = located_config_file if located_config_file - end - - # Don't try to load a knife.rb if it wasn't specified. - if config[:config_file] - Chef::Config.config_file = config[:config_file] - fetcher = Chef::ConfigFetcher.new(config[:config_file], Chef::Config.config_file_jail) - if fetcher.config_missing? - ui.error("Specified config file #{config[:config_file]} does not exist#{Chef::Config.config_file_jail ? " or is not under config file jail #{Chef::Config.config_file_jail}" : ""}!") - exit 1 - end - Chef::Log.debug("Using configuration from #{config[:config_file]}") - read_config(fetcher.read_config, config[:config_file]) - else - # ...but do log a message if no config was found. - Chef::Config[:color] = config[:color] - ui.warn("No knife configuration file found") - end + config_loader = self.class.load_config(config[:config_file]) + config[:config_file] = config_loader.config_location merge_configs apply_computed_config end - def read_config(config_content, config_file_path) - Chef::Config.from_string(config_content, config_file_path) - rescue SyntaxError => e - ui.error "You have invalid ruby syntax in your config file #{config_file_path}" - ui.info(ui.color(e.message, :red)) - if file_line = e.message[/#{Regexp.escape(config_file_path)}:[\d]+/] - line = file_line[/:([\d]+)$/, 1].to_i - highlight_config_error(config_file_path, line) - end - exit 1 - rescue Exception => e - ui.error "You have an error in your config file #{config_file_path}" - ui.info "#{e.class.name}: #{e.message}" - filtered_trace = e.backtrace.grep(/#{Regexp.escape(config_file_path)}/) - filtered_trace.each {|line| ui.msg(" " + ui.color(line, :red))} - if !filtered_trace.empty? - line_nr = filtered_trace.first[/#{Regexp.escape(config_file_path)}:([\d]+)/, 1] - highlight_config_error(config_file_path, line_nr.to_i) - end - - exit 1 - end - - def highlight_config_error(file, line) - config_file_lines = [] - IO.readlines(file).each_with_index {|l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}"} - if line == 1 - lines = config_file_lines[0..3] - lines[0] = ui.color(lines[0], :red) - else - lines = config_file_lines[Range.new(line - 2, line)] - lines[1] = ui.color(lines[1], :red) - end - ui.msg "" - ui.msg ui.color(" # #{file}", :white) - lines.each {|l| ui.msg(l)} - ui.msg "" - end - def show_usage stdout.puts("USAGE: " + self.opt_parser.to_s) end diff --git a/lib/chef/null_logger.rb b/lib/chef/null_logger.rb new file mode 100644 index 0000000000..5195cc5ce2 --- /dev/null +++ b/lib/chef/null_logger.rb @@ -0,0 +1,72 @@ +# +# Author:: Daniel DeLeo (<dan@getchef.com>) +# Copyright:: Copyright (c) 2014 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 +# +# 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. + +class Chef + + # Null logger implementation that just ignores everything. This is used by + # classes that are intended to be reused outside of Chef, but need to offer + # logging functionality when used by other Chef code. + # + # It does not define the full interface provided by Logger, just enough to be + # a reasonable duck type. In particular, methods setting the log level, log + # device, etc., are not implemented because any code calling those methods + # probably expected a real logger and not this "fake" one. + class NullLogger + + def fatal(message, &block) + end + + def error(message, &block) + end + + def warn(message, &block) + end + + def info(message, &block) + end + + def debug(message, &block) + end + + def add(severity, message=nil, progname=nil) + end + + def <<(message) + end + + def fatal? + false + end + + def error? + false + end + + def warn? + false + end + + def info? + false + end + + def debug? + false + end + + end +end diff --git a/lib/chef/workstation_config_loader.rb b/lib/chef/workstation_config_loader.rb new file mode 100644 index 0000000000..6715d4eec2 --- /dev/null +++ b/lib/chef/workstation_config_loader.rb @@ -0,0 +1,177 @@ +# +# Author:: Daniel DeLeo (<dan@getchef.com>) +# Copyright:: Copyright (c) 2014 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 +# +# 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 'chef/config_fetcher' +require 'chef/config' +require 'chef/null_logger' + +class Chef + + class WorkstationConfigLoader + + # Path to a config file requested by user, (e.g., via command line option). Can be nil + attr_reader :explicit_config_file + + # TODO: initialize this with a logger for Chef and Knife + def initialize(explicit_config_file, logger=nil) + @explicit_config_file = explicit_config_file + @config_location = nil + @logger = logger || NullLogger.new + end + + def no_config_found? + config_location.nil? + end + + def config_location + @config_location ||= (explicit_config_file || locate_local_config) + end + + def chef_config_dir + if @chef_config_dir.nil? + @chef_config_dir = false + full_path = working_directory.split(File::SEPARATOR) + (full_path.length - 1).downto(0) do |i| + candidate_directory = File.join(full_path[0..i] + [".chef" ]) + if File.exist?(candidate_directory) && File.directory?(candidate_directory) + @chef_config_dir = candidate_directory + break + end + end + end + @chef_config_dir + end + + def load + # Ignore it if there's no explicit_config_file and can't find one at a + # default path. + return false if config_location.nil? + + if explicit_config_file && !path_exists?(config_location) + raise Exceptions::ConfigurationError, "Specified config file #{config_location} does not exist" + end + + # Have to set Chef::Config.config_file b/c other config is derived from it. + Chef::Config.config_file = config_location + read_config(IO.read(config_location), config_location) + end + + # (Private API, public for test purposes) + def env + ENV + end + + # (Private API, public for test purposes) + def path_exists?(path) + Pathname.new(path).expand_path.exist? + end + + private + + def have_config?(path) + if path_exists?(path) + logger.info("Using config at #{path}") + true + else + logger.debug("Config not found at #{path}, trying next option") + false + end + end + + def locate_local_config + candidate_configs = [] + + # Look for $KNIFE_HOME/knife.rb (allow multiple knives config on same machine) + if env['KNIFE_HOME'] + candidate_configs << File.join(env['KNIFE_HOME'], 'config.rb') + candidate_configs << File.join(env['KNIFE_HOME'], 'knife.rb') + end + # Look for $PWD/knife.rb + if Dir.pwd + candidate_configs << File.join(Dir.pwd, 'config.rb') + candidate_configs << File.join(Dir.pwd, 'knife.rb') + end + # Look for $UPWARD/.chef/knife.rb + if chef_config_dir + candidate_configs << File.join(chef_config_dir, 'config.rb') + candidate_configs << File.join(chef_config_dir, 'knife.rb') + end + # Look for $HOME/.chef/knife.rb + if env['HOME'] + candidate_configs << File.join(env['HOME'], '.chef', 'config.rb') + candidate_configs << File.join(env['HOME'], '.chef', 'knife.rb') + end + + candidate_configs.find do | candidate_config | + have_config?(candidate_config) + end + end + + def working_directory + a = if Chef::Platform.windows? + env['CD'] + else + env['PWD'] + end || Dir.pwd + + a + end + + def read_config(config_content, config_file_path) + Chef::Config.from_string(config_content, config_file_path) + rescue SignalException + raise + rescue SyntaxError => e + message = "" + message << "You have invalid ruby syntax in your config file #{config_file_path}\n\n" + message << "#{e.class.name}: #{e.message}\n" + if file_line = e.message[/#{Regexp.escape(config_file_path)}:[\d]+/] + line = file_line[/:([\d]+)$/, 1].to_i + message << highlight_config_error(config_file_path, line) + end + raise Exceptions::ConfigurationError, message + rescue Exception => e + message = "You have an error in your config file #{config_file_path}\n\n" + message << "#{e.class.name}: #{e.message}\n" + filtered_trace = e.backtrace.grep(/#{Regexp.escape(config_file_path)}/) + filtered_trace.each {|bt_line| message << " " << bt_line << "\n" } + if !filtered_trace.empty? + line_nr = filtered_trace.first[/#{Regexp.escape(config_file_path)}:([\d]+)/, 1] + message << highlight_config_error(config_file_path, line_nr.to_i) + end + raise Exceptions::ConfigurationError, message + end + + + def highlight_config_error(file, line) + config_file_lines = [] + IO.readlines(file).each_with_index {|l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}"} + if line == 1 + lines = config_file_lines[0..3] + else + lines = config_file_lines[Range.new(line - 2, line)] + end + "Relevant file content:\n" + lines.join("\n") + "\n" + end + + def logger + @logger + end + + end +end diff --git a/spec/integration/client/client_spec.rb b/spec/integration/client/client_spec.rb index f0d978c516..8a1a65249b 100644 --- a/spec/integration/client/client_spec.rb +++ b/spec/integration/client/client_spec.rb @@ -33,17 +33,17 @@ EOM context 'and no config file' do it 'should complete with success when cwd is just above cookbooks and paths are not specified' do - result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('')}\"", :cwd => path_to('')) + result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => path_to('')) result.error! end it 'should complete with success when cwd is below cookbooks and paths are not specified' do - result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('')}\"", :cwd => path_to('cookbooks/x')) + result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => path_to('cookbooks/x')) result.error! end it 'should fail when cwd is below high above and paths are not specified' do - result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('')}\"", :cwd => File.expand_path('..', path_to(''))) + result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => File.expand_path('..', path_to(''))) result.exitstatus.should == 1 end end @@ -52,15 +52,11 @@ EOM before { file '.chef/knife.rb', 'xxx.xxx' } it 'should load .chef/knife.rb when -z is specified' do - result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('')}\"", :cwd => path_to('')) + result = shell_out("#{chef_client} -z -o 'x::default'", :cwd => path_to('')) # FATAL: Configuration error NoMethodError: undefined method `xxx' for nil:NilClass result.stdout.should include("xxx") end - it 'fails to load .chef/knife.rb when -z is specified and --config-file-jail does not include the .chef/knife.rb' do - result = shell_out("#{chef_client} -z -o 'x::default' --config-file-jail \"#{path_to('roles')}\"", :cwd => path_to('')) - result.error! - end end it "should complete with success" do diff --git a/spec/unit/config_fetcher_spec.rb b/spec/unit/config_fetcher_spec.rb index c29521806a..f6d5436a11 100644 --- a/spec/unit/config_fetcher_spec.rb +++ b/spec/unit/config_fetcher_spec.rb @@ -8,9 +8,7 @@ describe Chef::ConfigFetcher do let(:config_location_regex) { Regexp.escape(config_location) } let(:invalid_json_error_regex) { %r[Could not parse the provided JSON file \(#{config_location_regex}\)] } - let(:config_jail_path) { nil } - - let(:fetcher) { Chef::ConfigFetcher.new(config_location, config_jail_path) } + let(:fetcher) { Chef::ConfigFetcher.new(config_location) } context "when loading a local file" do let(:config_location) { "/etc/chef/client.rb" } diff --git a/spec/unit/knife/config_file_selection_spec.rb b/spec/unit/knife/config_file_selection_spec.rb deleted file mode 100644 index 0a623714d7..0000000000 --- a/spec/unit/knife/config_file_selection_spec.rb +++ /dev/null @@ -1,135 +0,0 @@ -# -# Author:: Nicolas Vinot (<aeris@imirhil.fr>) -# Copyright:: Copyright (c) 2010 Opscode, 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 -# -# 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 File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') -require 'tmpdir' - -describe Chef::Knife do - - let(:missing_config_fetcher) do - double(Chef::ConfigFetcher, :config_missing? => true) - end - - let(:available_config_fetcher) do - double(Chef::ConfigFetcher, :config_missing? => false, - :read_config => "") - end - - def have_config_file(path) - Chef::ConfigFetcher.should_receive(:new).at_least(1).times.with(path, nil).and_return(available_config_fetcher) - end - - before do - # Make sure tests can run when HOME is not set... - @original_home = ENV["HOME"] - ENV["HOME"] = Dir.tmpdir - end - - after do - ENV["HOME"] = @original_home - end - - before :each do - Chef::Config.stub(:from_file).and_return(true) - Chef::ConfigFetcher.stub(:new).and_return(missing_config_fetcher) - end - - it "configure knife from KNIFE_HOME env variable" do - env_config = File.expand_path(File.join(Dir.tmpdir, 'knife.rb')) - have_config_file(env_config) - - ENV['KNIFE_HOME'] = Dir.tmpdir - @knife = Chef::Knife.new - @knife.configure_chef - @knife.config[:config_file].should == env_config - end - - it "configure knife from PWD" do - pwd_config = "#{Dir.pwd}/knife.rb" - have_config_file(pwd_config) - - @knife = Chef::Knife.new - @knife.configure_chef - @knife.config[:config_file].should == pwd_config - end - - it "configure knife from UPWARD" do - upward_dir = File.expand_path "#{Dir.pwd}/.chef" - upward_config = File.expand_path "#{upward_dir}/knife.rb" - have_config_file(upward_config) - Chef::Knife.stub(:chef_config_dir).and_return(upward_dir) - - @knife = Chef::Knife.new - @knife.configure_chef - @knife.config[:config_file].should == upward_config - end - - it "configure knife from HOME" do - home_config = File.expand_path(File.join("#{ENV['HOME']}", "/.chef/knife.rb")) - have_config_file(home_config) - - @knife = Chef::Knife.new - @knife.configure_chef - @knife.config[:config_file].should == home_config - end - - it "configure knife from nothing" do - ::File.stub(:exist?).and_return(false) - @knife = Chef::Knife.new - @knife.ui.should_receive(:warn).with("No knife configuration file found") - @knife.configure_chef - @knife.config[:config_file].should be_nil - end - - it "configure knife precedence" do - env_config = File.join(Dir.tmpdir, 'knife.rb') - pwd_config = "#{Dir.pwd}/knife.rb" - upward_dir = File.expand_path "#{Dir.pwd}/.chef" - upward_config = File.expand_path "#{upward_dir}/knife.rb" - home_config = File.expand_path(File.join("#{ENV['HOME']}", "/.chef/knife.rb")) - configs = [ env_config, pwd_config, upward_config, home_config ] - - Chef::Knife.stub(:chef_config_dir).and_return(upward_dir) - ENV['KNIFE_HOME'] = Dir.tmpdir - - @knife = Chef::Knife.new - - @knife.configure_chef - @knife.config[:config_file].should be_nil - - have_config_file(home_config) - @knife = Chef::Knife.new - @knife.configure_chef - @knife.config[:config_file].should == home_config - - have_config_file(upward_config) - @knife = Chef::Knife.new - @knife.configure_chef - @knife.config[:config_file].should == upward_config - - have_config_file(pwd_config) - @knife = Chef::Knife.new - @knife.configure_chef - @knife.config[:config_file].should == pwd_config - - have_config_file(env_config) - @knife = Chef::Knife.new - @knife.configure_chef - @knife.config[:config_file].should == env_config - end -end diff --git a/spec/unit/knife_spec.rb b/spec/unit/knife_spec.rb index 70b60a2f96..2db6b40b28 100644 --- a/spec/unit/knife_spec.rb +++ b/spec/unit/knife_spec.rb @@ -44,34 +44,6 @@ describe Chef::Knife do @stderr = StringIO.new end - describe "selecting a config file" do - context "when the current working dir is inside a symlinked directory" do - before do - Chef::Knife.reset_config_path! - # pwd according to your shell is /home/someuser/prod/chef-repo, but - # chef-repo is a symlink to /home/someuser/codes/chef-repo - if Chef::Platform.windows? - ENV.should_receive(:[]).with("CD").and_return("/home/someuser/prod/chef-repo") - else - ENV.should_receive(:[]).with("PWD").and_return("/home/someuser/prod/chef-repo") - end - - Dir.stub(:pwd).and_return("/home/someuser/codes/chef-repo") - end - - after do - Chef::Knife.reset_config_path! - end - - it "loads the config from the non-dereferenced directory path" do - File.should_receive(:exist?).with("/home/someuser/prod/chef-repo/.chef").and_return(false) - File.should_receive(:exist?).with("/home/someuser/prod/.chef").and_return(true) - File.should_receive(:directory?).with("/home/someuser/prod/.chef").and_return(true) - Chef::Knife.chef_config_dir.should == "/home/someuser/prod/.chef" - end - end - end - describe "after loading a subcommand" do before do Chef::Knife.reset_subcommands! @@ -247,7 +219,7 @@ describe Chef::Knife do end it "loads lazy dependencies" do - command = Chef::Knife.run(%w{test yourself}) + Chef::Knife.run(%w{test yourself}) KnifeSpecs::TestYourself.test_deps_loaded.should be_true end @@ -256,7 +228,8 @@ describe Chef::Knife do KnifeSpecs::TestYourself.class_eval do deps { other_deps_loaded = true } end - command = Chef::Knife.run(%w{test yourself}) + + Chef::Knife.run(%w{test yourself}) KnifeSpecs::TestYourself.test_deps_loaded.should be_true other_deps_loaded.should be_true end diff --git a/spec/unit/workstation_config_loader_spec.rb b/spec/unit/workstation_config_loader_spec.rb new file mode 100644 index 0000000000..78313aec37 --- /dev/null +++ b/spec/unit/workstation_config_loader_spec.rb @@ -0,0 +1,277 @@ +# +# Author:: Daniel DeLeo (<dan@getchef.com>) +# Copyright:: Copyright (c) 2014 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 +# +# 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 'spec_helper' +require 'tempfile' +require 'chef/workstation_config_loader' + +describe Chef::WorkstationConfigLoader do + + let(:explicit_config_location) { nil } + + let(:env) { {} } + + let(:config_loader) do + described_class.new(explicit_config_location).tap do |c| + allow(c).to receive(:env).and_return(env) + end + end + + # Test methods that do I/O or reference external state which are stubbed out + # elsewhere. + describe "external dependencies" do + let(:config_loader) { described_class.new(nil) } + + it "delegates to ENV for env" do + expect(config_loader.env).to equal(ENV) + end + + it "tests a path's existence" do + expect(config_loader.path_exists?('/nope/nope/nope/nope/frab/jab/nab')).to be(false) + expect(config_loader.path_exists?(__FILE__)).to be(true) + end + + end + + describe "locating the config file" do + context "without an explicit config" do + + before do + allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false) + end + + it "has no config if HOME is not set" do + expect(config_loader.config_location).to be(nil) + expect(config_loader.no_config_found?).to be(true) + end + + context "when HOME is set and contains a knife.rb" do + + let(:home) { "/Users/example.user" } + + before do + env["HOME"] = home + allow(config_loader).to receive(:path_exists?).with("#{home}/.chef/knife.rb").and_return(true) + end + + it "uses the config in HOME/.chef/knife.rb" do + expect(config_loader.config_location).to eq("#{home}/.chef/knife.rb") + end + + context "and has a config.rb" do + + before do + allow(config_loader).to receive(:path_exists?).with("#{home}/.chef/config.rb").and_return(true) + end + + it "uses the config in HOME/.chef/config.rb" do + expect(config_loader.config_location).to eq("#{home}/.chef/config.rb") + end + + context "and/or a parent dir contains a .chef dir" do + + let(:env_pwd) { "/path/to/cwd" } + + before do + env["PWD"] = env_pwd + allow(config_loader).to receive(:path_exists?).with("#{env_pwd}/.chef/knife.rb").and_return(true) + allow(File).to receive(:exist?).with("#{env_pwd}/.chef").and_return(true) + allow(File).to receive(:directory?).with("#{env_pwd}/.chef").and_return(true) + end + + it "prefers the config from parent_dir/.chef" do + expect(config_loader.config_location).to eq("#{env_pwd}/.chef/knife.rb") + end + + context "and the parent dir's .chef dir has a config.rb" do + + before do + allow(config_loader).to receive(:path_exists?).with("#{env_pwd}/.chef/config.rb").and_return(true) + end + + it "prefers the config from parent_dir/.chef" do + expect(config_loader.config_location).to eq("#{env_pwd}/.chef/config.rb") + end + + context "and/or the current working directory contains a .chef dir" do + + let(:cwd) { Dir.pwd } + + before do + allow(config_loader).to receive(:path_exists?).with("#{cwd}/knife.rb").and_return(true) + end + + it "prefers a knife.rb located in the cwd" do + expect(config_loader.config_location).to eq("#{cwd}/knife.rb") + end + + context "and the CWD's .chef dir has a config.rb" do + + before do + allow(config_loader).to receive(:path_exists?).with("#{cwd}/config.rb").and_return(true) + end + + it "prefers a config located in the cwd" do + expect(config_loader.config_location).to eq("#{cwd}/config.rb") + end + + + context "and/or KNIFE_HOME is set" do + + let(:knife_home) { "/path/to/knife/home" } + + before do + env["KNIFE_HOME"] = knife_home + allow(config_loader).to receive(:path_exists?).with("#{knife_home}/knife.rb").and_return(true) + end + + it "prefers a knife located in KNIFE_HOME" do + expect(config_loader.config_location).to eq("/path/to/knife/home/knife.rb") + end + + context "and KNIFE_HOME contains a config.rb" do + + before do + env["KNIFE_HOME"] = knife_home + allow(config_loader).to receive(:path_exists?).with("#{knife_home}/config.rb").and_return(true) + end + + it "prefers a config.rb located in KNIFE_HOME" do + expect(config_loader.config_location).to eq("/path/to/knife/home/config.rb") + end + + end + + end + end + end + end + end + end + end + + context "when the current working dir is inside a symlinked directory" do + before do + # pwd according to your shell is /home/someuser/prod/chef-repo, but + # chef-repo is a symlink to /home/someuser/codes/chef-repo + env["CD"] = "/home/someuser/prod/chef-repo" # windows + env["PWD"] = "/home/someuser/prod/chef-repo" # unix + + Dir.stub(:pwd).and_return("/home/someuser/codes/chef-repo") + end + + it "loads the config from the non-dereferenced directory path" do + expect(File).to receive(:exist?).with("/home/someuser/prod/chef-repo/.chef").and_return(false) + expect(File).to receive(:exist?).with("/home/someuser/prod/.chef").and_return(true) + expect(File).to receive(:directory?).with("/home/someuser/prod/.chef").and_return(true) + + expect(config_loader).to receive(:path_exists?).with("/home/someuser/prod/.chef/knife.rb").and_return(true) + + expect(config_loader.config_location).to eq("/home/someuser/prod/.chef/knife.rb") + end + end + end + + context "when given an explicit config to load" do + + let(:explicit_config_location) { "/path/to/explicit/config.rb" } + + it "prefers the explicit config" do + expect(config_loader.config_location).to eq(explicit_config_location) + end + + end + end + + + describe "loading the config file" do + + context "when no explicit config is specifed and no implicit config is found" do + + before do + allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false) + end + + it "skips loading" do + expect(config_loader.config_location).to be(nil) + expect(config_loader.load).to be(false) + end + + end + + context "when an explict config is given but it doesn't exist" do + + let(:explicit_config_location) { "/nope/nope/nope/frab/jab/nab" } + + it "raises a configuration error" do + expect { config_loader.load }.to raise_error(Chef::Exceptions::ConfigurationError) + end + + end + + context "when the config file exists" do + + let(:config_content) { "" } + + let(:explicit_config_location) do + t = Tempfile.new("#{described_class}-rspec-test") + t.print(config_content) + t.close + t.path + end + + after { File.unlink(explicit_config_location) } + + context "and is valid" do + + let(:config_content) { "config_file_evaluated(true)" } + + it "loads the config" do + expect(config_loader.load).to be(true) + expect(Chef::Config.config_file_evaluated).to be(true) + end + + it "sets Chef::Config.config_file" do + config_loader.load + expect(Chef::Config.config_file).to eq(explicit_config_location) + end + end + + context "and has a syntax error" do + + let(:config_content) { "{{{{{:{{" } + + it "raises a ConfigurationError" do + expect { config_loader.load }.to raise_error(Chef::Exceptions::ConfigurationError) + end + end + + context "and raises a ruby exception during evaluation" do + + let(:config_content) { ":foo\n:bar\nraise 'oops'\n:baz\n" } + + it "raises a ConfigurationError" do + expect { config_loader.load }.to raise_error(Chef::Exceptions::ConfigurationError) + end + end + + end + + end + +end |