File: bench_regression

package info (click to toggle)
ruby-active-model-serializers 0.10.12-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,752 kB
  • sloc: ruby: 13,138; sh: 53; makefile: 6
file content (316 lines) | stat: -rwxr-xr-x 8,631 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/env ruby
require 'fileutils'
require 'pathname'
require 'shellwords'
require 'English'

############################
# USAGE
#
# bundle exec bin/bench_regression <ref1> <ref2>
#   <ref1> defaults to the current branch
#   <ref2> defaults to the master branch
# bundle exec bin/bench_regression current                    # will run on the current branch
# bundle exec bin/bench_regression revisions 792fb8a90 master # every revision inclusive
# bundle exec bin/bench_regression           792fb8a90 master --repeat-count 2 --env CACHE_ON=off
# bundle exec bin/bench_regression vendor
###########################

class BenchRegression
  ROOT = Pathname File.expand_path(File.join(*['..', '..']), __FILE__)
  TMP_DIR_NAME = File.join('tmp', 'bench')
  TMP_DIR = File.join(ROOT, TMP_DIR_NAME)
  E_TMP_DIR = Shellwords.shellescape(TMP_DIR)
  load ROOT.join('bin', 'bench')

  attr_reader :source_stasher

  def initialize
    @source_stasher = SourceStasher.new
  end

  class SourceStasher
    attr_reader :gem_require_paths, :gem_paths
    attr_writer :vendor

    def initialize
      @gem_require_paths = []
      @gem_paths = []
      refresh_temp_dir
      @vendor = false
    end

    def temp_dir_empty?
      File.directory?(TMP_DIR) &&
        Dir[File.join(TMP_DIR, '*')].none?
    end

    def empty_temp_dir
      return if @vendor
      return if temp_dir_empty?
      FileUtils.mkdir_p(TMP_DIR)
      Dir[File.join(TMP_DIR, '*')].each do |file|
        if File.directory?(file)
          FileUtils.rm_rf(file)
        else
          FileUtils.rm(file)
        end
      end
    end

    def fill_temp_dir
      vendor_files(Dir[File.join(ROOT, 'test', 'benchmark', '*.{rb,ru}')])
      # vendor_file(File.join('bin', 'bench'))
      housekeeping { empty_temp_dir }
      vendor_gem('benchmark-ips')
    end

    def vendor_files(files)
      files.each do |file|
        vendor_file(file)
      end
    end

    def vendor_file(file)
      FileUtils.cp(file, File.join(TMP_DIR, File.basename(file)))
    end

    def vendor_gem(gem_name)
      directory_name = `bundle exec gem unpack benchmark-ips --target=#{E_TMP_DIR}`[/benchmark-ips.+\d/]
      gem_paths << File.join(TMP_DIR, directory_name)
      gem_require_paths << File.join(TMP_DIR_NAME, directory_name, 'lib')
      housekeeping { remove_vendored_gems }
    end

    def remove_vendored_gems
      return if @vendor
      FileUtils.rm_rf(*gem_paths)
    end

    def refresh_temp_dir
      empty_temp_dir
      fill_temp_dir
    end

    def housekeeping
      at_exit { yield }
    end
  end

  module RevisionMethods
    module_function
    def current_branch
      @current_branch ||= `cat .git/HEAD | cut -d/ -f3,4,5`.chomp
    end

    def current_revision
      `git rev-parse --short HEAD`.chomp
    end

    def revision_description(rev)
      `git log --oneline -1 #{rev}`.chomp
    end

    def revisions(start_ref, end_ref)
      cmd = "git rev-list --reverse #{start_ref}..#{end_ref}"
      `#{cmd}`.chomp.split("\n")
    end

    def checkout_ref(ref)
      `git checkout #{ref}`.chomp
      if $CHILD_STATUS
        STDERR.puts "Checkout failed: #{ref}, #{$CHILD_STATUS.exitstatus}" unless $CHILD_STATUS.success?
        $CHILD_STATUS.success?
      else
        true
      end
    end

    def clean_head
      system('git reset --hard --quiet')
    end
  end
  module ShellMethods

    def sh(cmd)
      puts cmd
      # system(cmd)
      run(cmd)
      # env = {}
      # # out = STDOUT
      # pid = spawn(env, cmd)
      # Process.wait(pid)
      # pid = fork do
      #   exec cmd
      # end
      # Process.waitpid2(pid)
      # puts $CHILD_STATUS.exitstatus
    end

    require 'pty'
    # should consider trapping SIGINT in here
    def run(cmd)
      puts cmd
      child_process = ''
      result = ''
      # http://stackoverflow.com/a/1162850
      # stream output of subprocess
      begin
        PTY.spawn(cmd) do |stdin, _stdout, pid|
          begin
            # Do stuff with the output here. Just printing to show it works
            stdin.each do |line|
              print line
              result << line
            end
            child_process = PTY.check(pid)
          rescue Errno::EIO
            puts 'Errno:EIO error, but this probably just means ' \
                  'that the process has finished giving output'
          end
        end
      rescue PTY::ChildExited
        puts 'The child process exited!'
      end
      unless (child_process && child_process.success?)
        exitstatus = child_process.exitstatus
        puts "FAILED: #{child_process.pid} exited with status #{exitstatus.inspect} due to failed command #{cmd}"
        exit exitstatus || 1
      end
      result
    end

    def bundle(ref)
      system("rm -f Gemfile.lock")
      # This is absolutely critical for bundling to work
      Bundler.with_clean_env do
        system("bundle check ||
          bundle install --local ||
          bundle install ||
          bundle update")
      end

      # if $CHILD_STATUS
      #   STDERR.puts "Bundle failed at: #{ref}, #{$CHILD_STATUS.exitstatus}" unless $CHILD_STATUS.success?
      #   $CHILD_STATUS.success?
      # else
      #   false
      # end
    end
  end
  include ShellMethods
  include RevisionMethods

  def benchmark_refs(ref1: nil, ref2: nil, cmd:)
    checking_out = false
    ref0 = current_branch
    ref1 ||= current_branch
    ref2 ||= 'master'
    p [ref0, ref1, ref2, current_revision]

    run_benchmark_at_ref(cmd, ref1)
    p [ref0, ref1, ref2, current_revision]
    run_benchmark_at_ref(cmd, ref2)
    p [ref0, ref1, ref2, current_revision]

    checking_out = true
    checkout_ref(ref0)
  rescue Exception # rubocop:disable Lint/RescueException
    STDERR.puts "[ERROR] #{$!.message}"
    checkout_ref(ref0) unless checking_out
    raise
  end

  def benchmark_revisions(ref1: nil, ref2: nil, cmd:)
    checking_out = false
    ref0 = current_branch
    ref1 ||= current_branch
    ref2 ||= 'master'

    revisions(ref1, ref2).each do |rev|
      STDERR.puts "Checking out: #{revision_description(rev)}"

      run_benchmark_at_ref(cmd, rev)
      clean_head
    end
    checking_out = true
    checkout_ref(ref0)
  rescue Exception # rubocop:disable Lint/RescueException
    STDERR.puts "[ERROR]: #{$!.message}"
    checkout_ref(ref0) unless checking_out
    raise
  end

  def run_benchmark_at_ref(cmd, ref)
    checkout_ref(ref)
    run_benchmark(cmd, ref)
  end

  def run_benchmark(cmd, ref = nil)
    ref ||= current_revision
    bundle(ref) &&
      benchmark_tests(cmd, ref)
  end

  def benchmark_tests(cmd, ref)
    base = E_TMP_DIR
    # cmd.sub('bin/bench', 'tmp/revision_runner/bench')
    # bundle = Gem.bin('bunle'
    # Bundler.with_clean_env(&block)

    # cmd = Shellwords.shelljoin(cmd)
    # cmd = "COMMIT_HASH=#{ref} BASE=#{base} bundle exec ruby  -rbenchmark/ips #{cmd}"
    # Add vendoring benchmark/ips to load path

    # CURRENT THINKING: IMPORTANT
    # Pass into require statement as RUBYOPTS i.e. via env rather than command line argument
    # otherwise, have a 'fast ams benchmarking' module that extends benchmarkings to add the 'ams'
    # method but doesn't depend on benchmark-ips
    options = {
      commit_hash: ref,
      base: base,
      rubyopt: Shellwords.shellescape("-Ilib:#{source_stasher.gem_require_paths.join(':')}")
    }
    BenchmarkDriver.parse_argv_and_run(ARGV.dup, options)
  end
end

if $PROGRAM_NAME == __FILE__
  benchmarking = BenchRegression.new

  case ARGV[0]
  when 'current'
    # Run current branch only

    # super simple command line parsing
    args = ARGV.dup
    _    = args.shift # remove 'current' from args
    cmd  = args
    benchmarking.run_benchmark(cmd)
  when 'revisions'
    # Runs on every revision

    # super simple command line parsing
    args = ARGV.dup
    _         = args.shift
    ref1      = args.shift # remove 'revisions' from args
    ref2      = args.shift
    cmd       = args
    benchmarking.benchmark_revisions(ref1: ref1, ref2: ref2, cmd: cmd)
  when 'vendor'
    # Just prevents vendored files from being cleaned up
    # at exit. (They are vendored at initialize.)
    benchmarking.source_stasher.vendor = true
  else
    # Default: Compare current_branch to master
    # Optionally: pass in two refs as args to `bin/bench_regression`
    # TODO: Consider checking across more revisions, to automatically find problems.

    # super simple command line parsing
    args = ARGV.dup
    ref1      = args.shift
    ref2      = args.shift
    cmd       = args
    benchmarking.benchmark_refs(ref1: ref1, ref2: ref2, cmd: cmd)
  end
end