Class: Aws::Cfn::Compiler::Base

Inherits:
Dsl::Base
  • Object
show all
Includes:
Compile, Load, Options, Parse, Save
Defined in:
lib/aws/cfn/compiler/base.rb

Direct Known Subclasses

Main

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Save

#save_inifile, #save_section

Methods included from Compile

#compile_spec, #compile_value, #find_conditions, #find_fns, #find_maps, #find_refs, #get_meta, #map_resource_reference, #merge, #meta

Methods included from Parse

#parse, #parse_meta, #parse_rb_file, #parse_section, #requirement, #sym_to_s

Methods included from Load

#get_brick_dirname, #get_brick_path, #get_file_set, #short_path

Methods included from Options

#find_mia, #hint_paths, #parse_options, #report_mia, #set_config_options, #set_config_path_option

Constructor Details

#initializeBase

Returns a new instance of Base.


17
18
19
20
21
22
23
24
25
26
27
# File 'lib/aws/cfn/compiler/base.rb', line 17

def initialize
  super
  @items = {}
  @dynamic_items = {}
  @dynamic_references = {}
  @all_sections.each do |section|
    @dynamic_items[section]      ||= {}
    @dynamic_references[section] ||= []
    @dynamic_reference_locations ||= {}
  end
end

Instance Attribute Details

#itemsObject

Returns the value of attribute items


13
14
15
# File 'lib/aws/cfn/compiler/base.rb', line 13

def items
  @items
end

#optsObject

Returns the value of attribute opts


14
15
16
# File 'lib/aws/cfn/compiler/base.rb', line 14

def opts
  @opts
end

#specObject

Returns the value of attribute spec


15
16
17
# File 'lib/aws/cfn/compiler/base.rb', line 15

def spec
  @spec
end

Instance Method Details

#_uniq_names(arr) ⇒ Object


51
52
53
54
55
# File 'lib/aws/cfn/compiler/base.rb', line 51

def _uniq_names(arr)
  names = {}
  arr.map { |n| names[n] = nil }
  names.keys
end

#dynamic_item(section, resource, hash) ⇒ Object


29
30
31
32
# File 'lib/aws/cfn/compiler/base.rb', line 29

def dynamic_item(section,resource,hash)
  abort! "Invalid section '#{section}'\nValid sections are: #{@all_sections.join(',')}" unless @all_sections.include?(section)
  @dynamic_items[section][resource] = hash
end

#dynamic_reference(section, resource) ⇒ Object


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/aws/cfn/compiler/base.rb', line 34

