Class: SparkleFormation

Inherits:
Object
  • Object
show all
Extended by:
Utils::AnimalStrings, Utils::TypeCheckers
Includes:
Bogo::Memoization, Utils::AnimalStrings
Defined in:
lib/sparkle_formation.rb,
lib/sparkle_formation/error.rb,
lib/sparkle_formation/utils.rb,
lib/sparkle_formation/sparkle.rb,
lib/sparkle_formation/version.rb,
lib/sparkle_formation/provider.rb,
lib/sparkle_formation/resources.rb,
lib/sparkle_formation/translation.rb,
lib/sparkle_formation/provider/aws.rb,
lib/sparkle_formation/provider/heat.rb,
lib/sparkle_formation/resources/aws.rb,
lib/sparkle_formation/provider/azure.rb,
lib/sparkle_formation/resources/heat.rb,
lib/sparkle_formation/sparkle_struct.rb,
lib/sparkle_formation/function_struct.rb,
lib/sparkle_formation/resources/azure.rb,
lib/sparkle_formation/translation/heat.rb,
lib/sparkle_formation/sparkle_attribute.rb,
lib/sparkle_formation/sparkle_formation.rb,
lib/sparkle_formation/sparkle_collection.rb,
lib/sparkle_formation/resources/rackspace.rb,
lib/sparkle_formation/sparkle_attribute/aws.rb,
lib/sparkle_formation/translation/rackspace.rb,
lib/sparkle_formation/sparkle_attribute/heat.rb,
lib/sparkle_formation/sparkle_attribute/azure.rb,
lib/sparkle_formation/sparkle_collection/rainbow.rb,
lib/sparkle_formation/sparkle_attribute/rackspace.rb

Overview

Formation container

Defined Under Namespace

Modules: Provider, SparkleAttribute, Utils Classes: Cache, Error, FunctionStruct, Registry, Resources, Sparkle, SparkleCollection, SparkleStruct, Translation

Constant Summary collapse

SparklePack =

Alias for interfacing naming

Sparkle
VERSION =

Current library version

Gem::Version.new('2.1.0')
IGNORE_DIRECTORIES =

Returns directory names to ignore.

Returns:

  • (Array<String>)

    directory names to ignore

[
  'components',
  'dynamics',
  'registry'
]
DEFAULT_STACK_RESOURCE =

Returns default stack resource name.

Returns:

  • (String)

    default stack resource name

'AWS::CloudFormation::Stack'
VALID_STACK_RESOURCES =

Returns collection of valid stack resource types.

Returns:

  • (Array<String>)

    collection of valid stack resource types

[DEFAULT_STACK_RESOURCE]
ALLOWED_GENERATION_PARAMETERS =
['type', 'default', 'description', 'multiple', 'prompt_when_nested']
VALID_GENERATION_PARAMETER_TYPES =
['String', 'Number']

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils::TypeCheckers

__t_check, __t_hashish, __t_stringish

Methods included from Utils::AnimalStrings

camel, snake

Constructor Details

#initialize(name, options = {}) { ... } ⇒ SparkleFormation

Create new instance

Parameters:

  • name (String, Symbol)

    name of formation

  • options (Hash) (defaults to: {})

    options

Options Hash (options):

  • :sparkle_path (String)

    custom base path

  • :components_directory (String)

    custom components path

  • :dynamics_directory (String)

    custom dynamics path

  • :registry_directory (String)

    custom registry path

  • :parameters (Hash)

    parameters for stack generation

  • :disable_aws_builtins (Truthy, Falsey)

    do not load builtins

Yields:

  • base context



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/sparkle_formation/sparkle_formation.rb', line 396

def initialize(name, options={}, &block)
  @name = name.to_sym
  @component_paths = []
  if(options[:sparkle_collection])
    @sparkle = options[:sparkle_collection]
  else
    @sparkle = SparkleCollection.new
    @sparkle.set_root(
      Sparkle.new(
        Smash.new.tap{|h|
          s_path = options.fetch(:sparkle_path,
            self.class.custom_paths[:sparkle_path]
          )
          if(s_path)
            h[:root] = s_path
          end
        }
      )
    )
  end
  self.provider = options.fetch(:provider, @parent ? @parent.provider : :aws)
  if(provider == :aws || !options[:disable_aws_builtins])
    require 'sparkle_formation/aws'
  end
  @parameters = set_generation_parameters!(
    options.fetch(:compile_time_parameters,
      options.fetch(:parameters, {})
    )
  )
  @stack_resource_types = [
    stack_resource_type,
    *options.fetch(:stack_resource_types, [])
  ].compact.uniq
  @blacklisted_templates = [name]
  @components = Smash.new
  @load_order = []
  @overrides = []
  @parent = options[:parent]
  @seed = Smash.new(
    :inherit => options[:inherit],
    :layering => options[:layering]
  )
  if(block)
    load_block(block)
  end
  @compiled = nil
end

Instance Attribute Details

#blacklisted_templatesArray<String> (readonly)

Returns black listed templates.

Returns:

  • (Array<String>)

    black listed templates



