Class: ForemanTemplates::TemplateImporter

Inherits:
Action
  • Object
show all
Defined in:
app/services/foreman_templates/template_importer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Action

#get_absolute_repo_path, #get_default_branch, #git_repo?, #method_missing, #repond_to_missing?, #verify_path!

Constructor Details

#initialize(args = {}) ⇒ TemplateImporter

Returns a new instance of TemplateImporter.



12
13
14
15
16
17
18
19
20
21
22
# File 'app/services/foreman_templates/template_importer.rb', line 12

def initialize(args = {})
  super
  # Rake hands off strings, not booleans, and "false" is true...
  if @verbose.is_a?(String)
    @verbose = if @verbose == 'false'
                 false
               else
                 true
               end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class ForemanTemplates::Action

Instance Attribute Details

#metadataObject

Returns the value of attribute metadata.



6
7
8
# File 'app/services/foreman_templates/template_importer.rb', line 6

def 
  @metadata
end

#nameObject

Returns the value of attribute name.



6
7
8
# File 'app/services/foreman_templates/template_importer.rb', line 6

def name
  @name
end

#textObject

Returns the value of attribute text.



6
7
8
# File 'app/services/foreman_templates/template_importer.rb', line 6

def text
  @text
end

Class Method Details

.setting_overridesObject



8
9
10
# File 'app/services/foreman_templates/template_importer.rb', line 8

def self.setting_overrides
  super + %i(associate)
end

Instance Method Details

#auto_prefix(name) ⇒ Object



116
117
118
# File 'app/services/foreman_templates/template_importer.rb', line 116

def auto_prefix(name)
  name.start_with?(@prefix) ? name : [@prefix, name].compact.join
end

#calculate_diff(old, new) ⇒ Object



120
121
122
123
124
125
126
# File 'app/services/foreman_templates/template_importer.rb', line 120

def calculate_diff(old, new)
  if old != new
    Diffy::Diff.new(old, new, :include_diff_info => true).to_s(:color)
  else
    nil
  end
end

#import!Object



24
25
26
27
28
29
30
# File 'app/services/foreman_templates/template_importer.rb', line 24

def import!
  if git_repo?
    import_from_git
  else
    import_from_files
  end
end

#import_from_filesObject



32
33
34
35
36
# File 'app/services/foreman_templates/template_importer.rb', line 32

def import_from_files
  @dir = get_absolute_repo_path
  verify_path!(@dir)
  return parse_files!
end

#import_from_gitObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/services/foreman_templates/template_importer.rb', line 38

def import_from_git
  # Check out the community templates to a temp location
  @dir = Dir.mktmpdir

  begin
    gitrepo = Git.clone(@repo, @dir)
    branch = @branch ? @branch : get_default_branch(gitrepo)
    gitrepo.checkout(branch) if branch

    return parse_files!
  ensure
    FileUtils.remove_entry_secure(@dir) if File.exist?(@dir)
  end
end

#parse_files!Object



53
54
55
56
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
# File 'app/services/foreman_templates/template_importer.rb', line 53

def parse_files!
  result_lines = []

  # Build a list of ERB files to parse
  Dir["#{@dir}#{@dirname}/**/*.erb"].each do |template|
    text = File.read(template)
    result_lines << 'Parsing: ' + template.gsub(/#{@dir}#{@dirname}/, '') if @verbose

     = (text)
    ['associate'] = @associate

    # Get the name and filter
    filename = template.split('/').last
    title    = filename.split('.').first
    name     = ['name'] || title
    name     = auto_prefix(name)
    if @filter
      matching = name.match(/#{@filter}/i)
      matching = !matching if @negate
      next if !matching
    end

    begin
      # Expects a return of { :diff, :status, :result }
      data = if ['model'].present?
               ['model'].constantize.import!(name, text, )
             else
               # For backwards-compat before "model" metadata was added
               case ['kind']
               when 'ptable'
                 Ptable.import!(name, text, )
               when 'job_template'
                 # TODO: update REX templates to have `model` and delete this
                 update_job_template(name, text)
               else
                 ProvisioningTemplate.import!(name, text, )
               end
             end

      if data[:diff].nil? && data[:old].present? && data[:new].present?
        data[:diff] = calculate_diff(data[:old], data[:new])
      end

      if data[:status] == true && @verbose
        result_lines << data[:result]
        result_lines << data[:diff] unless data[:diff].nil?
      elsif data[:status] == false
        result_lines << "Template \"#{name}\": #{data[:result]}"
      end
    rescue MissingKindError
      result_lines << "  Skipping: '#{name}' - No template kind or model detected"
      next
    rescue NoKindError
      result_lines << "  Skipping: '#{name}' - Unknown template kind '#{['kind']}'"
      next
    rescue NameError
      result_lines << "  Skipping: '#{name}' - Unknown template model '#{['model']}'"
      next
    end
  end
  result_lines
end

#parse_metadata(text) ⇒ Object



128
129
130
131
132
# File 'app/services/foreman_templates/template_importer.rb', line 128

def (text)
  # Pull out the first erb comment only - /m is for a multiline regex
  extracted = text.match(/<%\#[\t a-z0-9=:]*(.+?).-?%>/m)
  extracted.nil? ? {} : YAML.load(extracted[1])
end

#purge!Object



163
164
165
166
167
168
169
# File 'app/services/foreman_templates/template_importer.rb', line 163

def purge!
  clause = "name #{@negate ? 'NOT ' : ''}LIKE ?"
  ProvisioningTemplate.where(clause, "#{@prefix}%").each do |template|
    puts template if @verbose
    template.destroy
  end
end

#update_job_template(name, text) ⇒ Object



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
# File 'app/services/foreman_templates/template_importer.rb', line 134

def update_job_template(name, text)
  file = name.gsub(/^#{@prefix}/, '')
  puts 'Deprecation warning: JobTemplate support is moving to the Remote Execution plugin'
  puts "- please add 'model: JobTemplate' to the metadata in '#{file}' to call the right method"

  return {
    :status => false,
    :result => 'Skipping job template import, remote execution plugin is not installed.'
  } unless defined?(JobTemplate)
  template = JobTemplate.import(
    text.sub(/^name: .*$/, "name: #{name}"),
    :update => true
  )

  c_or_u = template.new_record? ? 'Created' : 'Updated'
  id_string = ('id' + template.id) rescue ''

  if template.template != template.template_was
    diff = Diffy::Diff.new(
      template.template_was,
      template.template,
      :include_diff_info => true
    ).to_s(:color)
  end

  result = "  #{c_or_u} Template #{id_string}:#{name}"
  { :diff => diff, :status => template.save, :result => result }
end