summaryrefslogtreecommitdiff
path: root/lib/chef/provider/dsc_script.rb
blob: 5d7322842c456d5cf0f08e5b7d582779a9da5246 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#
# Author:: Adam Edwards (<adamed@getchef.com>)
#
# Copyright:: 2014, Chef Software, Inc.
#
# 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/util/powershell/cmdlet'
require 'chef/util/dsc/configuration_generator'
require 'chef/util/dsc/local_configuration_manager'

class Chef
  class Provider
    class DscScript < Chef::Provider
      def initialize(dsc_resource, run_context)
        super(dsc_resource, run_context)
        @dsc_resource = dsc_resource
        @resource_converged = false
        @operations = {
          :set => Proc.new { |config_manager, document|
            config_manager.set_configuration(document)
          },
          :test => Proc.new { |config_manager, document|
            config_manager.test_configuration(document)
          }}
      end

      def action_run
        if ! @resource_converged
          converge_by(generate_description) do
            run_configuration(:set)
            Chef::Log.info("DSC resource configuration completed successfully")
          end
        end
      end

      def load_current_resource
        @dsc_resources_info = run_configuration(:test)
        @resource_converged = @dsc_resources_info.all? do |resource|
          !resource.changes_state?
        end
      end

      def whyrun_supported?
        true
      end

      protected

      def run_configuration(operation)
        config_directory = ::Dir.mktmpdir("chef-dsc-script")
        configuration_data_path = get_configuration_data_path(config_directory)
        configuration_flags = get_augmented_configuration_flags(configuration_data_path)

        config_manager = Chef::Util::DSC::LocalConfigurationManager.new(@run_context.node, config_directory)

        begin
          configuration_document = generate_configuration_document(config_directory, configuration_flags)
          @operations[operation].call(config_manager, configuration_document)
        rescue Exception => e
          Chef::Log.error("DSC operation failed: #{e.message.to_s}")
          raise e
        ensure
          ::FileUtils.rm_rf(config_directory)
        end
      end

      def get_augmented_configuration_flags(configuration_data_path)
        updated_flags = nil
        if configuration_data_path
          updated_flags = @dsc_resource.flags.nil? ? {} : @dsc_resource.flags.dup
          Chef::Util::PathHelper.validate_path(configuration_data_path)
          updated_flags[:configurationdata] = configuration_data_path
        end
        updated_flags
      end

      def generate_configuration_document(config_directory, configuration_flags)
        shellout_flags = {
          :cwd => @dsc_resource.cwd,
          :environment => @dsc_resource.environment,
          :timeout => @dsc_resource.timeout
        }

        generator = Chef::Util::DSC::ConfigurationGenerator.new(@run_context.node, config_directory)

        if @dsc_resource.command
          generator.configuration_document_from_script_path(@dsc_resource.command, configuration_name, configuration_flags, shellout_flags)
        else
          # If code is also not provided, we mimic what the other script resources do (execute nothing)
          Chef::Log.warn("Neither code or command were provided for dsc_resource[#{@dsc_resource.name}].") unless @dsc_resource.code
          generator.configuration_document_from_script_code(@dsc_resource.code || '', configuration_flags, shellout_flags)
        end
      end

      def get_configuration_data_path(config_directory)
        if @dsc_resource.configuration_data_script
          @dsc_resource.configuration_data_script
        elsif @dsc_resource.configuration_data
          configuration_data_path = "#{config_directory}/chef_dsc_config_data.psd1"
          ::File.open(configuration_data_path, 'wt') do | script |
            script.write(@dsc_resource.configuration_data)
          end
          configuration_data_path
        end
      end

      def configuration_name
        @dsc_resource.configuration_name || @dsc_resource.name
      end

      def configuration_friendly_name
        if @dsc_resource.code
          @dsc_resource.name
        else
          configuration_name
        end
      end

      private

      def generate_description
        ["converge DSC configuration '#{configuration_friendly_name}'"] +
          @dsc_resources_info.map do |resource|
            if resource.changes_state?
              # We ignore the last log message because it only contains the time it took, which looks weird
              cleaned_messages = resource.change_log[0..-2].map { |c| c.sub(/^#{Regexp.escape(resource.name)}/, '').strip }
              "converge DSC resource #{resource.name} by #{cleaned_messages.find_all{ |c| c != ''}.join("\n")}"
            else
              # This is needed because a dsc script can have resouces that are both converged and not
              "converge DSC resource #{resource.name} by doing nothing because it is already converged"
            end
          end
      end
    end
  end
end