383
384
385
# File 'lib/sparkle_formation/sparkle_formation.rb', line 383

def blacklisted_templates
  @blacklisted_templates
end

#compile_stateHash

Returns state hash for compile time parameters.

Returns:

  • (Hash)

    state hash for compile time parameters



375
376
377
# File 'lib/sparkle_formation/sparkle_formation.rb', line 375

def compile_state
  @compile_state
end

#componentsArray (readonly)

Returns components to load.

Returns:

  • (Array)

    components to load



365
366
367
# File 'lib/sparkle_formation/sparkle_formation.rb', line 365

def components
  @components
end

#components_directoryString (readonly)

Returns components path.

Returns:

  • (String)

    components path



359
360
361
# File 'lib/sparkle_formation/sparkle_formation.rb', line 359

def components_directory
  @components_directory
end

#dynamics_directoryString (readonly)

Returns dynamics path.

Returns:

  • (String)

    dynamics path



361
362
363
# File 'lib/sparkle_formation/sparkle_formation.rb', line 361

def dynamics_directory
  @dynamics_directory
end

#load_orderArray (readonly)

Returns order of loading.

Returns:

  • (Array)

    order of loading



367
368
369
# File 'lib/sparkle_formation/sparkle_formation.rb', line 367

def load_order
  @load_order
end

#nameSymbol

Returns name of formation.

Returns:

  • (Symbol)

    name of formation



353
354
355
# File 'lib/sparkle_formation/sparkle_formation.rb', line 353

def name
  @name
end

#parametersHash (readonly)

Returns parameters for stack generation.

Returns:

  • (Hash)

    parameters for stack generation



369
370
371
# File 'lib/sparkle_formation/sparkle_formation.rb', line 369

def parameters
  @parameters
end

#parentSparkleFormation

Returns parent stack.

Returns:



371
372
373
# File 'lib/sparkle_formation/sparkle_formation.rb', line 371

def parent
  @parent
end

#providerSymbol

Returns target provider.

Returns:

  • (Symbol)

    target provider



377
378
379
# File 'lib/sparkle_formation/sparkle_formation.rb', line 377

def provider
  @provider
end

#provider_resourcesClass (readonly)

Returns Provider resources.

Returns:

  • (Class)

    Provider resources



379
380
381
# File 'lib/sparkle_formation/sparkle_formation.rb', line 379

def provider_resources
  @provider_resources
end

#registry_directoryString (readonly)

Returns registry path.

Returns:

  • (String)

    registry path



363
364
365
# File 'lib/sparkle_formation/sparkle_formation.rb', line 363

def registry_directory
  @registry_directory
end

#sparkleSparkle (readonly)

Returns parts store.

Returns:



355
356
357
# File 'lib/sparkle_formation/sparkle_formation.rb', line 355

def sparkle
  @sparkle
end

#sparkle_pathString (readonly)

Returns base path.

Returns:

  • (String)

    base path



357
358
359
# File 'lib/sparkle_formation/sparkle_formation.rb', line 357

def sparkle_path
  @sparkle_path
end

#stack_resource_typesArray<String> (readonly)

Returns valid stack resource types.

Returns:

  • (Array<String>)

    valid stack resource types



373
374
375
# File 'lib/sparkle_formation/sparkle_formation.rb', line 373

def stack_resource_types
  @stack_resource_types
end

#template_pathString

Returns local path to template.

Returns:

  • (String)

    local path to template



381
382
383
# File 'lib/sparkle_formation/sparkle_formation.rb', line 381

def template_path
  @template_path
end

Class Method Details

.build(base = nil) { ... } ⇒ SparkleStruct

Execute given block within struct context

Parameters:

Yields:

  • block to execute

Returns:



117
118
119
120
121
122
123
124
125
# File 'lib/sparkle_formation/sparkle_formation.rb', line 117

def build(base=nil, &block)
  if(base || block.nil?)
    struct = base || SparkleStruct.new
    struct.instance_exec(&block)
    struct
  else
    block
  end
end

.builtin_insert(dynamic_name, struct, *args, &block) ⇒ SparkleStruct

Insert a builtin dynamic into a context

Parameters:

  • dynamic_name (String, Symbol)

    dynamic name

  • struct (SparkleStruct)

    context for insertion

  • args (Object)

    parameters for dynamic

Returns:



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/sparkle_formation/sparkle_formation.rb', line 308

def builtin_insert(dynamic_name, struct, *args, &block)
  if(struct._self.provider_resources && lookup_key = struct._self.provider_resources.registry_key(dynamic_name))
    _name, _config = *args
    _config ||= {}
    __t_stringish(_name)
    __t_hashish(_config)
    resource_name = "#{_name}_#{_config.delete(:resource_name_suffix) || dynamic_name}".to_sym
    new_resource = struct.resources.set!(resource_name)
    new_resource.type lookup_key
    properties = new_resource.properties
    config_keys = _config.keys.zip(_config.keys.map{|k| snake(k).to_s.tr('_', '')})
    struct._self.provider_resources.resource(dynamic_name, :properties).each do |prop_name|
      key = (config_keys.detect{|k| k.last == snake(prop_name).to_s.tr('_', '')} || []).first
      value = _config[key] if key
      if(value)
        if(value.is_a?(Proc))
          properties.set!(prop_name, &value)
        else
          properties.set!(prop_name, value)
        end
      end
    end
    new_resource.instance_exec(&block) if block
    struct._self.provider_resources.resource_customizer(new_resource, lookup_key)
    new_resource
  end
