Class: Puppet::Parser::Compiler

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
AbstractCompiler, Puppet::Pops::Evaluator::Runtime3Support, Util, Util::Errors
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

CatalogCompiler, EnvironmentCompiler

Defined Under Namespace

Classes: CatalogValidationError, CatalogValidator

Constant Summary

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

Puppet::Pops::Evaluator::Runtime3Support::NAME_SPACE_SEPARATOR

Constants included from Util

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

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_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, #runtime_issue, #set_match_data, #set_scope_nesting_level, #set_variable, #variable_bound?, #variable_exists?

Methods included from Util::Errors

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

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, set_env, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, 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

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Constructor Details

#initialize(node, code_id: nil) ⇒ Compiler

Returns a new instance of Compiler.



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/puppet/parser/compiler.rb', line 399

def initialize(node, code_id: nil)
  @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
  @code_id = code_id
  initvars
  add_catalog_validators
  # Resolutions of fully qualified variable names
  @qualified_variables = {}
end

Instance Attribute Details

#catalogObject (readonly)

Returns the value of attribute catalog.



45
46
47
# File 'lib/puppet/parser/compiler.rb', line 45

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.



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

def code_id
  @code_id
end

#collectionsObject (readonly)

Returns the value of attribute collections.



45
46
47
# File 'lib/puppet/parser/compiler.rb', line 45

def collections
  @collections
end

#factsObject (readonly)

Returns the value of attribute facts.



45
46
47
# File 'lib/puppet/parser/compiler.rb', line 45

def facts
  @facts
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



51
52
53
# File 'lib/puppet/parser/compiler.rb', line 51

def loaders
  @loaders
end

#nodeObject (readonly)

Returns the value of attribute node.



45
46
47
# File 'lib/puppet/parser/compiler.rb', line 45

def node
  @node
end

#qualified_variablesObject (readonly)

Returns the value of attribute qualified_variables.



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

def qualified_variables
  @qualified_variables
end

#relationshipsObject (readonly)

Returns the value of attribute relationships.



45
46
47
# File 'lib/puppet/parser/compiler.rb', line 45

def relationships
  @relationships
end

#resourcesObject (readonly)

Returns the value of attribute resources.



45
46
47
# File 'lib/puppet/parser/compiler.rb', line 45

def resources
  @resources
end

#topscopeObject (readonly)

Returns the value of attribute topscope.



45
46
47
# File 'lib/puppet/parser/compiler.rb', line 45

def topscope
  @topscope
end

Class Method Details

.compile(node, code_id = nil) ⇒ Object



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

def self.compile(node, code_id = 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: %{error}") % { error: errors.first },
      _("For more information, see https://puppet.com/docs/puppet/latest/environments_about.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 = _("%{message} on node %{node}") % { message: detail, node: node.name }
  Puppet.log_exception(detail, message)
  raise Puppet::Error, message, detail.backtrace
end

Instance Method Details

#add_catalog_validator(catalog_validators) ⇒ Object

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

Parameters:



135
136
137
138
# File 'lib/puppet/parser/compiler.rb', line 135

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

#add_catalog_validatorsObject



140
141
142
# File 'lib/puppet/parser/compiler.rb', line 140

def add_catalog_validators
  add_catalog_validator(CatalogValidator::RelationshipValidator)
end

#add_class(name) ⇒ Object

Store the fact that we’ve evaluated a class



129
130
131
# File 'lib/puppet/parser/compiler.rb', line 129

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

#add_override(override) ⇒ Object

Store a resource override.



62
63
64
65
66
67
68
69
70
71
# File 'lib/puppet/parser/compiler.rb', line 62

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



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

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]
    #TRANSLATORS "stage" is a keyword in Puppet and should not be translated
    raise ArgumentError, _("Only classes can set 'stage'; normal resources like %{resource} cannot change run stage") % { resource: resource }
  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



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/puppet/parser/compiler.rb', line 112

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
    #TRANSLATORS "Site" is a puppet keyword and should not be translated
    raise ArgumentError, _("Application instances like '%{resource}' can only be contained within a Site") % { resource: resource }
  end
end

#compileObject

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



153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
# File 'lib/puppet/parser/compiler.rb', line 153

def compile
  Puppet.override( @context_overrides , _("For compiling %{node}") % { node: 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 }

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

    #TRANSLATORS "main" is a function name and should not be translated
    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



207
208
209
210
211
212
213
# File 'lib/puppet/parser/compiler.rb', line 207

def context_overrides()
  {
    :current_environment => environment,
    :global_scope => @topscope,             # 4x placeholder for new global scope
    :loaders  => @loaders,                  # 4x loaders
  }
end

#environmentObject

Return the node’s environment.



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

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.



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/puppet/parser/compiler.rb', line 316

def evaluate_applications
  @applications.each do |app|
    components = []
    mapping = app.parameters[:nodes] ? app.parameters[:nodes].value : {}
    raise Puppet::Error, _("Invalid node mapping in %{app}: Mapping must be a hash") % { app: app.ref } unless mapping.is_a?(Hash)
    all_mapped = Set.new
    mapping.each do |k,v|
      raise Puppet::Error, _("Invalid node mapping in %{app}: Key %{k} is not a Node") % { app: app.ref, k: k } 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}: Value %{res} is not a resource") % { app: app.ref, res: res } unless res.is_a?(Puppet::Resource)
        raise Puppet::Error, _("Application %{app} maps component %{res} to multiple nodes") % { app: app.ref, res: res } 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:



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/puppet/parser/compiler.rb', line 355

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|
    environment.known_resource_types.find_hostclass(name) or raise Puppet::Error, _("Could not find class %{name} for %{node}") % { name: name, node: 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.



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/puppet/parser/compiler.rb', line 227

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



392
393
394
# File 'lib/puppet/parser/compiler.rb', line 392

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.



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/puppet/parser/compiler.rb', line 252

def evaluate_site
  # Has a site been defined? If not, do nothing but issue a warning.
  #
  site = environment.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.



420
421
422
423
424
425
# File 'lib/puppet/parser/compiler.rb', line 420

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.



272
273
274
# File 'lib/puppet/parser/compiler.rb', line 272

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.



282
283
284
# File 'lib/puppet/parser/compiler.rb', line 282

def prune_catalog
  prune_node_catalog
end

#prune_node_catalogObject



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/puppet/parser/compiler.rb', line 286

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.



428
429
430
# File 'lib/puppet/parser/compiler.rb', line 428

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

#validate_catalog(validation_stage) ⇒ Object



202
203
204
# File 'lib/puppet/parser/compiler.rb', line 202

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

#with_context_overrides(description = '', &block) ⇒ Object



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

def with_context_overrides(description = '', &block)
  Puppet.override( @context_overrides , description, &block)
end