summaryrefslogtreecommitdiff
path: root/lib/chef/config_fetcher.rb
blob: 0e4a7935ac1733e1cd15675029fd497fc40cb03d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
require_relative "application"
require_relative "chef_fs/path_utils"
require_relative "http/simple"
require_relative "json_compat"

class Chef
  class ConfigFetcher

    attr_reader :config_location

    def initialize(config_location)
      @config_location = config_location
    end

    def expanded_path
      if config_location.nil? || remote_config?
        config_location
      else
        File.expand_path(config_location)
      end
    end

    def fetch_json
      config_data = read_config
      begin
        Chef::JSONCompat.from_json(config_data)
      rescue Chef::Exceptions::JSON::ParseError => error
        Chef::Application.fatal!("Could not parse the provided JSON file (#{config_location}): " + error.message)
      end
    end

    def read_config
      if remote_config?
        fetch_remote_config
      else
        read_local_config
      end
    end

    def fetch_remote_config
      http.get("")
    rescue SocketError, SystemCallError, Net::HTTPClientException => error
      Chef::Application.fatal!("Cannot fetch config '#{config_location}': '#{error.class}: #{error.message}")
    end

    def read_local_config
      ::File.read(config_location)
    rescue Errno::ENOENT
      Chef::Application.fatal!("Cannot load configuration from #{config_location}")
    rescue Errno::EACCES
      Chef::Application.fatal!("Permissions are incorrect on #{config_location}. Please chmod a+r #{config_location}")
    end

    def config_missing?
      return false if remote_config?

      # Check if the config file exists
      Pathname.new(config_location).realpath.to_s
      false
    rescue Errno::ENOENT
      true
    end

    def http
      Chef::HTTP::Simple.new(config_location)
    end

    def remote_config?
      !!(config_location =~ %r{^(http|https)://})
    end
  end
end