end

.compile(path, *args) ⇒ Hashish, SparkleStruct

Compile file

Parameters:

  • path (String)

    path to file

  • args (Object)

    use :sparkle to return struct. provide Hash to pass through when compiling (=> {})

Returns:



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/sparkle_formation/sparkle_formation.rb', line 95

def compile(path, *args)
  opts = args.detect{|i| i.is_a?(Hash) } || {}
  unless(path.is_a?(String) && File.file?(path.to_s))
    if(spath = (opts.delete(:sparkle_path) || SparkleFormation.sparkle_path))
      container = Sparkle.new(:root => spath)
      path = container.get(:template, path)[:path]
    end
  end
  formation = instance_eval(IO.read(path), path, 1)
  formation.template_path = path
  if(args.delete(:sparkle))
    formation
  else
    formation.compile(opts)._dump
  end
end

.components_path=(path = nil) ⇒ String Also known as: components_path

Get/set path to component files

Parameters:

  • path (String) (defaults to: nil)

    path to component files

Returns:

  • (String)

    path to component files



57
58
59
60
61
62
# File 'lib/sparkle_formation/sparkle_formation.rb', line 57

def components_path=(path=nil)
  if(path)
    custom_paths[:components_directory] = path
  end
  custom_paths[:components_directory]
end

.custom_pathsHashish

Returns custom paths.

Returns:

  • (Hashish)

    custom paths



33
34
35
36
# File 'lib/sparkle_formation/sparkle_formation.rb', line 33

def custom_paths
  @_paths ||= SparkleStruct.hashish.new
  @_paths
end

.dynamic(name, args = {}) { ... } ⇒ TrueClass

Define and register new dynamic

Examples:

 describes dynamic parameters for _config hash:
:item_name => {:description => 'Defines item name', :type => 'String'}

Parameters:

  • name (String, Symbol)

    name of dynamic

  • args (Hash) (defaults to: {})

    dynamic metadata

Options Hash (args):

  • :parameters (Hash)

    description of _config parameters

Yields:

  • dynamic block

Returns:

  • (TrueClass)


174
175
176
177
178
179
180
# File 'lib/sparkle_formation/sparkle_formation.rb', line 174

def dynamic(name, args={}, &block)
  @dynamics ||= SparkleStruct.hashish.new
  dynamics[name] = SparkleStruct.hashish[
    :block, block, :args, SparkleStruct.hashish[args.map(&:to_a)]
  ]
  true
end

.dynamic_info(name) ⇒ Hashish Also known as: dynamic_information

Metadata for dynamic

Parameters:

  • name (String, Symbol)

    dynamic name

Returns:

  • (Hashish)

    metadata information



186
187
188
189
190
191
192
# File 'lib/sparkle_formation/sparkle_formation.rb', line 186

def dynamic_info(name)
  if(dynamics[name])
    dynamics[name][:args] ||= SparkleStruct.hashish.new
  else
    raise KeyError.new("No dynamic registered with provided name (#{name})")
  end
end

.dynamicsHashish

Returns loaded dynamics.

Returns:

  • (Hashish)

    loaded dynamics



28
29
30
# File 'lib/sparkle_formation/sparkle_formation.rb', line 28

def dynamics
  @dynamics ||= SparkleStruct.hashish.new
end

.dynamics_path=(path = nil) ⇒ String Also known as: dynamics_path

Get/set path to dynamic files

Parameters:

  • path (String) (defaults to: nil)

    path to dynamic files

Returns:

  • (String)

    path to dynamic files



69
70
71
72
73
74
# File 'lib/sparkle_formation/sparkle_formation.rb', line 69

def dynamics_path=(path=nil)
  if(path)
    custom_paths[:dynamics_directory] = path
  end
  custom_paths[:dynamics_directory]
end

.from_hash(hash) ⇒ SparkleStruct

Note:

will do best effort on camel key auto discovery

Convert hash to SparkleStruct instance

Parameters:

  • hash (Hashish)

Returns:



341
342
343
344
345
346
347
# File 'lib/sparkle_formation/sparkle_formation.rb', line 341

def from_hash(hash)
  struct = SparkleStruct.new
  struct._camel_keys_set(:auto_discovery)
  struct._load(hash)
  struct._camel_keys_set(nil)
  struct
end

.insert(dynamic_name, struct, *args, &block) ⇒ SparkleStruct

Insert a dynamic into a context

Parameters:

  • dynamic_name (String, Symbol)

    dynamic name

  • struct (SparkleStruct)

    context for insertion

  • args (Object)

    parameters for dynamic

Returns:



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/sparkle_formation/sparkle_formation.rb', line 213