def dynamic_reference(section,resource)
  abort! "Invalid section '#{section}'\nValid sections are: #{@all_sections.join(',')}" unless @all_sections.include?(section)

  caller_rgxp = %r/([-\.\/\(\)\w]+):(\d+)(?::in `(\w+)')?/o
  stack = caller()[0]
  match = caller_rgxp.match(stack)
  f = File.basename(match[1])
  l = Integer(match[2])
  # m = match[3] unless match[3].nil?

  # logger.warn("Referenced resource '#{resource}' does not (yet) exist in the section '#{section}' (From #{f} line #{l})") unless (@items.has_key?(section) and @items[section].has_key?(resource))
  #
  @dynamic_references[section] << resource
  @dynamic_reference_locations[resource] ||= {}
  @dynamic_reference_locations[resource][section] = [f,l]
end

#load_spec(spec = nil) ⇒ Object


248
249
250
251
252
253
254
255
256
257
258
259
260
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
# File 'lib/aws/cfn/compiler/base.rb', line 248

def load_spec(spec=nil)
  if spec
    abs = nil
    [spec, File.join(@config[:brick_path_list],spec)].flatten.each do |p|
      begin
        abs = File.realpath(File.absolute_path(File.expand_path(p)))
        break if File.exists?(abs)
      rescue => e
        @logger.debug e
        # pass
      end
    end

    if not abs.nil? and File.exists?(abs)
      logStep "Loading specification #{@config[:expandedpaths] ? abs : spec}..."
      unless abs =~ /\.(json|ya?ml|jts|yts)\z/i
        abort! "Unsupported specification file type: #{spec}=>#{abs}\n\tSupported types are: json,yaml,jts,yts\n"
      end

      spec = File.read(abs)

      case File.extname(File.basename(abs)).downcase
        when /json|jts/
          @spec = JSON.parse(spec)
        when /yaml|yts/
          begin
            @spec = YAML.load(spec)
          rescue Psych::SyntaxError => e
            i = 0
            abort! "Error in the template specification: #{e.message}\n#{spec.split(/\n/).map{|l| "#{i+=1}: #{l}"}.join("\n")}"
          end
        else
          abort! "Unsupported file type for specification: #{spec}"
      end
    else
      abort! 'Unable to open specification'+ (abs.nil? ? " or {.,#{@config[:brick_path_list].join(',')}/}#{spec} not found" : ": #{abs}")
    end
  else
    abort! 'No specification provided'
  end
end

#save_template(output_file, compiled) ⇒ Object


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
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
# File 'lib/aws/cfn/compiler/base.rb', line 189

def save_template(output_file,compiled)
  filn = output_file
  file = output_file
  file = File.expand_path(output_file) if @config[:expandedpaths]
  if File.exists?(file)
    file = File.realpath(file)
  end
  logStep "Writing compiled file to #{filn}..."
  begin
    hash = {}
    compiled.each do |item,value|
      unless value.nil?
        if (not value.is_a?(Hash)) or (value.count > 0)
          hash[item] = value
        end
      end
    end

    dir  = File.dirname(output_file)
    file = File.basename(output_file)
    sect = dir == '.' ? Dir.pwd : dir
    sect = File.basename(sect) unless @config[:expandedpaths]
    save_section(dir, file, @config[:format], sect, hash, '', 'template')

    parameters = []
    if (@config[:parametersfile] or @config[:stackinifile]) and hash.has_key?('Parameters')
      hash['Parameters'].each do |par,hsh|
        # noinspection RubyStringKeysInHashInspection
        parameters <<   {
            'ParameterKey' => par,
            'ParameterValue' => hsh.has_key?('Default') ? hsh['Default'] : '',
            # 'UsePreviousValue' => false,
        }
      end
    end

    if @config[:parametersfile] and parameters.size > 0
      dir  = File.dirname(@config[:parametersfile])
      file = File.basename(@config[:parametersfile])
      sect = dir == '.' ? Dir.pwd : dir
      sect = File.basename(sect) unless @config[:expandedpaths]

      save_section(dir, file, @config[:format], sect, parameters, '', 'parameters')
    end

    if @config[:stackinifile] and parameters.size > 0
      dir  = File.dirname(@config[:stackinifile])
      file = File.basename(@config[:stackinifile])
      sect = dir == '.' ? Dir.pwd : dir
      sect = File.basename(sect) unless @config[:expandedpaths]

      save_inifile(dir, file, sect, parameters, 'parameters')
    end
    @logger.info '  Compiled file written.'
  rescue
    abort! "!!! Could not write compiled file: #{$!}"
  end
end

#validate(compiled) ⇒ Object


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
# File 'lib/aws/cfn/compiler/base.rb', line 57

def validate(compiled)
  abort! 'No Resources!?' unless compiled['Resources']
  logStep 'Validating template'

 # --- Parameters ----------------------------------------------------------------------------------------------
  prms  = compiled['Parameters'].keys rescue []
  if compiled['Parameters']
    compiled['Parameters'].each do |name,hash|
      abort! "Parameter #{name} has an invalid compiled block!\n#{hash.ai}" unless hash.is_a?(Hash)
      if hash['Type']
        unless %w(String Number CommaDelimitedList).include?(hash['Type'])
          abort! "Parameter #{name} has an invalid type: #{hash['Type']}"
        end
        if hash.has_key?('Default')
          @logger.debug "#{name} is a #{hash['Type']} and 'Default' is #{hash['Default']}"
          case hash['Type']
            when /String/
              abort! "Parameter #{name} has an invalid Default: #{hash['Default']}(#{hash['Default'].class})" unless hash['Default'].is_a?(String)
            when /Number/
              abort! "Parameter #{name} has an invalid Default: #{hash['Default']}(#{hash['Default'].class})" unless (hash['Default'].is_a?(Numeric) or hash['Default'].is_a?(String))
            when /CommaDelimitedList/
              abort! "Parameter #{name} has an invalid Default: #{hash['Default']}(#{hash['Default'].class})" unless (hash['Default'].is_a?(Array) or (hash['Default'].is_a?(String) and hash['Default'].split(%r'\s*,\s*').size > 0))
            else
              abort! "Parameter #{name} has an invalid type: #{hash['Type']}"
          end
        end
      end
      if hash['Default']
        unless hash['Default'].is_a?(String)
          abort! "Parameter #{name} has an invalid default (Must be string): #{hash['Default']}"
        end
      end
    end
    @logger.info '  Parameters validated'
  end

  # --- functions ----------------------------------------------------------------------------------------------
  funs  = find_fns(compiled) #.select { |a| !(a =~ /^AWS::/) }

  bad = []
  funs.each do |fn|
    unless @valid_functions.include?(fn)
      bad << fn
    end
  end
  if bad.size > 0
    abort! "Encountered unsupported function(s) ...\n#{bad.ai}\nSupported functions are:\n#{@valid_functions.ai}"
  end
  @logger.info '  Functions validated'

  # --- Mappings ----------------------------------------------------------------------------------------------
  mappings  = find_maps(compiled)
  mpgs  = compiled['Mappings'].nil? ? [] : compiled['Mappings'].keys
  names = _uniq_names(mpgs+@dynamic_items['Mappings'].keys)

  maps = {}
  mappings.each{|m| maps[m[:mapping]] = m[:source] }
  mapnames = maps.keys+@dynamic_references['Mappings']
  net = (mapnames-names)
  unless net.empty?
    @logger.error '!!! Unknown mappings !!!'
    net.each do |name|
      @logger.error "  #{name} (Location in template: #{maps[name].join('/')})"
    end
    abort!
  end
  net = (names-mapnames)
  unless net.empty?
    @logger.warn '!!! Unused mappings !!!'
    net.each do |name|
      @logger.warn "  #{name}"
    end
  end
  @logger.info '  Mappings validated'

  # --- Conditions ----------------------------------------------------------------------------------------------
  cond  = find_conditions(compiled)+@dynamic_references['Conditions']
  cnds  = compiled['Conditions'].keys rescue []
  names = _uniq_names(cnds+@dynamic_items['Conditions'].keys)

  net = (cond-names)
  unless net.empty?
    @logger.error '!!! Unknown conditions !!!'
    net.each do |name|
      @logger.error "  #{name}"
    end
    abort!
  end
  net = (names-cond)
  unless net.empty?
    @logger.warn '!!! Unused conditions !!!'
    net.each do |name|
      @logger.warn "  #{name}"
    end
  end
  @logger.info '  Conditions validated'

  # --- References ----------------------------------------------------------------------------------------------
  # Parameters => Resources => Outputs
  refs  = find_refs(compiled).select { |a,_| !(a =~ /^AWS::/) }
  rscs  = compiled['Resources'].keys
  names = _uniq_names((mpgs+rscs+prms+cnds)+@dynamic_items['Mappings'].keys+@dynamic_items['Conditions'].keys+@dynamic_items['Parameters'].keys+@dynamic_items['Resources'].keys)

  net = (_uniq_names(refs.keys+@dynamic_references['Mappings']+@dynamic_references['Parameters']+@dynamic_references['Resources'])-names)
  unless net.empty?
    @logger.error '!!! Unknown references !!!'
    net.each do |name|
      if refs.include?(name)
        @logger.error "  #{name} from #{refs[name][0]}:#{refs[name][1]}"
      else
        @logger.error "  #{name} from #{@dynamic_reference_locations[name].map{ |s,a| "#{s}:#{a[0]} line #{a[1]}" }.join(',')}"
      end
    end
    abort!
  end
  net = (prms+@dynamic_items['Parameters'].keys-refs.keys-@dynamic_references['Parameters'])
  unless net.empty?
    @logger.warn '!!! Unused Parameters !!!'
    net.sort.each do |name|
      @logger.warn "  #{name}"
    end
  end
  net = (rscs+@dynamic_items['Resources'].keys-refs.keys-@dynamic_references['Resources'])
  unless net.empty?
    @logger.info '!!! Unreferenced Resources !!!'
    net.sort.each do |name|
      @logger.info "  #{name}"
    end
  end
  @logger.info '  References validated'
end