Class: Puppet::Parser::Compiler

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Puppet::Pops::Evaluator::Runtime3Support, Resource::TypeCollectionHelper, Util, Util::Errors, Util::MethodHelper
Defined in:
lib/puppet/parser/compiler.rb,
lib/puppet/parser/compiler/catalog_validator.rb,
lib/puppet/parser/compiler/catalog_validator/site_validator.rb,
lib/puppet/parser/compiler/catalog_validator/relationship_validator.rb,
lib/puppet/parser/compiler/catalog_validator/env_relationship_validator.rb

Overview

Abstract class for a catalog validator that can be registered with the compiler to run at a certain stage.

Direct Known Subclasses

EnvironmentCompiler

Defined Under Namespace

Classes: CatalogValidationError, CatalogValidator

Constant Summary

Constants included from Puppet::Pops::Evaluator::Runtime3Support

Puppet::Pops::Evaluator::Runtime3Support::CLASS_STRING, Puppet::Pops::Evaluator::Runtime3Support::NAME_SPACE_SEPARATOR

Constants included from Util

Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Puppet::Pops::Evaluator::Runtime3Support

#add_relationship, #call_function, #capitalize_qualified_name, #coerce_numeric, #convert, #create_local_scope_from, #create_match_scope_from, #create_resource_defaults, #create_resource_overrides, #create_resource_parameter, #create_resources, #diagnostic_producer, #external_call_function, #extract_file_line, #fail, #find_closest_positioned, #find_resource, #get_resource_parameter_value, #get_scope_nesting_level, #get_variable_value, #is_boolean?, #is_parameter_of_resource?, #is_true?, #optionally_fail, #resource_to_ptype, #set_match_data, #set_scope_nesting_level, #set_variable, #variable_bound?, #variable_exists?

Methods included from Resource::TypeCollectionHelper

#known_resource_types

Methods included from Util::MethodHelper

#requiredopts, #set_options, #symbolize_options

Methods included from Util::Errors

#adderrorcontext, #devfail, #error_context, #exceptwrap, #fail

Methods included from Util

absolute_path?, benchmark, chuser, deterministic_rand, deterministic_rand_int, exit_on_fail, logmethods, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, symbolizehash, thinmark, uri_to_path, which, withenv, withumask

Methods included from Util::POSIX

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

Methods included from Util::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Constructor Details

#initialize(node, options = {}) ⇒ Compiler

Returns a new instance of Compiler.



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/puppet/parser/compiler.rb', line 415

def initialize(node, options = {})
  @node = sanitize_node(node)
  # Array of resources representing all application instances we've found
  @applications = []
  # We use @current_app and @current_components to signal to the
  # evaluator that we are in the middle of evaluating an
  # application. They are set in evaluate_applications to the application
  # instance, resp. to an array of the components of that application
  # that is mapped to the current node. They are only non-nil when we are
  # in the middle of executing evaluate_applications
  @current_app = nil
  @current_components = nil
  set_options(options)
  initvars
  add_catalog_validators
end

Instance Attribute Details

#boot_injectorPuppet::Pops::Binder::Injector?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The injector that provides lookup services during the creation of the #injector.

Returns:



68
69
70
# File 'lib/puppet/parser/compiler.rb', line 68

def boot_injector
  @boot_injector
end

#catalogObject (readonly)



47
48
49
# File 'lib/puppet/parser/compiler.rb', line 47

def catalog
  @catalog
end

#code_idObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The id of code input to the compiler.



72
73
74
# File 'lib/puppet/parser/compiler.rb', line 72

def code_id
  @code_id
end

#collectionsObject (readonly)



47
48
49
# File 'lib/puppet/parser/compiler.rb', line 47

def collections
  @collections
end

#factsObject (readonly)



47
48
49
# File 'lib/puppet/parser/compiler.rb', line 47

def facts
  @facts
end

#injectorPuppet::Pops::Binder::Injector?

The injector that provides lookup services, or nil if accessed before the compiler has started compiling and bootstrapped. The injector is initialized and available before any manifests are evaluated.

Returns:



55
56
57
# File 'lib/puppet/parser/compiler.rb', line 55