def insert(dynamic_name, struct, *args, &block)
  __t_stringish(dynamic_name)
  result = false
  begin
    dyn = struct._self.sparkle.get(:dynamic, dynamic_name)
    raise dyn if dyn.is_a?(Exception)
    dyn.monochrome.each do |dynamic_item|
      if(result)
        opts = args.detect{|i| i.is_a?(Hash)}
        if(opts)
          opts[:previous_layer_result] = result
        else
          args.push(:previous_layer_result => result)
        end
      end
      result = struct.instance_exec(*args, &dynamic_item[:block])
    end
    if(block_given?)
      result.instance_exec(&block)
    end
  rescue Error::NotFound::Dynamic
    result = builtin_insert(dynamic_name, struct, *args, &block)
    unless(result)
      message = "Failed to locate requested dynamic block for insertion: #{dynamic_name} " \
      "(valid: #{struct._self.sparkle.dynamics.keys.sort.join(', ')})"
      if(struct._self.provider_resources && struct._self.provider_resources.registry.keys.size > 1)
        t_name = struct._self.provider_resources.registry.keys.first
        valid_t_name = Bogo::Utility.snake(
          t_name.split(
            struct._self.provider_resources.resource_type_splitter
          ).join('_')
        )
        message << "\nBuiltin dynamics pattern `#{t_name}` -> `:#{Bogo::Utility.snake(valid_t_name)}`"
      end
      raise message
    end
  end
  result
end

.load_component(path) ⇒ SparkleStruct

Load component

Parameters:

  • path (String)

    path to component

Returns:



131
132
133
134
# File 'lib/sparkle_formation/sparkle_formation.rb', line 131

def load_component(path)
  instance_eval(IO.read(path), path, 1)
  @_struct
end

.load_dynamics!(directory) ⇒ TrueClass

Load all dynamics within a directory

Parameters:

  • directory (String)

Returns:

  • (TrueClass)


140
141
142
143
144
145
146
147
148
149
150
# File 'lib/sparkle_formation/sparkle_formation.rb', line 140

def load_dynamics!(directory)
  @loaded_dynamics ||= []
  Dir.glob(File.join(directory, '*.rb')).each do |dyn|
    dyn = File.expand_path(dyn)
    next if @loaded_dynamics.include?(dyn)
    instance_eval(IO.read(dyn), dyn, 1)
    @loaded_dynamics << dyn
  end
  @loaded_dynamics.uniq!
  true
end

.load_registry!(directory) ⇒ TrueClass

Load all registry entries within a directory

Parameters:

  • directory (String)

Returns:

  • (TrueClass)


156
157
158
159
160
161
162
# File 'lib/sparkle_formation/sparkle_formation.rb', line 156

def load_registry!(directory)
  Dir.glob(File.join(directory, '*.rb')).each do |reg|
    reg = File.expand_path(reg)
    require reg
  end
  true
end

.nest(template, struct, *args, &block) ⇒ SparkleStruct

Note:

if symbol is provided for template, double underscores will be used for directory separator and dashes will match underscores

Nest a template into a context

Parameters:

  • template (String, Symbol)

    template to nest

  • struct (SparkleStruct)

    context for nesting

  • args (String, Symbol)

    stringified and underscore joined for name

Returns:



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/sparkle_formation/sparkle_formation.rb', line 261

def nest(template, struct, *args, &block)
  options = args.detect{|i| i.is_a?(Hash)}
  if(options)
    args.delete(options)
  else
    options = {}
  end
  [template, *args].compact.each do |item|
    __t_stringish(item)
  end
  to_nest = struct._self.sparkle.get(:template, template)
  resource_name = template.to_s.gsub('__', '_')
  unless(args.empty?)
    resource_name = [
      options.delete(:overwrite_name) ? nil : resource_name,
      args.map{|a| Bogo::Utility.snake(a)}.join('_')
    ].flatten.compact.join('_').to_sym
  end
  nested_template = compile(to_nest[:path], :sparkle)
  nested_template.parent = struct._self
  nested_template.name = Bogo::Utility.camel(resource_name)
  if(options[:parameters])
    nested_template.compile_state = options[:parameters]
  end
  struct.resources.set!(resource_name) do
    type struct._self.stack_resource_type
  end
  unless(struct._self.sparkle.empty?)
    struct._self.sparkle.size.times do |idx|
      nested_template.sparkle.add_sparkle(
        struct._self.sparkle.sparkle_at(idx)
      )
    end
  end
  struct.resources[resource_name].properties.stack nested_template
  if(block_given?)
    struct.resources[resource_name].instance_exec(&block)
  end
  struct.resources[resource_name]
end

.registry(registry_name, struct, *args) ⇒ SparkleStruct

Insert a dynamic into a context

Parameters:

  • dynamic_name (String, Symbol)

    dynamic name

  • struct (SparkleStruct)

    context for insertion

  • args (Object)

    parameters for dynamic

Returns:



201
202
203
204
205
# File 'lib/sparkle_formation/sparkle_formation.rb', line 201

def registry(registry_name, struct, *args)
  __t_stringish(registry_name)
  reg = struct._self.sparkle.get(:registry, registry_name)
  struct.instance_exec(*args, &reg[:block])
end

