summaryrefslogtreecommitdiff
path: root/tasks/parallel.rake
blob: 4192ad67e424ef5e5a2b6d953f29dbafb0a9d8fb (plain)
1
2
3
4
5
6
7
8
9
10
11
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
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
349
350
351
352
353
354
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# encoding: utf-8

require 'rubygems'
require 'thread'
begin
  require 'rspec'
  require 'rspec/core/formatters/helpers'
  require 'facter'
rescue LoadError
  # Don't define the task if we don't have rspec or facter present
else
  module Parallel
    module RSpec
      #
      # Responsible for buffering the output of RSpec's progress formatter.
      #
      class ProgressFormatBuffer
        attr_reader :pending_lines
        attr_reader :failure_lines
        attr_reader :examples
        attr_reader :failures
        attr_reader :pending
        attr_reader :failed_example_lines
        attr_reader :state

        module OutputState
          HEADER = 1
          PROGRESS = 2
          SUMMARY = 3
          PENDING = 4
          FAILURES = 5
          DURATION = 6
          COUNTS = 7
          FAILED_EXAMPLES = 8
        end

        def initialize(io, color)
          @io = io
          @color = color
          @state = OutputState::HEADER
          @pending_lines = []
          @failure_lines = []
          @examples = 0
          @failures = 0
          @pending = 0
          @failed_example_lines = []
        end

        def color?
          @color
        end

        def read
          # Parse and ignore the one line header
          if @state == OutputState::HEADER
            begin
              @io.readline
            rescue EOFError
              return nil
            end
            @state = OutputState::PROGRESS
            return ''
          end

          # If the progress has been read, parse the summary
          if @state == OutputState::SUMMARY
            parse_summary
            return nil
          end

          # Read the progress output up to 128 bytes at a time
          # 128 is a small enough number to show some progress, but not too small that
          # we're constantly writing synchronized output
          data = @io.read(128)
          return nil unless data

          data = @remainder + data if @remainder

          # Check for the end of the progress line
          if (index = data.index "\n")
            @state = OutputState::SUMMARY
            @remainder = data[(index+1)..-1]
            data = data[0...index]
          # Check for partial ANSI escape codes in colorized output
          elsif @color && !data.end_with?("\e[0m") && (index = data.rindex("\e[", -6))
            @remainder = data[index..-1]
            data = data[0...index]
          else
            @remainder = nil
          end

          data
        end

        private

        def parse_summary
          # If there is a remainder, concat it with the next line and handle each line
          unless @remainder.empty?
            lines = @remainder
            eof = false
            begin
              lines += @io.readline
            rescue EOFError
              eof = true
            end
            lines.each_line do |line|
              parse_summary_line line
            end
            return if eof
          end

          # Process the rest of the lines
          begin
            @io.each_line do |line|
              parse_summary_line line
            end
          rescue EOFError
          end
        end

        def parse_summary_line(line)
          line.chomp!
          return if line.empty?

          if line == 'Pending:'
            @status = OutputState::PENDING
            return
          elsif line == 'Failures:'
            @status = OutputState::FAILURES
            return
          elsif line == 'Failed examples:'
            @status = OutputState::FAILED_EXAMPLES
            return
          elsif (line.match /^Finished in ((\d+\.?\d*) minutes?)? ?(\d+\.?\d*) seconds?$/)
            @status = OutputState::DURATION
            return
          elsif (match = line.gsub(/\e\[\d+m/, '').match /^(\d+) examples?, (\d+) failures?(, (\d+) pending)?$/)
            @status = OutputState::COUNTS
            @examples = match[1].to_i
            @failures = match[2].to_i
            @pending = (match[4] || 0).to_i
            return
          end

          case @status
            when OutputState::PENDING
              @pending_lines << line
            when OutputState::FAILURES
              @failure_lines << line
            when OutputState::FAILED_EXAMPLES
              @failed_example_lines << line
          end
        end
      end

      #
      # Responsible for parallelizing spec testing.
      #
      class Parallelizer
        include ::RSpec::Core::Formatters::Helpers

        # Number of processes to use
        attr_reader :process_count
        # Approximate size of each group of tests
        attr_reader :group_size

        def initialize(process_count, group_size, color)
          @process_count = process_count
          @group_size = group_size
          @color = color
        end

        def color?
          @color
        end

        def run
          @start_time = Time.now

          groups = group_specs
          fail red('error: no specs were found') if groups.length == 0

          begin
            run_specs groups
          ensure
            groups.each do |file|
              File.unlink(file)
            end
          end
        end

        private

        def group_specs
          # Spawn the rspec_grouper utility to perform the test grouping
          # We do this in a separate process to limit this processes' long-running footprint
          io = IO.popen("ruby util/rspec_grouper #{@group_size}")

          header = true
          spec_group_files = []
          io.each_line do |line|
            line.chomp!
            header = false if line.empty?
            next if header || line.empty?
            spec_group_files << line
          end

          _, status = Process.waitpid2(io.pid)
          io.close

          fail red('error: no specs were found.') unless status.success?
          spec_group_files
        end

        def run_specs(groups)
          puts "Processing #{groups.length} spec group(s) with #{@process_count} worker(s)"

          interrupted = false
          success = true
          worker_threads = []
          group_index = -1
          pids = Array.new(@process_count)
          mutex = Mutex.new

          # Handle SIGINT by killing child processes
          original_handler = Signal.trap :SIGINT do
            break if interrupted
            interrupted = true

            # Can't synchronize in a trap context, so read dirty
            pids.each do |pid|
              begin
                Process.kill(:SIGKILL, pid) if pid
              rescue Errno::ESRCH
              end
            end
            puts yellow("\nshutting down...")
          end

          buffers = []

          process_count.times do |thread_id|
            worker_threads << Thread.new do
              while !interrupted do
                # Get the spec file for this rspec run
                group = mutex.synchronize { if group_index < groups.length then groups[group_index += 1] else nil end }
                break unless group && !interrupted

                # Spawn the worker process with redirected output
                io = IO.popen("ruby util/rspec_runner #{group}")
                pids[thread_id] = io.pid

                # TODO: make the buffer pluggable to handle other output formats like documentation
                buffer = ProgressFormatBuffer.new(io, @color)

                # Process the output
                while !interrupted
                  output = buffer.read
                  break unless output && !interrupted
                  next if output.empty?
                  mutex.synchronize { print output }
                end

                # Kill the process if we were interrupted, just to be sure
                if interrupted
                  begin
                    Process.kill(:SIGKILL, pids[thread_id])
                  rescue Errno::ESRCH
                  end
                end

                # Reap the process
                result = Process.waitpid2(pids[thread_id])[1].success?
                io.close
                pids[thread_id] = nil
                mutex.synchronize do
                  buffers << buffer
                  success &= result
                end
              end
            end
          end

          # Join all worker threads
          worker_threads.each do |thread|
            thread.join
          end

          Signal.trap :SIGINT, original_handler
          fail yellow('execution was interrupted') if interrupted

          dump_summary buffers
          success
        end

        def colorize(text, color_code)
          if @color
            "#{color_code}#{text}\e[0m"
          else
            text
          end
        end

        def red(text)
          colorize(text, "\e[31m")
        end

        def green(text)
          colorize(text, "\e[32m")
        end

        def yellow(text)
          colorize(text, "\e[33m")
        end

        def dump_summary(buffers)
          puts

          # Print out the pending tests
          print_header = true
          buffers.each do |buffer|
            next if buffer.pending_lines.empty?
            if print_header
              puts "\nPending:"
              print_header = false
            end
            puts buffer.pending_lines
          end

          # Print out the failures
          print_header = true
          buffers.each do |buffer|
            next if buffer.failure_lines.empty?
            if print_header
              puts "\nFailures:"
              print_header = false
            end
            puts
            puts buffer.failure_lines
          end

          # Print out the run time
          puts "\nFinished in #{format_duration(Time.now - @start_time)}"

          # Count all of the examples
          examples = 0
          failures = 0
          pending = 0
          buffers.each do |buffer|
            examples += buffer.examples
            failures += buffer.failures
            pending += buffer.pending
          end
          if failures > 0
            puts red(summary_count_line(examples, failures, pending))
          elsif pending > 0
            puts yellow(summary_count_line(examples, failures, pending))
          else
            puts green(summary_count_line(examples, failures, pending))
          end

          # Print out the failed examples
          print_header = true
          buffers.each do |buffer|
            next if buffer.failed_example_lines.empty?
            if print_header
              puts "\nFailed examples:"
              print_header = false
            end
            puts buffer.failed_example_lines
          end
        end

        def summary_count_line(examples, failures, pending)
          summary = pluralize(examples, "example")
          summary << ", " << pluralize(failures, "failure")
          summary << ", #{pending} pending" if pending > 0
          summary
        end
      end
    end
  end

  namespace 'parallel' do
    def color_output?
      # Check with RSpec to see if color is enabled
      config = ::RSpec::Core::Configuration.new
      config.error_stream = $stderr
      config.output_stream = $stdout
      options = ::RSpec::Core::ConfigurationOptions.new []
      options.parse_options
      options.configure config
      config.color
    end

    desc 'Runs specs in parallel.'
    task 'spec', :process_count, :group_size do |_, args|
      # Default group size in rspec examples
      DEFAULT_GROUP_SIZE = 1000

      process_count = [(args[:process_count] || Facter["processorcount"].value).to_i, 1].max
      group_size = [(args[:group_size] || DEFAULT_GROUP_SIZE).to_i, 1].max

      abort unless Parallel::RSpec::Parallelizer.new(process_count, group_size, color_output?).run
    end
  end
end