def injector
  @injector
end

#loadersPuppet::Pops::Loader::Loaders (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Access to the configured loaders for 4x

Returns:

  • (Puppet::Pops::Loader::Loaders)

    the configured loaders



60
61
62
# File 'lib/puppet/parser/compiler.rb', line 60

def loaders
  @loaders
end

#nodeObject (readonly)



47
48
49
# File 'lib/puppet/parser/compiler.rb', line 47

def node
  @node
end

#relationshipsObject (readonly)



47
48
49
# File 'lib/puppet/parser/compiler.rb', line 47

def relationships
  @relationships
end

#resourcesObject (readonly)



47
48
49
# File 'lib/puppet/parser/compiler.rb', line 47

def resources
  @resources
end

#topscopeObject (readonly)



47
48
49
# File 'lib/puppet/parser/compiler.rb', line 47

def topscope
  @topscope
end

Class Method Details

.compile(node, code_id = nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/puppet/parser/compiler.rb', line 22

def self.compile(node, code_id = nil)
   $env_module_directories = nil
   node.environment.check_for_reparse

   errors = node.environment.validation_errors
   if !errors.empty?
     errors.each { |e| Puppet.err(e) } if errors.size > 1
     errmsg = [
       "Compilation has been halted because: #{errors.first}",
       "For more information, see http://docs.puppetlabs.com/puppet/latest/reference/environments.html",
     ]
     raise(Puppet::Error, errmsg.join(' '))
   end

   new(node, :code_id => code_id).compile {|resulting_catalog| resulting_catalog.to_resource }
 rescue Puppet::ParseErrorWithIssue => detail
   detail.node = node.name
   Puppet.log_exception(detail)
   raise
 rescue => detail
   message = "#{detail} on node #{node.name}"
   Puppet.log_exception(detail, message)
   raise Puppet::Error, message, detail.backtrace
end

Instance Method Details

#activate_binderBoolean

Answers if Puppet Binder should be active or not, and if it should and is not active, then it is activated.

Returns:

  • (Boolean)

    true if the Puppet Binder should be activated



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

def activate_binder
  # TODO: this should be in a central place
  Puppet::Parser::ParserFactory.assert_rgen_installed()
  @@binder_loaded ||= false
  unless @@binder_loaded
    require 'puppet/pops'
    require 'puppet/plugins/configuration'
    @@binder_loaded = true
  end
  true
end

#add_catalog_validator(catalog_validators) ⇒ Object

Add a catalog validator that will run at some stage to this compiler

Parameters:



153
154
155
156
# File 'lib/puppet/parser/compiler.rb', line 153

def add_catalog_validator(catalog_validators)
  @catalog_validators << catalog_validators
  nil
end

#add_catalog_validatorsObject



158
159
160
# File 'lib/puppet/parser/compiler.rb', line 158

def add_catalog_validators
  add_catalog_validator(CatalogValidator::RelationshipValidator)
end

#add_class(name) ⇒ Object

Store the fact that we’ve evaluated a class



147
148
149
# File 'lib/puppet/parser/compiler.rb', line 147

def add_class(name)
  @catalog.add_class(name) unless name == ""
end

#add_override(override) ⇒ Object

Store a resource override.



79
80
81
82
83
84
85
86
87
88
# File 'lib/puppet/parser/compiler.rb', line 79

def add_override(override)
  # If possible, merge the override in immediately.
  if resource = @catalog.resource(override.ref)
    resource.merge(override)
  else
    # Otherwise, store the override for later; these
    # get evaluated in Resource#finish.
    @resource_overrides[override.ref] << override
  end
end

#add_resource(scope, resource) ⇒ Object



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
# File 'lib/puppet/parser/compiler.rb', line 90

def add_resource(scope, resource)
  type = resource.resource_type
  if type.is_a?(Puppet::Resource::Type) && type.application?
    @applications << resource
    assert_app_in_site(scope, resource)
    return
  end

  if @current_app
    # We are in the process of pulling application components out that
    # apply to this node
    Puppet.notice "Check #{resource}"
    return unless @current_components.any? do |comp|
      comp.type == resource.type && comp.title == resource.title
    end
  end

  @resources << resource

  # Note that this will fail if the resource is not unique.
  @catalog.add_resource(resource)

  if not resource.class? and resource[:stage]
    raise ArgumentError, "Only classes can set 'stage'; normal resources like #{resource} cannot change run stage"
  end

  # Stages should not be inside of classes.  They are always a
  # top-level container, regardless of where they appear in the
  # manifest.
  return if resource.stage?

  # This adds a resource to the class it lexically appears in in the
  # manifest.
  unless resource.class?
    @catalog.add_edge(scope.resource, resource)
  end
end

#assert_app_in_site(scope, resource) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/puppet/parser/compiler.rb', line 128

def assert_app_in_site(scope, resource)
  if resource.type == 'App'
    if scope.resource
      # directly contained in a Site
      return if scope.resource.type == 'Site'
      # contained in something that may be contained in Site
      upstream = @catalog.upstream_from_vertex(scope.resource)
      if upstream
        return if upstream.keys.map(&:type).include?('Site')
      end
    end
    raise ArgumentError, "Application instances like '#{resource}' can only be contained within a Site"
  end
end

#compileObject

Compiler our catalog. This mostly revolves around finding and evaluating classes. This is the main entry into our catalog.



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/puppet/parser/compiler.rb', line 167

def compile
  Puppet.override( @context_overrides , "For compiling #{node.name}") do
    @catalog.environment_instance = environment

    # Set the client's parameters into the top scope.
    Puppet::Util::Profiler.profile("Compile: Set node parameters", [:compiler, :set_node_params]) { set_node_parameters }

    Puppet::Util::Profiler.profile("Compile: Created settings scope", [:compiler, :create_settings_scope]) { create_settings_scope }

    activate_binder

    Puppet::Util::Profiler.profile("Compile: Evaluated capability mappings", [:compiler, :evaluate_capability_mappings]) { evaluate_capability_mappings }

    Puppet::Util::Profiler.profile("Compile: Evaluated main", [:compiler, :evaluate_main]) { evaluate_main }

    Puppet::Util::Profiler.profile("Compile: Evaluated site", [:compiler, :evaluate_site]) { evaluate_site }

    Puppet::Util::Profiler.profile("Compile: Evaluated AST node", [:compiler, :evaluate_ast_node]) { evaluate_ast_node }

    Puppet::Util::Profiler.profile("Compile: Evaluated node classes", [:compiler, :evaluate_node_classes]) { evaluate_node_classes }

    Puppet::Util::Profiler.profile("Compile: Evaluated application instances", [:compiler, :evaluate_applications]) { evaluate_applications }

    # New capability mappings may have been defined when the site was evaluated
    Puppet::Util::Profiler.profile("Compile: Evaluated site capability mappings", [:compiler, :evaluate_capability_mappings]) { evaluate_capability_mappings }

    Puppet::Util::Profiler.profile("Compile: Evaluated generators", [:compiler, :evaluate_generators]) { evaluate_generators }

    Puppet::Util::Profiler.profile("Compile: Validate Catalog pre-finish", [:compiler, :validate_pre_finish]) do
      validate_catalog(CatalogValidator::PRE_FINISH)
    end

    Puppet::Util::Profiler.profile("Compile: Finished catalog", [:compiler, :finish_catalog]) { finish }

    Puppet::Util::Profiler.profile("Compile: Prune", [:compiler, :prune_catalog]) { prune_catalog }

    fail_on_unevaluated

    Puppet::Util::Profiler.profile("Compile: Validate Catalog final", [:compiler, :validate_final]) do
      validate_catalog(CatalogValidator::FINAL)
    end

    if block_given?
      yield @catalog
    else
      @catalog
    end
  end
end

#context_overridesObject

Constructs the overrides for the context



222
223
224
225
226
227
228
229
# File 'lib/puppet/parser/compiler.rb', line 222

def context_overrides()
  {
    :current_environment => environment,
    :global_scope => @topscope,             # 4x placeholder for new global scope
    :loaders  => lambda {|| loaders() },    # 4x loaders
    :injector => lambda {|| injector() }    # 4x API - via context instead of via compiler
  }
end

#create_boot_injector(env_boot_bindings) ⇒ Puppet::Pops::Binder::Injector

Creates the boot injector from registered system, default, and injector config.

Returns:



464
465
466
467
468
469
470
471
# File 'lib/puppet/parser/compiler.rb', line 464

def create_boot_injector(env_boot_bindings)
  assert_binder_active()
  pb = Puppet::Pops::Binder
  boot_contribution = pb::SystemBindings.injector_boot_contribution(env_boot_bindings)
  final_contribution = pb::SystemBindings.final_contribution
  binder = pb::Binder.new(pb::BindingsFactory.layered_bindings(final_contribution, boot_contribution))
  @boot_injector = pb::Injector.new(binder)
end

#environmentObject

Return the node’s environment.



234
235
236
# File 'lib/puppet/parser/compiler.rb', line 234

def environment
  node.environment
end

#evaluate_applicationsObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/puppet/parser/compiler.rb', line 332

def evaluate_applications
  @applications.each do |app|
    components = []
    mapping = app.parameters[:nodes] ? app.parameters[:nodes].value : {}
    raise Puppet::Error, "Invalid node mapping in #{app.ref}: Mapping must be a hash" unless mapping.is_a?(Hash)
    all_mapped = Set.new
    mapping.each do |k,v|
      raise Puppet::Error, "Invalid node mapping in #{app.ref}: Key #{k} is not a Node" unless k.is_a?(Puppet::Resource) && k.type == 'Node'
      v = [v] unless v.is_a?(Array)
      v.each do |res|
        raise Puppet::Error, "Invalid node mapping in #{app.ref}: Value #{res} is not a resource" unless res.is_a?(Puppet::Resource)
        raise Puppet::Error, "Application #{app.ref} maps component #{res} to multiple nodes" if all_mapped.add?(res.ref).nil?
        components << res if k.title == node.name
      end
    end
    begin
      @current_app = app
      @current_components = components
      unless @current_components.empty?
        Puppet.notice "EVAL APP #{app} #{components.inspect}"
        # Add the app itself since components mapped to the current node
        # will have a containment edge for it
        # @todo lutter 2015-01-28: the node mapping winds up in the
        # catalog, but probably shouldn't
        @catalog.add_resource(@current_app)
        @current_app.evaluate
      end
    ensure
      @current_app = nil
      @current_components = nil
    end
  end
end

#evaluate_classes(classes, scope, lazy_evaluate = true) ⇒ Object

Evaluates each specified class in turn. If there are any classes that can’t be found, an error is raised. This method really just creates resource objects that point back to the classes, and then the resources are themselves evaluated later in the process.

Raises:



371
372
373
374
375
376
377
378
379
380
381
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/parser/compiler.rb', line 371

def evaluate_classes(classes, scope, lazy_evaluate = true)
  raise Puppet::DevError, "No source for scope passed to evaluate_classes" unless scope.source
  class_parameters = nil
  # if we are a param class, save the classes hash
  # and transform classes to be the keys
  if classes.class == Hash
    class_parameters = classes
    classes = classes.keys
  end

  unless @current_components.nil?
    classes = classes.select do |title|
      @current_components.any? { |comp| comp.class? && comp.title == title }
    end
  end

  hostclasses = classes.collect do |name|
    scope.find_hostclass(name) or raise Puppet::Error, "Could not find class #{name} for #{node.name}"
  end

  if class_parameters
    resources = ensure_classes_with_parameters(scope, hostclasses, class_parameters)
    if !lazy_evaluate
      resources.each(&:evaluate)
    end

    resources
  else
    already_included, newly_included = ensure_classes_without_parameters(scope, hostclasses)
    if !lazy_evaluate
      newly_included.each(&:evaluate)
    end

    already_included + newly_included
  end
end

#evaluate_node_classesObject

Evaluate all of the classes specified by the node. Classes with parameters are evaluated as if they were declared. Classes without parameters or with an empty set of parameters are evaluated as if they were included. This means classes with an empty set of parameters won’t conflict even if the class has already been included.



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/puppet/parser/compiler.rb', line 243

def evaluate_node_classes
  if @node.classes.is_a? Hash
    classes_with_params, classes_without_params = @node.classes.partition {|name,params| params and !params.empty?}

    # The results from Hash#partition are arrays of pairs rather than hashes,
    # so we have to convert to the forms evaluate_classes expects (Hash, and
    # Array of class names)
    classes_with_params = Hash[classes_with_params]
    classes_without_params.map!(&:first)
  else
    classes_with_params = {}
    classes_without_params = @node.classes
  end

  evaluate_classes(classes_with_params, @node_scope || topscope)
  evaluate_classes(classes_without_params, @node_scope || topscope)
end

#evaluate_relationshipsObject



408
409
410
# File 'lib/puppet/parser/compiler.rb', line 408

def evaluate_relationships
  @relationships.each { |rel| rel.evaluate(catalog) }
end

#evaluate_siteObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Evaluates the site - the top container for an environment catalog The site contain behaves analogous to a node - for the environment catalog, node expressions are ignored as the result is cross node. The site expression serves as a container for everything that is across all nodes.



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/puppet/parser/compiler.rb', line 268

def evaluate_site
  # Has a site been defined? If not, do nothing but issue a warning.
  #
  site = known_resource_types.find_site()
  unless site
    on_empty_site()
    return
  end

  # Create a resource to model this site and add it to catalog
  resource = site.ensure_in_catalog(topscope)

  # The site sets node scope to be able to shadow what is in top scope
  @node_scope = topscope.class_scope(site)

  # Evaluates the logic contain in the site expression
  resource.evaluate
end

#newscope(parent, options = {}) ⇒ Object

Create a new scope, with either a specified parent scope or using the top scope.



434
435
436
437
438
439
# File 'lib/puppet/parser/compiler.rb', line 434

def newscope(parent, options = {})
  parent ||= topscope
  scope = Puppet::Parser::Scope.new(self, options)
  scope.parent = parent
  scope
end

#on_empty_siteObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



288
289
290
# File 'lib/puppet/parser/compiler.rb', line 288

def on_empty_site
  # do nothing
end

#prune_catalogObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Prunes the catalog by dropping all resources are contained under the Site (if a site expression is used). As a consequence all edges to/from dropped resources are also dropped. Once the pruning is performed, this compiler returns the pruned list when calling the #resources method. The pruning does not alter the order of resources in the resources list.



298
299
300
# File 'lib/puppet/parser/compiler.rb', line 298

def prune_catalog
  prune_node_catalog
end

#prune_node_catalogObject



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/puppet/parser/compiler.rb', line 302

def prune_node_catalog
  # Everything under Site[site] should be pruned as that is for the environment catalog, not a node
  #
  the_site_resource = @catalog.resource('Site', 'site')

  if the_site_resource
    # Get downstream vertexes returns a hash where the keys are the resources and values nesting level
    to_be_removed = @catalog.downstream_from_vertex(the_site_resource).keys

    # Drop the Site[site] resource if it has no content
    if to_be_removed.empty?
      to_be_removed << the_site_resource
    end
  else
    to_be_removed = []
  end

  # keep_from_site is populated with any App resources.
  application_resources = @resources.select {|r| r.type == 'App' }
  # keep all applications plus what is directly referenced from applications
  keep_from_site = application_resources
  keep_from_site += application_resources.map {|app| @catalog.direct_dependents_of(app) }.flatten

  to_be_removed -= keep_from_site
  @catalog.remove_resource(*to_be_removed)
  # set the pruned result
  @resources = @catalog.resources
end

#resource_overrides(resource) ⇒ Object

Return any overrides for the given resource.



442
443
444
# File 'lib/puppet/parser/compiler.rb', line 442

def resource_overrides(resource)
  @resource_overrides[resource.ref]
end

#validate_catalog(validation_stage) ⇒ Object



217
218
219
# File 'lib/puppet/parser/compiler.rb', line 217

def validate_catalog(validation_stage)
  @catalog_validators.select { |vclass| vclass.validation_stage?(validation_stage) }.each { |vclass| vclass.new(@catalog).validate }
end