.registry_path=(path = nil) ⇒ String Also known as: registry_path

Get/set path to registry files

Parameters:

  • path (String) (defaults to: nil)

    path to registry files

Returns:

  • (String)

    path to registry files



81
82
83
84
85
86
# File 'lib/sparkle_formation/sparkle_formation.rb', line 81

def registry_path=(path=nil)
  if(path)
    custom_paths[:registry_directory] = path
  end
  custom_paths[:registry_directory]
end

.sparkle_path=(path = nil) ⇒ String Also known as: sparkle_path

Get/set path to sparkle directory

Parameters:

  • path (String) (defaults to: nil)

    path to directory

Returns:

  • (String)

    path to directory



42
43
44
45
46
47
48
49
50
# File 'lib/sparkle_formation/sparkle_formation.rb', line 42

def sparkle_path=(path=nil)
  if(path)
    custom_paths[:sparkle_path] = path
    custom_paths[:components_directory] = File.join(path, 'components')
    custom_paths[:dynamics_directory] = File.join(path, 'dynamics')
    custom_paths[:registry_directory] = File.join(path, 'registry')
  end
  custom_paths[:sparkle_path]
end

Instance Method Details

#apply_deep_nesting(*args) {|stack, resource, s_name| ... } ⇒ Hash

Apply deeply nested stacks. This is the new nesting approach and does not bubble parameters up to the root stack. Parameters are isolated to the stack resource itself and output mapping is automatically applied.

Yield Parameters:

  • stack (SparkleFormation)

    stack instance

  • resource (AttributeStruct)

    the stack resource

  • s_name (String)

    stack resource name

Yield Returns:

  • (Hash)

    key/values to be merged into resource properties

Returns:

  • (Hash)

    dumped stack



826
827
828
# File 'lib/sparkle_formation/sparkle_formation.rb', line 826

def apply_deep_nesting(*args, &block)
  compile.dump!
end

#apply_nesting(*args, &block) ⇒ Hash

Note:

see specific version for expected block parameters

Apply nesting logic to stack

Parameters:

  • nest_type (Symbol)

    values: :shallow, :deep (default: :deep)

Returns:

  • (Hash)

    dumped stack



808
809
810
811
812
813
814
# File 'lib/sparkle_formation/sparkle_formation.rb', line 808

def apply_nesting(*args, &block)
  if(args.include?(:shallow))
    apply_shallow_nesting(&block)
  else
    apply_deep_nesting(&block)
  end
end

#apply_shallow_nesting(*args) {|resource_name, stack| ... } ⇒ Hash

Apply shallow nesting. This style of nesting will bubble parameters up to the root stack. This type of nesting is the original and now deprecated, but remains for compat issues so any existing usage won’t be automatically busted.

Yield Parameters:

  • resource_name (String)

    name of stack resource

  • stack (SparkleFormation)

    nested stack

Yield Returns:

  • (String)

    Remote URL storage for template

Returns:

  • (Hash)


884
885
886
# File 'lib/sparkle_formation/sparkle_formation.rb', line 884

def apply_shallow_nesting(*args, &block)
  compile.dump!
end

#block(block) ⇒ TrueClass Also known as: load_block

Add block to load order

Parameters:

  • block (Proc)

Returns:

  • (TrueClass)


634
635
636
637
638
# File 'lib/sparkle_formation/sparkle_formation.rb', line 634

def block(block)
  @components[:__base__] = block
  @load_order << :__base__
  true
end

#collect_outputs(*args) ⇒ Smash<output_name:SparkleFormation>

Returns:

  • (Smash<output_name:SparkleFormation>)


889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
# File 'lib/sparkle_formation/sparkle_formation.rb', line 889

def collect_outputs(*args)
  if(args.include?(:force) || root?)
    unless(compile.outputs.nil?)
      outputs = Smash[
        compile.outputs.keys!.zip(
          [self] * compile.outputs.keys!.size
        )
      ]
    else
      outputs = Smash.new
    end
    nested_stacks.each do |nested_stack|
      outputs = nested_stack.collect_outputs(:force).merge(outputs)
    end
    outputs
  else
    root.collect_outputs(:force)
  end
end

#compile(args = {}) ⇒ SparkleStruct

Compile the formation

Parameters:

  • args (Hash) (defaults to: {})

Options Hash (args):

  • :state (Hash)

    local state parameters

Returns:



674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/sparkle_formation/sparkle_formation.rb', line 674

