Class: Puppet::Provider::AixObject

Inherits:
Puppet::Provider show all
Defined in:
lib/puppet/provider/aix_object.rb

Overview

Common code for AIX user/group providers.

Defined Under Namespace

Classes: MappedObject

Constant Summary

Constants inherited from Puppet::Provider

Confine

Constants included from Util

Util::ALNUM, Util::ALPHA, Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE, Util::ESCAPED, Util::HEX, Util::HttpProxy, Util::PUPPET_STACK_INSERTION_FRAME, Util::RESERVED, Util::RFC_3986_URI_REGEX, Util::UNRESERVED, Util::UNSAFE

Constants included from Util::POSIX

Util::POSIX::LOCALE_ENV_VARS, Util::POSIX::USER_ENV_VARS

Constants included from Util::SymbolicFileMode

Util::SymbolicFileMode::SetGIDBit, Util::SymbolicFileMode::SetUIDBit, Util::SymbolicFileMode::StickyBit, Util::SymbolicFileMode::SymbolicMode, Util::SymbolicFileMode::SymbolicSpecialToBit

Constants included from Util::Docs

Util::Docs::HEADER_LEVELS

Instance Attribute Summary

Attributes inherited from Puppet::Provider

#resource

Attributes included from Util::Docs

#doc, #nodoc

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Puppet::Provider

#<=>, #clear, command, #command, commands, declared_feature?, default?, default_match, defaultfor, execpipe, #execpipe, execute, #execute, fact_match, feature_match, #flush, has_command, #initialize, initvars, #inspect, #name, notdefaultfor, optional_commands, post_resource_eval, prefetch, some_default_match, specificity, supports_parameter?, #to_s

Methods included from Util::Logging

#clear_deprecation_warnings, #debug, #deprecation_warning, #format_backtrace, #format_exception, #get_deprecation_offender, #log_and_raise, #log_deprecations_to_file, #log_exception, #puppet_deprecation_warning, #send_log, setup_facter_logging!, #warn_once

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, create_erb, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, format_backtrace_array, format_puppetstack_frame, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, resolve_stackframe, rfc2396_escape, safe_posix_fork, set_env, skip_external_facts, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, uri_unescape, which, withenv, withumask

Methods included from Util::POSIX

#get_posix_field, #gid, groups_of, #idfield, #methodbyid, #methodbyname, #search_posix_field, #uid

Methods included from Util::SymbolicFileMode

#display_mode, #normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods included from Util::Docs

#desc, #dochook, #doctable, #markdown_definitionlist, #markdown_header, #nodoc?, #pad, scrub

Methods included from Util::Warnings

clear_warnings, debug_once, maybe_log, notice_once, warnonce

Methods included from Confiner

#confine, #confine_collection, #suitable?

Methods included from Util::Errors

#adderrorcontext, #devfail, #error_context, error_location, error_location_with_space, error_location_with_unknowns, #exceptwrap, #fail

Constructor Details

This class inherits a constructor from Puppet::Provider

Class Method Details

.instancesObject


Provider API




291
292
293
294
295
# File 'lib/puppet/provider/aix_object.rb', line 291

def instances
  list_all.to_a.map! do |object|
    new({ :name => object[:name] })
  end
end

.list_all(ia_module_args = []) ⇒ Object

Lists all instances of the given object, taking in an optional set of ia_module arguments. Returns an array of hashes, each hash having the schema

{
  :name => <object_name>
  :id   => <object_id>
}


277
278
279
280
281
282
283
284
285
# File 'lib/puppet/provider/aix_object.rb', line 277

def list_all(ia_module_args = [])
  cmd = [command(:list), '-c', *ia_module_args, '-a', 'id', 'ALL']
  parse_aix_objects(execute(cmd)).to_a.map do |object|
    name = object[:name]
    id = object[:attributes].delete(:id)

    { name: name, id: id }
  end
end

.mapping(info = {}) ⇒ Object

Add a mapping from a Puppet property to an AIX attribute. The info must include:

* :puppet_property       -- The puppet property corresponding to this attribute
* :aix_attribute         -- The AIX attribute corresponding to this attribute. Defaults
                         to puppet_property if this is not provided.
* :property_to_attribute -- A lambda that converts a Puppet Property to an AIX attribute
                         value. Defaults to the identity function if not provided.
* :attribute_to_property -- A lambda that converts an AIX attribute to a Puppet property.
                         Defaults to the identity function if not provided.

NOTE: The lambdas for :property_to_attribute or :attribute_to_property can be ‘pure’ or ‘impure’. A ‘pure’ lambda is one that needs only the value to do the conversion, while an ‘impure’ lambda is one that requires the provider instance along with the value. ‘Pure’ lambdas have the interface ‘do |value| …’ while ‘impure’ lambdas have the interface ‘do |provider, value| …’.

