Class: Simp::Rake::Beaker

Inherits:
Rake::TaskLib
  • Object
show all
Defined in:
lib/simp/rake/beaker.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_dir) {|_self| ... } ⇒ Beaker

Returns a new instance of Beaker.

Yields:

  • (_self)

Yield Parameters:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
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
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
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
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
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
314
315
316
317
318
319
# File 'lib/simp/rake/beaker.rb', line 12

def initialize(base_dir)

  @base_dir   = base_dir
  @clean_list = []

  ::CLEAN.include( %{#{@base_dir}/log} )
  ::CLEAN.include( %{#{@base_dir}/junit} )
  ::CLEAN.include( %{#{@base_dir}/sec_results} )
  ::CLEAN.include( %{#{@base_dir}/spec/fixtures/inspec_deps} )

  yield self if block_given?

  ::CLEAN.include( @clean_list )

  namespace :beaker do
    desc <<-EOM
      Run a Beaker test against a specific Nodeset
        * :nodeset - The nodeset against which you wish to run
    EOM
    task :run, [:nodeset] do |t,args|
      fail "You must pass :nodeset to #{t}" unless args[:nodeset]
      nodeset = args[:nodeset].strip

      old_stdout = $stdout
      nodesets = StringIO.new
      $stdout = nodesets

      Rake::Task['beaker_nodes'].invoke

      $stdout = old_stdout

      nodesets = nodesets.string.split("\n")

      fail "Nodeset '#{nodeset}' not found. Valid Nodesets:\n#{nodesets.map{|x| x = %(  * #{x})}.join(%(\n))}" unless nodesets.include?(nodeset)

      ENV['BEAKER_set'] = nodeset

      Rake::Task['beaker'].invoke
    end

    desc <<-EOM
      Run Beaker test suites.
        * :suite - A specific suite to run
          * If you set this to `ALL`, all suites will be run

        * :nodeset - A specific nodeset to run on within a specific suite
          * If you set this to `ALL`, all nodesets will be looped through, starting with 'default'
          * You may also set this to a colon delimited list of short
            nodeset names that will be run in that order

        ## Suite Execution

          By default the only suite that will be executed is `default`.
          Since each suite is executed in a new environment, spin up can
          take a lot of time. Therefore, the default is to only run the
          default suite.

          If there is a suite where the metadata contains `default_run` set
          to the Boolean `true`, then that suite will be part of the
          default suite execution.

          You can run all suites by setting the passed suite name to `ALL`
          (case sensitive).

        ## Environment Variables

          * BEAKER_suite_runall
            * Run all Suites

          * BEAKER_suite_basedir
            * The base directory where suites will be defined
            * Default: spec/acceptance

        ## Global Suite Configuration
          A file `config.yml` can be placed in the `suites` directory to
          control certain aspects of the suite run.

        ### Supported Config:

          ```yaml
          ---
          # Fail the entire suite at the first failure
          'fail_fast' : <true|false> => Default: true
          ```
        ## Individual Suite Configuration

          Each suite may contain a YAML file, metadata.yml, which will be
          used to provide information to the suite of tests.

        ### Supported Config:

          ```yaml
          ---
          'name' :        '<User friendly name for the suite>'

          # Run this suite by default
          'default_run' : <true|false> => Default: false
          ```
    EOM
    task :suites, [:suite, :nodeset] => ['spec_prep'] do |t,args|
      suite = args[:suite]
      nodeset = args[:nodeset]

      # Record Tasks That Fail
      # Need to figure out how to capture the errors
      failures = Hash.new

      suite_basedir = File.join(@base_dir, 'spec/acceptance/suites')

      if ENV['BEAKER_suite_basedir']
        suite_basedir = ENV['BEAKER_suite_basedir']
      end

      raise("Error: Suites Directory at '#{suite_basedir}'!") unless File.directory?(suite_basedir)

      if suite && (suite != 'ALL')
        unless File.directory?(File.join(suite_basedir, suite))
          STDERR.puts("Error: Could not find suite '#{suite}'")
          STDERR.puts("Available Suites:")
          STDERR.puts('  * ' + Dir.glob(
            File.join(suite_basedir, '*')).sort.map{ |x|
              File.basename(x)
            }.join("\n  * ")
          )
          exit(1)
        end
      end

      suite_config = {
        'fail_fast' => true
      }
       = File.join(suite_basedir, 'config.yml')
      if File.file?()
        suite_config.merge!(YAML.load_file())
      end

      suites = Hash.new

      if suite && (suite != 'ALL')
        suites[suite] = Hash.new
        # If a suite was set, make sure it runs.
        suites[suite]['default_run'] = true
      else
        Dir.glob(File.join(suite_basedir,'*')) do |file|
          if File.directory?(file)
            suites[File.basename(file)] = Hash.new

            if suite == 'ALL'
              suites[File.basename(file)]['default_run'] = true
            end
          end
        end
      end

      suites.keys.each do |ste|
        suites[ste]['name']  = ste
        suites[ste]['path']  = File.join(suite_basedir, ste)

         = File.join(suites[ste]['path'], 'metadata.yml')
        if File.file?()
          suites[ste]['metadata'] = YAML.load_file()
        end

        unless File.directory?(File.join(suites[ste]['path'],'nodesets'))
          Dir.chdir(suites[ste]['path']) do
            if File.directory?('../../nodesets')
              FileUtils.ln_s('../../nodesets', 'nodesets')
            end
          end
        end

        suites[ste].merge!(suites[ste]['metadata']) if suites[ste]['metadata']

        # Ensure that the 'default' suite runs unless explicitly disabled.
        if suites['default']
          if ( suites['default']['default_run'].nil? ) || ( suites['default']['default_run'] == true )
            suites['default']['default_run'] = true
          end
        end
      end

      raise("Error: No Suites Found in '#{suite_basedir}'!") if suites.empty?

      # Need to ensure that 'default' is first
      ordered_suites = suites.keys.sort
      default_suite = ordered_suites.delete('default')
      ordered_suites.unshift(default_suite) if default_suite

      suite_start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      ordered_suites.each do |ste|

        next unless (suites[ste]['default_run'] == true)

        name = suites[ste]['name']

        $stdout.puts("\n\n=== Suite '#{name}' Starting ===\n\n")

        nodesets = Array.new
        nodeset_path = File.join(suites[ste]['path'],'nodesets')

        if nodeset
          if nodeset == 'ALL'
            nodesets = Dir.glob(File.join(nodeset_path, '*.yml'))

            # Make sure we run the default set first
            default_set = nodesets.delete(File.join(nodeset_path, 'default.yml'))
            nodesets.unshift(default_set) if default_set
          else
            nodeset.split(':').each do |tgt_nodeset|
              nodesets << File.join(nodeset_path, "#{tgt_nodeset.strip}.yml")
            end
          end
        else
          nodesets << File.join(nodeset_path, 'default.yml')
        end

        refined_nodesets = []

        nodesets.each do |nodeset_yml|
          parsed_nodeset = ::Beaker::Options::HostsFileParser.parse_hosts_file(nodeset_yml)

          # Default to multi-node testing for backwards compatibility
          multi_node = (parsed_nodeset[:multi_node] == false ? false: true)

          if multi_node
            refined_nodesets.push(nodeset_yml)
          else
            parsed_nodeset_hosts = parsed_nodeset.delete(:HOSTS)

            parsed_nodeset_hosts.each do |k,v|

              v[:roles] ||= []
              v[:roles] |= ['default']

              tmp_nodeset = {
                :HOSTS  => { k => v },
                :CONFIG => parsed_nodeset
              }

              tmp_nodeset_file = Tempfile.new("nodeset_#{k}-")
              tmp_nodeset_file.write(tmp_nodeset.to_yaml)
              tmp_nodeset_file.close

              refined_nodesets.push(tmp_nodeset_file.path)

              at_exit do
                if tmp_nodeset_file && File.exist?(tmp_nodeset_file.path)
                  tmp_nodeset_file.close
                  tmp_nodeset_file.unlink
                end
              end
            end
          end
        end

        refined_nodesets.sort.each do |nodeset_yml|
          unless File.file?(nodeset_yml)
            # Get here if user has specified a non-existent nodeset or the
            # implied `default` nodeset does not exist.
            if suite_config['fail_fast']
              fail("*** Suite #{name} Nodeset '#{File.basename(nodeset_yml, '.yml')}' Not Found ***")
            else
              $stdout.puts("=== Suite #{name} Nodeset '#{File.basename(nodeset_yml, '.yml')}' Not Found, Skipping ===")
              next
            end
          end

          ENV['BEAKER_setfile'] = nodeset_yml

          Rake::Task[:beaker].clear
          RSpec::Core::RakeTask.new(:beaker) do |tsk|
            tsk.rspec_opts = ['--color']
            tsk.pattern = File.join(suites[ste]['path'])
          end

          current_suite_task = Rake::Task[:beaker]

          if suite_config['fail_fast'] == true
            current_suite_task.execute
          else
            begin
              current_suite_task.execute
            rescue SystemExit
              failures[suites[ste]['name']] = {
                'path'    => suites[ste]['path'],
                'nodeset' => File.basename(nodeset_yml, '.yml')
              }
            end
          end

          $stdout.puts("\n\n=== Suite '#{name}' Complete ===\n\n")
        end
      end
      suite_end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

      suite_run_time = ((suite_end_time - suite_start_time)/60).round(2)

      $stdout.puts("== Total Runtime: #{suite_run_time} minutes ==\n\n")

      unless failures.keys.empty?
        $stdout.puts("The following tests had failures:")
        failures.keys.sort.each do |ste|
          $stdout.puts("  * #{ste} => #{failures[ste]['path']} on #{failures[ste]['nodeset']}")
        end
      end
    end
  end
end