def compile(args={})
  if(args.key?(:state))
    @compile_state = args[:state]
    unmemoize(:compile)
  end
  memoize(:compile) do
    # NOTE: this is where we inject inherit or layering
    seed_self

    set_compile_time_parameters!
    if(provider && SparkleAttribute.const_defined?(camel(provider)))
      const = SparkleAttribute.const_get(camel(provider))
      struct_class = Class.new(SparkleStruct)
      struct_class.include(const)
      struct_name = [SparkleStruct.name, camel(provider)].join('::')
      struct_class.define_singleton_method(:name){ struct_name }
      struct_class.define_singleton_method(:to_s){ struct_name }
    else
      struct_class = SparkleStruct
    end
    if(Resources.const_defined?(camel(provider)))
      @provider_resources = Resources.const_get(camel(provider))
      provider_resources.load!
    end
    compiled = struct_class.new
    compiled._set_self(self)
    compiled._struct_class = struct_class
    if(struct_class.const_defined?(:CAMEL_KEYS))
      compiled._camel_keys = struct_class.const_get(:CAMEL_KEYS)
    end
    if(struct_class.const_defined?(:CAMEL_STYLE))
      compiled._camel_style = struct_class.const_get(:CAMEL_STYLE)
    end
    if(compile_state)
      compiled.set_state!(compile_state)
    end
    @load_order.each do |key|
      if(components[key])
        self.class.build(compiled, &components[key])
      else
        sparkle.get(:component, key).monochrome.each do |component_block|
          self.class.build(compiled, &component_block[:block])
        end
      end
    end
    @overrides.each do |override|
      if(override[:args] && !override[:args].empty?)
        compiled._set_state(override[:args])
      end
      self.class.build(compiled, &override[:block])
    end
    if(compile_state && !compile_state.empty?)
      compiled.outputs.compile_state.value MultiJson.dump(compile_state)
    end
    compiled
  end
end

#compile_time_parameter_setter {|| ... } ⇒ Proc, NilClass

Get or set the compile time parameter setting block. If a get request the ancestor path will be searched to root

Yields:

  • block to set compile time parameters

Yield Parameters:

Returns:

  • (Proc, NilClass)


592
593
594
595
596
597
598
599
600
601
602
# File 'lib/sparkle_formation/sparkle_formation.rb', line 592

def compile_time_parameter_setter(&block)
  if(block)
    @compile_time_parameter_setter = block
  else
    if(@compile_time_parameter_setter)
      @compile_time_parameter_setter
    else
      parent.nil? ? nil : parent.compile_time_parameter_setter
    end
  end
end

#dumpHash

Returns dumped hash.

Returns:

  • (Hash)

    dumped hash



928
929
930
# File 'lib/sparkle_formation/sparkle_formation.rb', line 928

def dump
  MultiJson.load(to_json)
end

#extract_template_data(template) ⇒ self

Extract information from given template and integrate with current instance

Parameters:

Returns:

  • (self)


500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'lib/sparkle_formation/sparkle_formation.rb', line 500

def extract_template_data(template)
  if(provider != template.provider)
    raise TypeError.new "This template `#{name}` cannot inherit template `#{template.name}`! Provider mismatch: `#{provider}` != `#{template.provider}`" # rubocop:disable Metrics/LineLength
  end
  sparkle.size.times do |idx|
    template.sparkle.add_sparkle(sparkle.sparkle_at(idx))
  end
  template.seed_self
  blacklisted_templates.replace(
    (blacklisted_templates + template.blacklisted_templates).map(&:to_s).uniq
  )
  @parameters = template.parameters
  @overrides = template.raw_overrides + raw_overrides
  new_components = template.components
  new_load_order = template.load_order
  load_order.each do |comp_key|
    if(components[comp_key])
      original_key = comp_key
      comp_key = "#{comp_key}_#{Smash.new(:name => name, :path => template_path).checksum}_child"
      new_components[comp_key] = components[original_key]
    end
    new_load_order << comp_key
  end
  @components = new_components
  @load_order = new_load_order
  self
end

#extract_templates {|stack, resource, s_name| ... } ⇒ Object

Extract and process nested stacks

Yield Parameters:

  • stack (SparkleFormation)

    stack instance

  • resource (AttributeStruct)

    the stack resource

  • s_name (String)

    stack resource name

Yield Returns:

  • (Hash)

    key/values to be merged into resource properties



858
859
860
# File 'lib/sparkle_formation/sparkle_formation.rb', line 858

def extract_templates(&block)
  stack_template_extractor(nested_stacks(:with_resource, :with_name), &block)
end

#generate_policyHash

Generate policy for stack

Returns:

  • (Hash)


799
800
801
# File 'lib/sparkle_formation/sparkle_formation.rb', line 799

def generate_policy
  Smash.new
end

#includes_policies?(stack_hash = nil) ⇒ TrueClass, FalseClass

Returns policies defined.

Returns:

  • (TrueClass, FalseClass)

    policies defined



785
786
787
788
789
790
791
792
793
794
# File 'lib/sparkle_formation/sparkle_formation.rb', line 785

def includes_policies?(stack_hash=nil)
  if(stack_hash)
    raise Error::Deprecated.new "Hash parameter no longer valid for this method (`#{self.class}##{__callee__}`)"
  end
  unless(compile.resources.nil?)
    compile.resources._data.any? do |r_name, r_value|
      !r_value.policy.nil?
    end
  end
end

#inherit_from(template_name) ⇒ self

Inhert template structure

Parameters:

  • template_name (String)

    name of template to inherit

Returns:

  • (self)


485
486
487
488
489
490
491
492
493
494
# File 'lib/sparkle_formation/sparkle_formation.rb', line 485