NOTE: ‘Impure’ lambdas are useful in case we need to generate more specific error messages or pass-in instance-specific command-line arguments.



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/puppet/provider/aix_object.rb', line 96

def mapping(info = {})
  identity_fn = lambda { |x| x }
  info[:aix_attribute] ||= info[:puppet_property]
  info[:property_to_attribute] ||= identity_fn
  info[:attribute_to_property] ||= identity_fn

  mappings[:aix_attribute][info[:puppet_property]] = MappedObject.new(
    info[:aix_attribute],
    :convert_property_value,
    info[:property_to_attribute]
  )
  mappings[:puppet_property][info[:aix_attribute]] = MappedObject.new(
    info[:puppet_property],
    :convert_attribute_value,
    info[:attribute_to_property]
  )
end

.mappingsObject


Mappings




68
69
70
71
72
73
74
75
76
# File 'lib/puppet/provider/aix_object.rb', line 68

def mappings
  return @mappings if @mappings

  @mappings = {}
  @mappings[:aix_attribute] = {}
  @mappings[:puppet_property] = {}

  @mappings
end

.mk_resource_methodsObject

Defines the getter and setter methods for each Puppet property that’s mapped to an AIX attribute. We define only a getter for the :attributes property.

Provider subclasses should call this method after they’ve defined all of their <puppet_property> => <aix_attribute> mappings.



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/puppet/provider/aix_object.rb', line 149

def mk_resource_methods
  # Define the Getter methods for each of our properties + the attributes
  # property
  properties = [:attributes]
  properties += mappings[:aix_attribute].keys
  properties.each do |property|
    # Define the getter
    define_method(property) do
      get(property)
    end

    # We have a custom setter for the :attributes property,
    # so no need to define it.
    next if property == :attributes

    # Define the setter
    define_method("#{property}=".to_sym) do |value|
      set(property, value)
    end
  end
end

.numeric_mapping(info = {}) ⇒ Object

Creates a mapping from a purely numeric Puppet property to an attribute



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/puppet/provider/aix_object.rb', line 116

def numeric_mapping(info = {})
  property = info[:puppet_property]

  # We have this validation here b/c not all numeric properties
  # handle this at the property level (e.g. like the UID). Given
  # that, we might as well go ahead and do this validation for all
  # of our numeric properties. Doesn't hurt.
  info[:property_to_attribute] = lambda do |value|
    unless value.is_a?(Integer)
      raise ArgumentError, _("Invalid value %{value}: %{property} must be an Integer!") % { value: value, property: property }
    end

    value.to_s
  end

  # AIX will do the right validation to ensure numeric attributes
  # can't be set to non-numeric values, so no need for the extra clutter.
  info[:attribute_to_property] = lambda do |value|
    value.to_i
  end

  mapping(info)
end

.parse_aix_objects(output) ⇒ Object

Parses the AIX objects from the command output, returning an array of hashes with each hash having the following schema:

{
  :name       => <object_name>
  :attributes => <object_attributes>
}

Output should be of the form

#name:<attr1>:<attr2> ...
<name>:<value1>:<value2> ...
#name:<attr1>:<attr2> ...
<name>:<value1>:<value2> ...

NOTE: We need to parse the colon-formatted output in case we have space-separated attributes (e.g. ‘gecos’). “:” characters are escaped with a “#!”.



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/puppet/provider/aix_object.rb', line 244

