diff --git a/lib/puppet/provider/dsc_base_provider/dsc_base_provider.rb b/lib/puppet/provider/dsc_base_provider/dsc_base_provider.rb index 7b643537..4a246ca9 100644 --- a/lib/puppet/provider/dsc_base_provider/dsc_base_provider.rb +++ b/lib/puppet/provider/dsc_base_provider/dsc_base_provider.rb @@ -150,7 +150,12 @@ def get(context, names = nil) state_from_test = resource_mode_state_from_test(context, name) next [state_from_test] unless state_from_test.nil? - [invoke_get_method(context, name.merge(mandatory_get_properties(context, name)))] + current = invoke_get_method(context, name.merge(mandatory_get_properties(context, name))) + # invoke_dsc_resource already logged the DSC error; returning nil makes the Resource API fail on + # "undefined method `[]' for nil" instead, so fail this resource with a readable message. + raise Puppet::ResourceError, "DSC Get failed for #{name[:name]}, see the error above" if current.nil? + + [current] end end @@ -274,7 +279,7 @@ def log_change_detail(context, name, is_value, should) # @param should [Hash] the desired state hash (used to extract query properties) # @return [Hash] returns a hash with dsc_ prefixed keys and current system values, or nil on failure def perform_fresh_get(context, name, should) - query_props = should.select { |k, v| mandatory_get_attributes(context).include?(k) || (k == :dsc_psdscrunascredential && !v.nil?) } + query_props = get_query_properties(context, should) data = invoke_dsc_resource(context, name, query_props, 'get') return nil if data.nil? @@ -410,9 +415,9 @@ def invoke_dsc_resource(context, name_hash, props, method) @cached_query_results << name_hash # if fetch_cached_hashes(@cached_query_results, [data]).empty? elsif error.match?(collision_error_matcher) context.notice('Invoke-DscResource collision detected: Please stagger the timing of your Puppet runs as this can lead to unexpected behaviour.') - retry_invoke_dsc_resource(context, 5, 60, collision_error_matcher) do - data = ps_manager.execute(remove_secret_identifiers(script_content))[:stdout] - end + retried = retry_invoke_dsc_resource(context, 5, 60, collision_error_matcher) { ps_manager.execute(remove_secret_identifiers(script_content), @timeout)[:stdout] } + # A retry that succeeded is a good result. + return retried if retried.is_a?(Hash) && retried['errormessage'].nil? else context.err(error) end @@ -448,7 +453,11 @@ def retry_invoke_dsc_resource(context, max_retry_count, retry_wait_interval_secs sleep retry_wait_interval_secs # notify and retry context.notice("Retrying: attempt #{try} of #{max_retry_count}.") - data = JSON.parse(yield) + stdout = yield + # The retry itself can time out: nothing to parse then. + return context.err('Nothing returned.') if stdout.nil? + + data = JSON.parse(stdout) # if no error, assume successful invocation and break break if data['errormessage'].nil? @@ -598,6 +607,8 @@ def insync?(context, name, property_name, _is_hash, should_hash) # Returns the properties that Get needs besides the namevars (and the credential, if any), taken # from the canonicalized resource matching the name hash, so that each resource gets its own # values. Falls back on the first canonicalized resource, as before, when none matches. + # In resource validation mode, the matching resource's other DSC properties and its validation mode + # are added as well, for get_query_properties; never those of the fallback resource. # # @param context [Object] the Puppet runtime context to operate in and send feedback to # @param name [Hash] the name hash for the resource @@ -605,13 +616,16 @@ def insync?(context, name, property_name, _is_hash, should_hash) def mandatory_get_properties(context, name) return {} if @cached_canonicalized_resource.empty? - canonicalized_resource = @cached_canonicalized_resource.find { |resource| (name.to_a - resource.to_a).empty? } || - @cached_canonicalized_resource[0] + matching_resource = @cached_canonicalized_resource.find { |resource| (name.to_a - resource.to_a).empty? } + canonicalized_resource = matching_resource || @cached_canonicalized_resource[0] mandatory_properties = canonicalized_resource.select do |attribute, _value| (mandatory_get_attributes(context) - namevar_attributes(context)).include?(attribute) end # If dsc_psdscrunascredential was specified, re-add it here. mandatory_properties[:dsc_psdscrunascredential] = canonicalized_resource[:dsc_psdscrunascredential] if canonicalized_resource.key?(:dsc_psdscrunascredential) + if matching_resource && matching_resource[:validation_mode] == 'resource' + mandatory_properties.merge!(matching_resource.select { |attribute, value| attribute == :validation_mode || (attribute.to_s.start_with?('dsc_') && !value.nil?) }) + end mandatory_properties end @@ -632,6 +646,29 @@ def cached_get_results(name) canon_results end + # Returns the properties passed to the DSC Get method: the mandatory Get properties and the + # credential, if any. In resource validation mode, every other DSC property set in the manifest is + # passed too, as the LCM does: some resources need them in Get (SqlServerDsc SqlScript connects with + # its Encrypt property, the class-based SqlPermission asserts that a permission property is set). + # DSC Test decides the sync state in that mode, so a Get that echoes a desired value cannot hide a drift. + # + # @param context [Object] the Puppet runtime context to operate in and send feedback to + # @param hash [Hash] the name hash or should hash of the resource + # @return [Hash] the properties to pass to Invoke-DscResource + def get_query_properties(context, hash) + query_props = hash.select { |k, v| mandatory_get_attributes(context).include?(k) || (k == :dsc_psdscrunascredential && !v.nil?) } + return query_props unless hash[:validation_mode] == 'resource' + + attributes = context.type.attributes + hash.each do |attribute, value| + next if value.nil? || query_props.key?(attribute) || !attribute.to_s.start_with?('dsc_') + next unless attributes.key?(attribute) && attributes[attribute][:behaviour].nil? + + query_props[attribute] = value + end + query_props + end + # Resource validation mode: DSC Test decides whether the resource is in the desired state, so when it # passes, the desired values are the current state and no Get call is needed (one DSC call instead of # two for an in-sync resource). When Test fails, the caller falls back on the Get method, to report @@ -768,7 +805,7 @@ def fresh_value_equal?(context, property_name, fresh_value, should_value) def invoke_get_method(context, name_hash) context.debug("retrieving #{name_hash.inspect}") - query_props = name_hash.select { |k, v| mandatory_get_attributes(context).include?(k) || (k == :dsc_psdscrunascredential && !v.nil?) } + query_props = get_query_properties(context, name_hash) data = invoke_dsc_resource(context, name_hash, query_props, 'get') return nil if data.nil? @@ -845,6 +882,7 @@ def canonicalize_get_value!(context, data, type_key, query_props) if data[type_key].is_a?(Enumerable) downcase_hash_keys!(data[type_key]) munge_cim_instances!(data[type_key]) + data[type_key] = fill_required_arrays(data[type_key], attribute_type(context, type_key)) if context.type.attributes[type_key][:mof_is_embedded] end # Convert DateTime back to appropriate type @@ -856,11 +894,66 @@ def canonicalize_get_value!(context, data, type_key, query_props) nil end end + # PowerShell serializes a whole Real32/Real64 value without its decimal part (0, not 0.0), and the + # Float type of the attribute rejects an Integer. + data[type_key] = whole_to_float(data[type_key]) if /\AReal(32|64)/i.match?(context.type.attributes[type_key][:mof_type]) # PowerShell does not distinguish between a return of empty array/string # and null but Puppet does; revert to those values if specified. data[type_key] = [] if data[type_key].nil? && query_props.key?(type_key) && query_props[type_key].is_a?(Array) end + # Returns the parsed Puppet type of an attribute, cached per attribute, or nil when it cannot be parsed + # (the value is then returned unchanged). + def attribute_type(context, attribute) + @attribute_types ||= {} + return @attribute_types[attribute] if @attribute_types.key?(attribute) + + @attribute_types[attribute] = begin + Puppet::Pops::Types::TypeParser.singleton.parse(context.type.attributes[attribute][:type]) + rescue StandardError => e + context.debug("Could not parse the type of #{attribute}: #{e.message}") + nil + end + end + + # PowerShell returns $null for an empty array, so a CIM instance field typed as a required Array + # comes back nil (SqlServerDsc SqlPermission returns `Permission = $null` for the states without + # permissions), which the type rejects. Returns the value with those fields set to an empty array, + # at any nesting level; optional fields are left alone. + # + # @param value [Object] the value returned by DSC Get, keys already downcased + # @param type [Puppet::Pops::Types::PAnyType] the Puppet type of the value + # @return [Object] the value with the required array fields filled + def fill_required_arrays(value, type) + type = type.optional_type while type.is_a?(Puppet::Pops::Types::POptionalType) && !type.optional_type.nil? + case type + when Puppet::Pops::Types::PArrayType + value.is_a?(Array) ? value.map { |item| fill_required_arrays(item, type.element_type) } : value + when Puppet::Pops::Types::PStructType + return value unless value.is_a?(Hash) + + type.elements.each_with_object(value.dup) do |element, result| + key = result.keys.find { |k| k.to_s.casecmp?(element.name) } + if key.nil? || result[key].nil? + result[key || element.name.downcase] = [] if element.value_type.is_a?(Puppet::Pops::Types::PArrayType) + else + result[key] = fill_required_arrays(result[key], element.value_type) + end + end + else + value + end + end + + # Converts an Integer, or the Integers of an array, to Float. + def whole_to_float(value) + case value + when Integer then value.to_f + when Array then value.map { |item| whole_to_float(item) } + else value + end + end + # Sanitize .NET serialization artifacts (e.g., "System.Object[]") to nil. def sanitize_dotnet_artifacts!(context, data) data.each do |key, value| @@ -892,7 +985,12 @@ def invoke_set_method(context, name, should) context.debug("Invoking Set Method for '#{name}' with #{should.inspect}") apply_props = should.select { |k, _v| k.to_s =~ /^dsc_/ } - invoke_dsc_resource(context, should, apply_props, 'set') + result = invoke_dsc_resource(context, should, apply_props, 'set') + # invoke_dsc_resource already logged the DSC error; without raising, the Resource API reports the resource + # as changed and its dependents run as if the Set had worked. + raise Puppet::ResourceError, "DSC Set failed for #{name[:name]}, see the error above" if result.nil? + + result # TODO: Implement this functionality for notifying a DSC reboot? # notify_reboot_pending if data['rebootrequired'] == true diff --git a/spec/unit/puppet/provider/dsc_base_provider/dsc_base_provider_spec.rb b/spec/unit/puppet/provider/dsc_base_provider/dsc_base_provider_spec.rb index da042d2c..2d0a56fa 100644 --- a/spec/unit/puppet/provider/dsc_base_provider/dsc_base_provider_spec.rb +++ b/spec/unit/puppet/provider/dsc_base_provider/dsc_base_provider_spec.rb @@ -314,6 +314,95 @@ expect(provider).to receive(:invoke_get_method).with(context, { name: 'bar' }).and_return({ name: 'bar', dsc_setting: 'Bar' }) expect(provider.get(context, [{ name: 'foo' }, { name: 'bar' }])).to eq([{ name: 'foo', dsc_setting: 'Foo' }, { name: 'bar', dsc_setting: 'Bar' }]) end + + it 'adds the other DSC properties of the matching resource in the resource validation mode' do + provider.instance_variable_set(:@cached_canonicalized_resource, [{ name: 'foo', validation_mode: 'resource', dsc_path: 'C:\\foo', dsc_encrypt: 'Optional', dsc_unset: nil, noop: true }]) + allow(context).to receive(:debug) + allow(provider).to receive_messages(fetch_cached_hashes: [], namevar_attributes: [:name], mandatory_get_attributes: [:dsc_path], resource_mode_state_from_test: nil) + expect(provider).to receive(:invoke_get_method) + .with(context, { name: 'foo', validation_mode: 'resource', dsc_path: 'C:\\foo', dsc_encrypt: 'Optional' }).and_return({ name: 'foo' }) + provider.get(context, [{ name: 'foo' }]) + end + + it 'does not add the properties of the fallback resource in the resource validation mode' do + provider.instance_variable_set(:@cached_canonicalized_resource, [{ name: 'foo', validation_mode: 'resource', dsc_path: 'C:\\foo', dsc_encrypt: 'Optional' }]) + allow(context).to receive(:debug) + allow(provider).to receive_messages(fetch_cached_hashes: [], namevar_attributes: [:name], mandatory_get_attributes: [:dsc_path], resource_mode_state_from_test: nil) + expect(provider).to receive(:invoke_get_method).with(context, { name: 'bar', dsc_path: 'C:\\foo' }).and_return({ name: 'bar' }) + provider.get(context, [{ name: 'bar' }]) + end + + it 'fails the resource with a readable error when the DSC Get call fails' do + provider.instance_variable_set(:@cached_canonicalized_resource, []) + allow(context).to receive(:debug) + allow(provider).to receive_messages(fetch_cached_hashes: [], namevar_attributes: [:name], mandatory_get_attributes: [], invoke_get_method: nil) + expect { provider.get(context, [{ name: 'foo' }]) }.to raise_error(Puppet::ResourceError, /DSC Get failed for foo/) + end + end + + describe '.get_query_properties' do + let(:attributes) do + { + name: { type: 'String', behaviour: :namevar }, + dsc_name: { type: 'String', behaviour: :namevar, mandatory_for_get: true }, + dsc_encrypt: { type: 'Optional[String]' }, + dsc_unset: { type: 'Optional[String]' }, + dsc_timeout: { type: 'Optional[Integer]', behaviour: :parameter }, + dsc_psdscrunascredential: { type: 'Optional[Hash]', behaviour: :parameter } + } + end + let(:hash) { { name: 'foo', dsc_name: 'foo', dsc_encrypt: 'Optional', dsc_unset: nil, dsc_timeout: 600, dsc_psdscrunascredential: nil } } + + before do + allow(context).to receive(:type).and_return(type) + allow(type).to receive(:attributes).and_return(attributes) + allow(provider).to receive(:mandatory_get_attributes).and_return([:dsc_name]) + end + + it 'returns only the mandatory Get properties in the property validation mode' do + expect(provider.send(:get_query_properties, context, hash)).to eq({ dsc_name: 'foo' }) + end + + it 'adds the other DSC properties set in the manifest in the resource validation mode' do + expect(provider.send(:get_query_properties, context, hash.merge(validation_mode: 'resource'))).to eq({ dsc_name: 'foo', dsc_encrypt: 'Optional' }) + end + end + + describe '.whole_to_float' do + it 'converts integers, also inside arrays, and leaves other values alone' do + expect(provider.whole_to_float(0)).to be_a(Float).and(eq(0.0)) + expect(provider.whole_to_float([1, 2.5])).to eql([1.0, 2.5]) + expect(provider.whole_to_float(nil)).to be_nil + end + end + + describe '.fill_required_arrays' do + let(:type) do + Puppet::Pops::Types::TypeParser.singleton.parse( + 'Optional[Array[Struct[{ permission => Array[String], state => String, Optional[note] => Optional[Array[String]] }]]]' + ) + end + + it 'returns a nil required array field as an empty array and leaves optional fields alone' do + value = [{ 'permission' => ['ConnectSql'], 'state' => 'Grant' }, { 'permission' => nil, 'state' => 'Deny', 'note' => nil }] + expect(provider.fill_required_arrays(value, type)).to eq( + [{ 'permission' => ['ConnectSql'], 'state' => 'Grant' }, { 'permission' => [], 'state' => 'Deny', 'note' => nil }] + ) + end + + it 'leaves a nil value alone' do + expect(provider.fill_required_arrays(nil, type)).to be_nil + end + end + + describe '.canonicalize_get_value!' do + it 'returns a whole Real64 value as a Float, as the type expects' do + allow(context).to receive(:type).and_return(type) + allow(type).to receive(:attributes).and_return({ dsc_maxsizeinbytes: { type: 'Optional[Float]', mof_type: 'Real64', mof_is_embedded: false } }) + data = { dsc_maxsizeinbytes: 0 } + provider.canonicalize_get_value!(context, data, :dsc_maxsizeinbytes, {}) + expect(data[:dsc_maxsizeinbytes]).to be_a(Float).and(eq(0.0)) + end end describe '.get in the resource validation mode' do @@ -339,7 +428,8 @@ it 'calls the Get method when DSC Test fails' do expect(provider).to receive(:invoke_test_method).and_return([false, 'not in the desired state']) - expect(provider).to receive(:invoke_get_method).with(context, { name: 'foo' }).and_return({ name: 'foo', dsc_setting: 'Bar' }) + expect(provider).to receive(:invoke_get_method) + .with(context, { name: 'foo', dsc_name: 'foo', dsc_setting: 'Foo', validation_mode: 'resource' }).and_return({ name: 'foo', dsc_setting: 'Bar' }) expect(provider.get(context, [{ name: 'foo' }])).to eq([{ name: 'foo', dsc_setting: 'Bar' }]) end @@ -1558,26 +1648,27 @@ def insync_with(actual) context 'when the specified account has already failed to logon' do let(:should_hash) { name.merge(dsc_psdscrunascredential: 'bar') } - it 'returns immediately' do + it 'fails the resource without invoking DSC' do expect(provider).to receive(:logon_failed_already?).and_return(true) expect(context).to receive(:err).with('Logon credentials are invalid') - expect(result).to be_nil + expect(ps_manager).not_to receive(:execute) + expect { result }.to raise_error(Puppet::ResourceError, /DSC Set failed for foo/) end end context 'when the invocation script returns nil' do - it 'errors via context but does not raise' do + it 'errors via context and fails the resource' do expect(ps_manager).to receive(:execute).and_return({ stdout: nil }) expect(context).to receive(:err).with('Nothing returned.') - expect { result }.not_to raise_error + expect { result }.to raise_error(Puppet::ResourceError, /DSC Set failed for foo/) end end context 'when the invocation script errors' do - it 'writes the error via context but does not raise and returns nil' do + it 'writes the error via context and fails the resource' do expect(ps_manager).to receive(:execute).and_return({ stdout: '{"errormessage": "DSC Error!"}' }) expect(context).to receive(:err).with('DSC Error!') - expect(result).to be_nil + expect { result }.to raise_error(Puppet::ResourceError, /DSC Set failed for foo/) end end @@ -1591,7 +1682,7 @@ def insync_with(actual) expect(context).to receive(:notice).with('Attempt 1 of 5 failed.') allow(provider).to receive(:sleep) expect(ps_manager).to receive(:execute).and_return({ stdout: '{"errormessage": null}' }) - expect { result }.not_to raise_error + expect(result).to eq({ 'errormessage' => nil }) end it 'writes a error via context and fails to apply when all retry attempts used' do @@ -1604,7 +1695,7 @@ def insync_with(actual) expect(context).to receive(:notice).with(/Attempt [1-5] of 5 failed/).exactly(5).times expect(context).to receive(:err).with(/The Invoke-DscResource cmdlet is in progress and must return before Invoke-DscResource can be invoked/) allow(provider).to receive(:sleep) - expect(result).to be_nil + expect { result }.to raise_error(Puppet::ResourceError, /DSC Set failed for foo/) end it 'writes an error via context and fails to apply when encountering an unexpected error' do @@ -1616,7 +1707,18 @@ def insync_with(actual) expect(ps_manager).to receive(:execute).and_return({ stdout: '{"errormessage": "Some unexpected error"}' }).once expect(context).to receive(:notice).with(/Attempt 1 of 5 failed/).once expect(context).to receive(:err).with(/Some unexpected error/) - expect(result).to be_nil + expect { result }.to raise_error(Puppet::ResourceError, /DSC Set failed for foo/) + end + + it 'writes an error via context and fails to apply when a retry returns nothing' do + expect(ps_manager).to receive(:execute).and_return({ stdout: '{"errormessage": "The Invoke-DscResource cmdlet is in progress and must return before Invoke-DscResource can be invoked"}' }) + expect(context).to receive(:notice).with(/Invoke-DscResource collision detected/).once + expect(context).to receive(:notice).with('Sleeping for 60 seconds.').once + expect(context).to receive(:notice).with(/Retrying: attempt 1 of 5/).once + allow(provider).to receive(:sleep) + expect(ps_manager).to receive(:execute).and_return({ stdout: nil }).once + expect(context).to receive(:err).with('Nothing returned.') + expect { result }.to raise_error(Puppet::ResourceError, /DSC Set failed for foo/) end end