def inherit_from(template_name)
  if(blacklisted_templates.map(&:to_s).include?(template_name.to_s))
    raise Error::CircularInheritance.new "Circular inheritance detected between templates `#{template_name}` and `#{name}`" # rubocop:disable Metrics/LineLength
  end
  template = self.class.compile(sparkle.get(:template, template_name)[:path], :sparkle)
  template.blacklisted_templates.replace(
    (template.blacklisted_templates + blacklisted_templates).map(&:to_s).uniq
  )
  extract_template_data(template)
end

#isolated_nests?(stack_hash = nil) ⇒ TrueClass, FalseClass

Returns includes only nested stacks.

Returns:

  • (TrueClass, FalseClass)

    includes only nested stacks



773
774
775
776
777
778
779
780
781
782
# File 'lib/sparkle_formation/sparkle_formation.rb', line 773

def isolated_nests?(stack_hash=nil)
  if(stack_hash)
    raise Error::Deprecated.new "Hash parameter no longer valid for this method (`#{self.class}##{__callee__}`)"
  end
  unless(compile.resources.nil?)
    compile.resources._data.all? do |r_name, r_value|
      stack_resource_type?(r_value.type)
    end
  end
end

#load(*args) ⇒ self

Load components into instance

Parameters:

  • args (String, Symbol)

    Symbol component names or String paths

Returns:

  • (self)


645
646
647
648
649
650
651
652
653
654
655
656
657
658
# File 'lib/sparkle_formation/sparkle_formation.rb', line 645

def load(*args)
  args.each do |thing|
    key = File.basename(thing.to_s).sub('.rb', '')
    if(thing.is_a?(String))
      # NOTE: This needs to be deprecated and removed
      # TODO: deprecate
      components[key] = self.class.load_component(thing)
      @load_order << key
    else
      @load_order << thing
    end
  end
  self
end

#make_output_available(output_name, outputs) ⇒ Object

Extract output to make available for stack parameter usage at the current depth

Parameters:

  • output_name (String)

    name of output

  • outputs (Hash)

    listing of outputs



848
849
850
# File 'lib/sparkle_formation/sparkle_formation.rb', line 848

def make_output_available(output_name, outputs)
  {}
end

#merge_previous!self

Merge previous layer template structure

Returns:

  • (self)


473
474
475
476
477
478
479
# File 'lib/sparkle_formation/sparkle_formation.rb', line 473

def merge_previous!
  my_index = sparkle.get(:template, name).spectrum.find_index do |item|
    item[:path] == template_path
  end
  template = self.class.compile(sparkle.get(:template, name).layer_at(my_index - 1)[:path], :sparkle)
  extract_template_data(template)
end

#nested?(stack_hash = nil) ⇒ TrueClass, FalseClass

Returns includes nested stacks.

Returns:

  • (TrueClass, FalseClass)

    includes nested stacks



761
762
763
764
765
766
767
768
769
770
# File 'lib/sparkle_formation/sparkle_formation.rb', line 761

def nested?(stack_hash=nil)
  if(stack_hash)
    raise Error::Deprecated.new "Hash parameter no longer valid for this method (`#{self.class}##{__callee__}`)"
  end
  unless(compile.resources.nil?)
    compile.resources._data.any? do |r_name, r_value|
      stack_resource_type?(r_value.type)
    end
  end
end

#nested_stacks(*args) ⇒ Array<SparkleFormation>

Returns:



741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# File 'lib/sparkle_formation/sparkle_formation.rb', line 741

def nested_stacks(*args)
  if(compile[:resources])
    compile.resources.keys!.map do |key|
      if(stack_resource_type?(compile.resources[key].type))
        result = [compile.resources[key].properties.stack]
        if(args.include?(:with_resource))
          result.push(compile[:resources][key])
        end
        if(args.include?(:with_name))
          result.push(key)
        end
        result.size == 1 ? result.first : result
      end
    end.compact
  else
    []
  end
end

#output_matched?(p_name, output_names) ⇒ String, NilClass

Note:

will auto downcase name prior to comparison

Check if parameter name matches an output name

Parameters:

  • p_name (String, Symbol)

    parameter name

  • output_names (Array<String>)

    list of available outputs

Returns:

  • (String, NilClass)

    matching output name



836
837
838
839
840
# File 'lib/sparkle_formation/sparkle_formation.rb', line 836

def output_matched?(p_name, output_names)
  output_names.detect do |o_name|
    Bogo::Utility.snake(o_name).tr('_', '') == Bogo::Utility.snake(p_name).tr('_', '')
  end
end

#overrides(args = {}) { ... } ⇒ Object

Registers block into overrides

Parameters:

  • args (Hash) (defaults to: {})

    optional arguments to provide state

Yields:

  • override block



664
665
666
667
# File 'lib/sparkle_formation/sparkle_formation.rb', line 664

def overrides(args={}, &block)
  @overrides << {:args => args, :block => block}
  self
end

#raw_overridesArray<Proc>

Returns:

  • (Array<Proc>)


445
446
447
# File 'lib/sparkle_formation/sparkle_formation.rb', line 445

def raw_overrides
  @overrides
end

#recompileSparkleStruct

Clear compiled stack if cached and perform compilation again