def parse_aix_objects(output)
  # Object names cannot begin with '#', so we are safe to
  # split individual users this way. We do not have to worry
  # about an empty list either since there is guaranteed to be
  # at least one instance of an AIX object (e.g. at least one
  # user or one group on the system).
  _, *objects = output.chomp.split(/^#/)

  objects.map! do |object|
    attributes_line, values_line = object.chomp.split("\n")

    attributes = parse_colon_separated_list(attributes_line.chomp)
    attributes.map!(&:to_sym)

    values = parse_colon_separated_list(values_line.chomp)

    attributes_hash = Hash[attributes.zip(values)]

    object_name = attributes_hash.delete(:name)

    Hash[[[:name, object_name.to_s], [:attributes, attributes_hash]]]
  end

  objects
end

.parse_colon_separated_list(colon_list) ⇒ Object

Parses a colon-separated list. Example includes something like:

<item1>:<item2>:<item3>:<item4>

Returns an array of the parsed items, e.g.

[ <item1>, <item2>, <item3>, <item4> ]

Note that colons inside items are escaped by #!



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/puppet/provider/aix_object.rb', line 199

def parse_colon_separated_list(colon_list)
  # ALGORITHM:
  # Treat the colon_list as a list separated by '#!:' We will get
  # something like:
  #     [ <chunk1>, <chunk2>, ... <chunkn> ]
  #
  # Each chunk is now a list separated by ':' and none of the items
  # in each chunk contains an escaped ':'. Now, split each chunk on
  # ':' to get:
  #     [ [<piece11>, ..., <piece1n>], [<piece21>, ..., <piece2n], ... ]
  #
  # Now note that <item1> = <piece11>, <item2> = <piece12> in our original
  # list, and that <itemn> = <piece1n>#!:<piece21>. This is the main idea
  # behind what our inject method is trying to do at the end, except that
  # we replace '#!:' with ':' since the colons are no longer escaped.
  chunks = split_list(colon_list, '#!:')
  chunks.map! { |chunk| split_list(chunk, ':') }

  chunks.inject do |accum, chunk|
    left = accum.pop
    right = chunk.shift

    accum.push("#{left}:#{right}")
    accum += chunk

    accum
  end
end

.split_list(list, sep) ⇒ Object

This helper splits a list separated by sep into its corresponding items. Note that a key precondition here is that none of the items in the list contain sep.

Let A be the return value. Then one of our postconditions is:

A.join(sep) == list

NOTE: This function is only used by the parse_colon_separated_list function below. It is meant to be an inner lambda. The reason it isn’t here is so we avoid having to create a proc. object for the split_list lambda each time parse_colon_separated_list is invoked. This will happen quite often since it is used at the class level and at the instance level. Since this function is meant to be an inner lambda and thus not exposed anywhere else, we do not have any unit tests for it. These test cases are instead covered by the unit tests for parse_colon_separated_list



186
187
188
189
190
# File 'lib/puppet/provider/aix_object.rb', line 186

def split_list(list, sep)
  return [""] if list.empty?

  list.split(sep, -1)
end

Instance Method Details

#addcmd(attributes) ⇒ Object



344
345
346
347
# File 'lib/puppet/provider/aix_object.rb', line 344

def addcmd(attributes)
  attribute_args = attributes_to_args(attributes)
  [self.class.command(:add)] + ia_module_args + attribute_args + [@resource[:name]]
end

#attributes=(new_attributes) ⇒ Object

Modifies the attribute property. Note we raise an error if the user specified an AIX attribute corresponding to a Puppet property.



410
411
412
413
414
415
# File 'lib/puppet/provider/aix_object.rb', line 410

def attributes=(new_attributes)
  validate_new_attributes(new_attributes)
  modify_object(new_attributes)
rescue Puppet::ExecutionFailure => detail
  raise Puppet::Error, _("Could not set attributes on %{resource}[%{name}]: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end

#attributes_to_args(attributes) ⇒ Object

Converts the given attributes hash to CLI args.



327
328
329
330
331
# File 'lib/puppet/provider/aix_object.rb', line 327

def attributes_to_args(attributes)
  attributes.map do |attribute, value|
    "#{attribute}=#{value}"
  end
end

#createObject

Creates a new instance of the resource



460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/puppet/provider/aix_object.rb', line 460

def create
  attributes = @resource.should(:attributes) || {}
  validate_new_attributes(attributes)

  mappings[:aix_attribute].each do |property, aix_attribute|
    property_should = @resource.should(property)
    next if property_should.nil?
    attributes[aix_attribute.name] = aix_attribute.convert_property_value(property_should)
  end

  execute(addcmd(attributes))
rescue Puppet::ExecutionFailure => detail
  raise Puppet::Error, _("Could not create %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end

#deleteObject

Deletes this instance resource



476
477
478
479
480
481
482
483
484
485
# File 'lib/puppet/provider/aix_object.rb', line 476

def delete
  execute(deletecmd)

  # Recollect the object info so that our current properties reflect
  # the actual state of the system. Otherwise, puppet resource reports
  # the wrong info. at the end. Note that this should return nil.
  object_info(true)
rescue Puppet::ExecutionFailure => detail
  raise Puppet::Error, _("Could not delete %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end

#deletecmdObject



349
350
351
# File 'lib/puppet/provider/aix_object.rb', line 349

def deletecmd
  [self.class.command(:delete)] + ia_module_args + [@resource[:name]]
end

#exists?Boolean

Check that the AIX object exists

Returns:

  • (Boolean)


455
456
457
# File 'lib/puppet/provider/aix_object.rb', line 455

def exists?
  ! object_info.nil?
end

#get(property) ⇒ Object

Gets a Puppet property’s value from object_info



365
366
367
368
# File 'lib/puppet/provider/aix_object.rb', line 365

def get(property)
  return :absent unless exists?
  object_info[property] || :absent
end

#ia_module_argsObject

Raises:

  • (ArgumentError)


333
334
335
336
337
338
# File 'lib/puppet/provider/aix_object.rb', line 333

def ia_module_args
  raise ArgumentError, _("Cannot have both 'forcelocal' and 'ia_load_module' at the same time!") if @resource[:ia_load_module] && @resource[:forcelocal]
  return ["-R", @resource[:ia_load_module].to_s] if @resource[:ia_load_module]
  return ["-R", "files"] if @resource[:forcelocal]
  []
end

#lscmdObject



340
341
342
# File 'lib/puppet/provider/aix_object.rb', line 340

def lscmd
  [self.class.command(:list), '-c'] + ia_module_args + [@resource[:name]]
end

#mappingsObject

Instantiate our mappings. These need to be at the instance-level since some of our mapped objects may have impure conversion functions that need our provider instance.



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/puppet/provider/aix_object.rb', line 301

def mappings
  return @mappings if @mappings
  
  @mappings = {}
  self.class.mappings.each do |type, mapped_objects|
    @mappings[type] = {}
    mapped_objects.each do |input, mapped_object|
      if mapped_object.pure_conversion_fn?
        # Our mapped_object has a pure conversion function so we
        # can go ahead and use it as-is.
        @mappings[type][input] = mapped_object
        next
      end

      # Otherwise, we need to dup it and set its provider to our
      # provider instance. The dup is necessary so that we do not
      # touch the class-level mapped object.
      @mappings[type][input] = mapped_object.dup
      @mappings[type][input].set_provider(self)
    end
  end

  @mappings
end

#modify_object(new_attributes) ⇒ Object

Modifies the AIX object by setting its new attributes.



359
360
361
362
# File 'lib/puppet/provider/aix_object.rb', line 359

def modify_object(new_attributes)
  execute(modifycmd(new_attributes))
  object_info(true) 
end

#modifycmd(new_attributes) ⇒ Object



353
354
355
356
# File 'lib/puppet/provider/aix_object.rb', line 353

def modifycmd(new_attributes)
  attribute_args = attributes_to_args(new_attributes)
  [self.class.command(:modify)] + ia_module_args + attribute_args + [@resource[:name]]
end

#object_info(refresh = false) ⇒ Object

Collects the current property values of all mapped properties + the attributes property.



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/puppet/provider/aix_object.rb', line 419

def object_info(refresh = false)
  return @object_info if @object_info && ! refresh
  @object_info = nil

  begin
    output = execute(lscmd)
  rescue Puppet::ExecutionFailure
    Puppet.debug(_("aix.object_info(): Could not find %{resource}[%{name}]") % { resource: @resource.class.name, name: @resource.name })

    return @object_info
  end

  # If lscmd succeeds, then output will contain our object's information.
  # Thus, .parse_aix_objects will always return a single element array.
  aix_attributes = self.class.parse_aix_objects(output).first[:attributes]
  aix_attributes.each do |attribute, value|
    @object_info ||= {}

    # If our attribute has a Puppet property, then we store that. Else, we store it as part
    # of our :attributes property hash
    if (property = mappings[:puppet_property][attribute])
      @object_info[property.name] = property.convert_attribute_value(value)
    else
      @object_info[:attributes] ||= {}
      @object_info[:attributes][attribute] = value
    end
  end

  @object_info
end

#set(property, value) ⇒ Object

Sets a mapped Puppet property’s value.



371
372
373
374
375
376
377
378
# File 'lib/puppet/provider/aix_object.rb', line 371

def set(property, value)
  aix_attribute = mappings[:aix_attribute][property]
  modify_object(
    { aix_attribute.name => aix_attribute.convert_property_value(value) }
  )
rescue Puppet::ExecutionFailure => detail
  raise Puppet::Error, _("Could not set %{property} on %{resource}[%{name}]: %{detail}") % { property: property, resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end

#validate_new_attributes(new_attributes) ⇒ Object

This routine validates our new attributes property value to ensure that it does not contain any Puppet properties.

Raises:



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/puppet/provider/aix_object.rb', line 382

def validate_new_attributes(new_attributes)
  # Gather all of the <puppet property>, <aix attribute> conflicts to print
  # them all out when we create our error message. This makes it easy for the
  # user to update their manifest based on our error message.
  conflicts = {}
  mappings[:aix_attribute].each do |property, aix_attribute|
    next unless new_attributes.key?(aix_attribute.name)

    conflicts[:properties] ||= []
    conflicts[:properties].push(property)

    conflicts[:attributes] ||= []
    conflicts[:attributes].push(aix_attribute.name)
  end

  return if conflicts.empty?

  properties, attributes = conflicts.keys.map do |key|
    conflicts[key].map! { |name| "'#{name}'" }.join(', ')
  end
    
  detail = _("attributes is setting the %{properties} properties via. the %{attributes} attributes, respectively! Please specify these property values in the resource declaration instead.") % { properties: properties, attributes: attributes }

  raise Puppet::Error, _("Could not set attributes on %{resource}[%{name}]: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }
end