Returns:



735
736
737
738
# File 'lib/sparkle_formation/sparkle_formation.rb', line 735

def recompile
  unmemoize(:compile)
  compile
end

#remap_nested_parameters(template, parameters, stack_name, stack_resource, output_map) ⇒ TrueClass

Note:

if parameter has includes ‘StackUnique` a new parameter will be added to container stack and it will not use outputs

Extract parameters from nested stacks. Check for previous nested stack outputs that match parameter. If match, set parameter to use output. If no match, check container stack parameters for match. If match, set to use ref. If no match, add parameter to container stack parameters and set to use ref.

Parameters:

  • template (Hash)

    template being processed

  • parameters (Hash)

    top level parameter set being built

  • stack_name (String)

    name of stack resource

  • stack_resource (Hash)

    duplicate of stack resource contents

  • output_map (Hash)

    mapping of output names to required stack output access

Returns:

  • (TrueClass)


923
924
925
# File 'lib/sparkle_formation/sparkle_formation.rb', line 923

def remap_nested_parameters(template, parameters, stack_name, stack_resource, output_map)
  true
end

#rootSparkleFormation

Returns root stack.

Returns:



561
562
563
564
565
566
567
# File 'lib/sparkle_formation/sparkle_formation.rb', line 561

def root
  if(parent)
    parent.root
  else
    self
  end
end

#root?TrueClass, FalseClass

Returns current stack is root.

Returns:

  • (TrueClass, FalseClass)

    current stack is root



579
580
581
# File 'lib/sparkle_formation/sparkle_formation.rb', line 579

def root?
  root == self
end

#root_pathArray<SparkleFormation] path to root

Returns Array<SparkleFormation] path to root.

Returns:



570
571
572
573
574
575
576
# File 'lib/sparkle_formation/sparkle_formation.rb', line 570

def root_path
  if(parent)
    [*parent.root_path, self].compact
  else
    [self]
  end
end

#seed_selfself

Update underlying data structures based on inherit or layering behavior if defined for this template

Parameters:

  • options (Hash)

Returns:

  • (self)


454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/sparkle_formation/sparkle_formation.rb', line 454

def seed_self
  memoize(:seed) do
    options = @seed
    if(options[:inherit] && options[:layering].to_s == 'merge')
      raise ArgumentError.new 'Cannot merge and inherit!'
    end
    if(options[:inherit])
      inherit_from(options[:inherit])
    elsif(options[:layering].to_s == 'merge')
      merge_previous!
    end
    true
  end
  self
end

#set_compile_time_parameters!Object

Set the compile time parameters for the stack if the setter proc is available



606
607
608
609
610
# File 'lib/sparkle_formation/sparkle_formation.rb', line 606

def set_compile_time_parameters!
  if(compile_time_parameter_setter)
    compile_time_parameter_setter.call(self)
  end
end

#set_generation_parameters!(params) ⇒ Hash

Validation parameters used for template generation to ensure they are in the expected format

Parameters:

  • params (Hash)

    parameter set

Returns:

  • (Hash)

    parameter set



618
619
620
621
622
623
624
625
626
627
628
# File 'lib/sparkle_formation/sparkle_formation.rb', line 618

def set_generation_parameters!(params)
  params.each do |name, value|
    unless(value.is_a?(Hash))
      raise TypeError.new("Expecting `Hash` type. Received `#{value.class}`")
    end
    if(key = value.keys.detect{|k| !ALLOWED_GENERATION_PARAMETERS.include?(k.to_s) })
      raise ArgumentError.new("Invalid generation parameter key provided `#{key}`")
    end
  end
  params
end

#stack_resource_typeString

Returns provider stack resource type.

Returns:

  • (String)

    provider stack resource type



529
530
531
# File 'lib/sparkle_formation/sparkle_formation.rb', line 529

def stack_resource_type
  DEFAULT_STACK_RESOURCE
end

#stack_resource_type?(type) ⇒ TrueClass, FalseClass

Check if type is a registered stack type

Parameters:

  • type (String)

Returns:

  • (TrueClass, FalseClass)


556
557
558
# File 'lib/sparkle_formation/sparkle_formation.rb', line 556

def stack_resource_type?(type)
  stack_resource_types.include?(type)
end

#stack_template_extractor(x_stacks, &block) ⇒ Object

Run the stack extraction

Parameters:



865
866
867
868
869
870
871
872
873
# File 'lib/sparkle_formation/sparkle_formation.rb', line 865

def stack_template_extractor(x_stacks, &block)
  x_stacks.each do |stack, resource, s_name|
    unless(stack.nested_stacks.empty?)
      stack_template_extractor(stack.nested_stacks(:with_resource, :with_name), &block)
    end
    resource.properties.set!(:stack, stack.compile.dump!)
    block.call(s_name, stack, resource)
  end
end

#to_json(*args) ⇒ String

Returns dumped hash JSON.

Returns:

  • (String)

    dumped hash JSON



933
934
935
# File 'lib/sparkle_formation/sparkle_formation.rb', line 933

def to_json(*args)
  MultiJson.dump(compile.dump!, *args)
end