polyrun-legacy 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +8 -0
  3. data/CODE_OF_CONDUCT.md +26 -0
  4. data/CONTRIBUTING.md +23 -0
  5. data/LICENSE +21 -0
  6. data/README.md +115 -0
  7. data/SECURITY.md +25 -0
  8. data/bin/polyrun +5 -0
  9. data/lib/polyrun/legacy/cli.rb +102 -0
  10. data/lib/polyrun/legacy/compat.rb +53 -0
  11. data/lib/polyrun/legacy/config_commands.rb +52 -0
  12. data/lib/polyrun/legacy/configuration.rb +115 -0
  13. data/lib/polyrun/legacy/coverage_formats.rb +95 -0
  14. data/lib/polyrun/legacy/coverage_reports.rb +74 -0
  15. data/lib/polyrun/legacy/failure_reports.rb +100 -0
  16. data/lib/polyrun/legacy/junit_reports.rb +115 -0
  17. data/lib/polyrun/legacy/lifecycle.rb +95 -0
  18. data/lib/polyrun/legacy/merge.rb +139 -0
  19. data/lib/polyrun/legacy/options.rb +48 -0
  20. data/lib/polyrun/legacy/partition.rb +22 -0
  21. data/lib/polyrun/legacy/partition_plan.rb +105 -0
  22. data/lib/polyrun/legacy/paths.rb +59 -0
  23. data/lib/polyrun/legacy/planning_commands.rb +104 -0
  24. data/lib/polyrun/legacy/process_launch.rb +78 -0
  25. data/lib/polyrun/legacy/report_commands.rb +61 -0
  26. data/lib/polyrun/legacy/run_shards.rb +59 -0
  27. data/lib/polyrun/legacy/shard_commands.rb +132 -0
  28. data/lib/polyrun/legacy/shard_env.rb +34 -0
  29. data/lib/polyrun/legacy/shard_heap.rb +35 -0
  30. data/lib/polyrun/legacy/table.rb +54 -0
  31. data/lib/polyrun/legacy/timings.rb +103 -0
  32. data/lib/polyrun/legacy/version.rb +5 -0
  33. data/lib/polyrun/legacy/worker_wait.rb +80 -0
  34. data/lib/polyrun/legacy/yaml_data.rb +116 -0
  35. data/lib/polyrun/legacy.rb +7 -0
  36. data/polyrun-legacy.gemspec +44 -0
  37. metadata +91 -0
@@ -0,0 +1,105 @@
1
+ module Polyrun
2
+ module Legacy
3
+ module Partition
4
+ class Plan
5
+ COST_STRATEGIES = %w[cost cost_binpack binpack timing].freeze
6
+ HASH_STRATEGIES = %w[hrw rendezvous].freeze
7
+
8
+ attr_reader :buckets
9
+
10
+ def initialize(paths, workers, settings)
11
+ @workers = workers
12
+ @costs = timing_costs(settings[:timing])
13
+ @strategy = settings[:strategy] || (@costs.empty? ? "round_robin" : "cost_binpack")
14
+ @seed = settings[:seed]
15
+ @default_cost = mean_cost
16
+ @buckets = assign(paths)
17
+ end
18
+
19
+ def manifest(index)
20
+ out = {
21
+ "shard_index" => index, "shard_total" => @workers, "strategy" => @strategy,
22
+ "seed" => @seed, "paths" => @buckets[index] || []
23
+ }
24
+ costs = shard_seconds
25
+ out["shard_seconds"] = costs if costs
26
+ out
27
+ end
28
+
29
+ private
30
+
31
+ def assign(paths)
32
+ case @strategy
33
+ when "round_robin"
34
+ Partition.round_robin(paths, @workers)
35
+ when "lazy_robin"
36
+ raise ArgumentError, "lazy_robin requires timing data" if @costs.empty?
37
+
38
+ Partition.round_robin(paths, @workers)
39
+ when "preserve_order_round_robin"
40
+ Partition.distribute(paths, @workers)
41
+ when *COST_STRATEGIES
42
+ raise ArgumentError, "#{@strategy} requires timing data" if @costs.empty?
43
+
44
+ balance(paths)
45
+ when *HASH_STRATEGIES
46
+ rendezvous(paths)
47
+ else
48
+ raise ArgumentError, "unknown partition strategy #{@strategy.inspect}"
49
+ end
50
+ end
51
+
52
+ def timing_costs(path)
53
+ return {} unless path
54
+
55
+ costs = {}
56
+ Timings.read(path).each { |item, stats| costs[File.expand_path(item)] = Timings.weight(stats) }
57
+ costs
58
+ end
59
+
60
+ def mean_cost
61
+ return 1.0 if @costs.empty?
62
+
63
+ @costs.values.inject(0.0) { |total, cost| total + cost } / @costs.size
64
+ end
65
+
66
+ def cost(path, fallback = @default_cost)
67
+ @costs.fetch(File.expand_path(path), fallback)
68
+ end
69
+
70
+ def balance(paths)
71
+ shards = Array.new(@workers) { [] }
72
+ available = ShardHeap.new(@workers)
73
+ weights = paths.map { |path| [path, cost(path)] }
74
+ weights.sort_by { |path, weight| [-weight, path] }.each do |path, weight|
75
+ index = available.assign(weight)
76
+ shards[index] << path
77
+ end
78
+ shards
79
+ end
80
+
81
+ def rendezvous(paths)
82
+ require "digest/sha2"
83
+ seed = @seed.to_s.empty? ? "polyrun-hrw" : @seed
84
+ shards = Array.new(@workers) { [] }
85
+ paths.each do |path|
86
+ winner = (0...@workers).max_by { |index| Digest::SHA256.hexdigest("#{seed}\n#{path}\n#{index}") }
87
+ shards[winner] << path
88
+ end
89
+ shards
90
+ end
91
+
92
+ def shard_seconds
93
+ weighted = COST_STRATEGIES.include?(@strategy) || @strategy == "lazy_robin"
94
+ include_costs = weighted || (HASH_STRATEGIES.include?(@strategy) && !@costs.empty?)
95
+ return unless include_costs
96
+
97
+ fallback = weighted ? @default_cost : 0.0
98
+ (0...@workers).map do |index|
99
+ (@buckets[index] || []).inject(0.0) { |total, path| total + cost(path, fallback) }
100
+ end
101
+ end
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,59 @@
1
+ require "rbconfig"
2
+
3
+ module Polyrun
4
+ module Legacy
5
+ module Paths
6
+ SUITE_GLOBS = {"rspec" => "spec/**/*_spec.rb", "minitest" => "test/**/*_test.rb", "sus" => "test/**/*.rb"}.freeze
7
+
8
+ module_function
9
+
10
+ def read(path)
11
+ File.readlines(path).map { |line| line.strip }.reject { |line| line.empty? }
12
+ end
13
+
14
+ def glob(patterns)
15
+ patterns.map { |pattern| Dir.glob(pattern).sort }.flatten.select { |path| File.file?(path) }.uniq
16
+ end
17
+
18
+ def resolve(settings, explicit, suite = nil)
19
+ return explicit unless explicit.empty?
20
+ return read(settings[:paths_file]) if settings[:paths_file]
21
+ return glob(settings[:globs]) unless settings[:globs].empty?
22
+ return [] unless suite
23
+ return read("spec/spec_paths.txt") if suite == "rspec" && File.file?("spec/spec_paths.txt")
24
+
25
+ glob([SUITE_GLOBS.fetch(suite)])
26
+ end
27
+
28
+ def runner(suite)
29
+ if suite == "minitest"
30
+ ruby = ruby_executable
31
+ return [ruby, "bin/rails", "test"] if File.file?("bin/rails")
32
+
33
+ return [ruby, "-I", "test", "-e", "paths = ARGV.dup; ARGV.clear; paths.each { |path| require File.expand_path(path) }"]
34
+ end
35
+
36
+ command = [suite]
37
+ File.file?("Gemfile") ? %w[bundle exec] + command : command
38
+ end
39
+
40
+ def ruby_executable
41
+ config = defined?(RbConfig) ? RbConfig::CONFIG : Config::CONFIG
42
+ File.join(config.fetch("bindir"), config.fetch("ruby_install_name") + config["EXEEXT"].to_s)
43
+ end
44
+
45
+ def default_suite(partition)
46
+ name = partition["suite"]
47
+ if name && name != "auto"
48
+ raise ArgumentError, "unknown suite runner #{name.inspect}" unless SUITE_GLOBS.key?(name)
49
+
50
+ return name
51
+ end
52
+ return "rspec" if File.file?("spec/spec_paths.txt") || !glob([SUITE_GLOBS["rspec"]]).empty?
53
+ return "sus" if File.file?("config/sus.rb") && !glob([SUITE_GLOBS["sus"]]).empty?
54
+
55
+ glob([SUITE_GLOBS["minitest"]]).empty? ? "rspec" : "minitest"
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,104 @@
1
+ module Polyrun
2
+ module Legacy
3
+ module PlanningCommands
4
+ module_function
5
+
6
+ def plan(argv, config)
7
+ settings = matrix_settings(config)
8
+ parser = matrix_parser("plan", settings)
9
+ return 0 unless Options.parse(parser, argv)
10
+
11
+ index, total = shard_numbers(settings)
12
+ partition = matrix_plan(argv, total, settings)
13
+ Compat.load_json
14
+ puts JSON.generate(partition.manifest(index))
15
+ 0
16
+ end
17
+
18
+ def ci_run(name, argv, suite, config)
19
+ arguments, command = Options.split_command(argv)
20
+ settings = matrix_settings(config)
21
+ settings[:workers] = Options.env_value("POLYRUN_SHARD_PROCESSES", config.partition.fetch("shard_processes", 1))
22
+ parser = matrix_parser(name, settings)
23
+ return 0 unless Options.parse(parser, arguments)
24
+
25
+ command = Paths.runner(suite) + (command || []) if suite
26
+ raise ArgumentError, "specify a command after --" if command.nil? || command.empty?
27
+
28
+ index, total = shard_numbers(settings)
29
+ paths = matrix_plan(arguments, total, settings, suite).buckets[index] || []
30
+ workers = Options.integer(settings[:workers], "workers", 1)
31
+ return 0 if paths.empty?
32
+
33
+ run_ci_workers(command, paths, workers, index, total, settings)
34
+ end
35
+
36
+ def run_ci_workers(command, paths, workers, index, total, settings)
37
+ if workers == 1
38
+ settings[:first_index] = index
39
+ RunShards.run_buckets(command, [paths], total, settings)
40
+ else
41
+ settings[:matrix] = [index, total] if total > 1
42
+ RunShards.run_buckets(command, Partition.round_robin(paths, workers), workers, settings)
43
+ end
44
+ end
45
+
46
+ def env(argv, config)
47
+ settings = matrix_settings(config)
48
+ parser = OptionParser.new do |flags|
49
+ flags.banner = "Usage: polyrun env [--shard INDEX] [--total N] [--database TEMPLATE]"
50
+ shard_flags(flags, settings)
51
+ flags.on("--database TEMPLATE", "Database name with optional %{shard}") { |value| settings[:database] = value }
52
+ end
53
+ return 0 unless Options.parse(parser, argv)
54
+ raise ArgumentError, parser.banner unless argv.empty?
55
+
56
+ index, total = shard_numbers(settings)
57
+ ShardEnv.for_shard(index, total, settings[:database]).sort.each do |name, value|
58
+ quoted = value.index(/\A[\w.%+-]+\z/) ? value : "'" + value.gsub("'") { "'\\''" } + "'"
59
+ puts "export #{name}=#{quoted}"
60
+ end
61
+ 0
62
+ end
63
+
64
+ def matrix_plan(arguments, total, settings, suite = nil)
65
+ paths = Paths.resolve(settings, arguments, suite)
66
+ raise ArgumentError, "provide test paths, --paths-file, or --paths-glob" if paths.empty?
67
+
68
+ Partition::Plan.new(paths, total, settings)
69
+ end
70
+
71
+ def matrix_parser(name, settings)
72
+ OptionParser.new do |flags|
73
+ flags.banner = "Usage: polyrun #{name} [options] [PATH ...]"
74
+ shard_flags(flags, settings)
75
+ ShardCommands.partition_flags(flags, settings)
76
+ if settings.key?(:workers)
77
+ flags.on("--shard-processes N", "--workers N", "Processes in this matrix job") { |value| settings[:workers] = value }
78
+ flags.on("--worker-timeout SEC", "Maximum time per worker") { |value| settings[:worker_timeout] = value }
79
+ flags.on("--worker-log-dir DIR", "Write worker logs to this directory") { |value| settings[:worker_log_dir] = value }
80
+ end
81
+ end
82
+ end
83
+
84
+ def matrix_settings(config)
85
+ settings = config.shard_settings
86
+ settings[:shard], settings[:total] = ShardEnv.defaults(config.partition)
87
+ settings
88
+ end
89
+
90
+ def shard_numbers(settings)
91
+ index = Options.integer(settings[:shard], "shard", 0)
92
+ total = Options.integer(settings[:total], "total", 1)
93
+ raise ArgumentError, "shard_index out of range" if index >= total
94
+
95
+ [index, total]
96
+ end
97
+
98
+ def shard_flags(flags, settings)
99
+ flags.on("--shard INDEX", "Zero-based shard index") { |value| settings[:shard] = value }
100
+ flags.on("--total N", "Number of shards") { |value| settings[:total] = value }
101
+ end
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,78 @@
1
+ module Polyrun
2
+ module Legacy
3
+ module ProcessLaunch
4
+ module_function
5
+
6
+ def start(environment, command, options = {})
7
+ environment = child_environment(environment)
8
+ if Process.respond_to?(:spawn)
9
+ spawn_command(environment, command, options)
10
+ else
11
+ [fork { exec_command(environment, command, options) }, nil]
12
+ end
13
+ end
14
+
15
+ def spawn_command(environment, command, options)
16
+ spawn_options = {:pgroup => true} # rubocop:disable Style/HashSyntax
17
+ directory = options[:chdir]
18
+ if directory
19
+ if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
20
+ # JRuby's shell launch can continue after its chdir fails.
21
+ command = ["/bin/sh", "-c", 'cd -- "$1" || exit 2; shift; exec "$@"', "polyrun", directory] + command
22
+ else
23
+ spawn_options[:chdir] = directory
24
+ end
25
+ end
26
+ spawn_options[:out] = $stderr if options[:report]
27
+ if options[:log]
28
+ stream = File.open(options[:log], "w")
29
+ spawn_options[:out] = stream
30
+ spawn_options[:err] = stream
31
+ end
32
+ executable = command.first
33
+ arguments = command.drop(1) << spawn_options
34
+ [Process.spawn(environment, [executable, executable], *arguments), nil]
35
+ rescue SystemCallError, ArgumentError => error
36
+ (stream || $stderr).puts("polyrun: #{error.message}")
37
+ [nil, failure_status(error, options)]
38
+ ensure
39
+ stream.close if stream # rubocop:disable Style/SafeNavigation -- Ruby 1.8
40
+ end
41
+
42
+ def exec_command(environment, command, options)
43
+ Process.setpgid(0, 0)
44
+ environment.each do |name, value|
45
+ ENV[name] = value
46
+ end
47
+ Dir.chdir(options[:chdir]) if options[:chdir] # rubocop:disable ThreadSafety/DirChdir
48
+ if options[:log]
49
+ File.open(options[:log], "w") do |file|
50
+ $stdout.reopen(file)
51
+ $stderr.reopen(file)
52
+ end
53
+ elsif options[:report]
54
+ $stdout.reopen($stderr)
55
+ end
56
+ executable = command.first
57
+ exec([executable, executable], *command.drop(1))
58
+ rescue SystemCallError, ArgumentError => error
59
+ warn "polyrun: #{error.message}"
60
+ exit!(failure_status(error, options))
61
+ end
62
+
63
+ def failure_status(error, options)
64
+ return 2 if error.is_a?(ArgumentError)
65
+
66
+ options[:launch_failure_status] || (error.is_a?(Errno::ENOENT) ? 127 : 126)
67
+ end
68
+
69
+ def child_environment(environment)
70
+ child = {}
71
+ environment.each do |name, value|
72
+ child[name.to_s] = value.nil? ? nil : value.to_s # rubocop:disable Style/SafeNavigation -- Ruby 1.8
73
+ end
74
+ child
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,61 @@
1
+ module Polyrun
2
+ module Legacy
3
+ module ReportCommands
4
+ module_function
5
+
6
+ def arguments(argv, name, defaults)
7
+ settings = defaults.merge({:inputs => []}) # rubocop:disable Style/HashSyntax
8
+ parser = OptionParser.new do |flags|
9
+ flags.banner = "Usage: polyrun #{name} -i FILE [-o PATH] [options]"
10
+ flags.on("-i", "--input FILE", "Input JSON or glob (repeatable)") { |value| settings[:inputs] << value }
11
+ flags.on("-o", "--output PATH", "Destination") { |value| settings[:output] = value }
12
+ if settings.key?(:format)
13
+ flags.on("--format FORMAT", "Report format") { |value| settings[:format] = value }
14
+ end
15
+ yield flags, settings if block_given?
16
+ end
17
+ return unless Options.parse(parser, argv)
18
+
19
+ settings[:inputs].concat(argv)
20
+ settings
21
+ end
22
+
23
+ def inputs(settings)
24
+ raise ArgumentError, "provide at least one input file with -i" if settings[:inputs].empty?
25
+
26
+ Options.files(settings[:inputs])
27
+ end
28
+
29
+ def write(output, contents)
30
+ Compat.write_report(output, contents)
31
+ puts File.expand_path(output)
32
+ 0
33
+ end
34
+
35
+ def merge_timing(argv)
36
+ settings = arguments(argv, "merge-timing", {:output => "polyrun_timing.json"}) # rubocop:disable Style/HashSyntax
37
+ return 0 unless settings
38
+
39
+ timings = Timings.merge(inputs(settings))
40
+ write(settings[:output], JSON.generate(timings) + "\n")
41
+ end
42
+
43
+ def report_timing(argv)
44
+ settings = arguments(argv, "report-timing", {:format => "text", :top => 30}) do |flags, options| # rubocop:disable Style/HashSyntax
45
+ flags.on("--top N", "Maximum rows") { |value| options[:top] = value }
46
+ end
47
+ return 0 unless settings
48
+
49
+ paths = inputs(settings)
50
+ raise ArgumentError, "provide one merged timing file" unless paths.size == 1
51
+
52
+ count = Options.integer(settings[:top], "top", 0)
53
+ summary = Timings.report(Timings.read(paths.first), count, settings[:format])
54
+ return write(settings[:output], summary) if settings[:output]
55
+
56
+ print summary
57
+ 0
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,59 @@
1
+ module Polyrun
2
+ module Legacy
3
+ module RunShards
4
+ module_function
5
+
6
+ def run(command, paths, workers)
7
+ settings = {:run_empty => paths.empty?} # rubocop:disable Style/HashSyntax
8
+ run_buckets(command, Partition.round_robin(paths, workers), workers, settings)
9
+ end
10
+
11
+ def run_buckets(command, buckets, workers, settings)
12
+ children = []
13
+ raise ArgumentError, "specify a command after --" if command.empty? || command.first.empty?
14
+
15
+ timeout = worker_timeout(settings[:worker_timeout])
16
+ logs = log_directory(settings[:worker_log_dir])
17
+ buckets.each_with_index do |shard, index|
18
+ next if shard.empty? && !settings[:run_empty]
19
+
20
+ shard_index = index + settings.fetch(:first_index, 0)
21
+ environment = worker_env(shard_index, workers, settings)
22
+ log = logs && File.join(logs, "shard-#{shard_index}.log")
23
+ started = WorkerWait.now if timeout
24
+ pid, failure = ProcessLaunch.start(environment, command + shard, :log => log) # rubocop:disable Style/HashSyntax
25
+ children << [pid, shard_index, started, failure]
26
+ end
27
+ WorkerWait.wait(children, timeout)
28
+ ensure
29
+ WorkerWait.stop(children)
30
+ end
31
+
32
+ def worker_env(index, workers, settings)
33
+ environment = ShardEnv.for_shard(index, workers)
34
+ environment["POLYRUN_HOOKS_DISABLE"] = "1"
35
+ environment["POLYRUN_FAILURE_FRAGMENTS"] = "1" if settings[:merge_failures]
36
+ if settings[:matrix]
37
+ environment["POLYRUN_SHARD_MATRIX_INDEX"], environment["POLYRUN_SHARD_MATRIX_TOTAL"] = settings[:matrix].map { |value| value.to_s }
38
+ end
39
+ environment
40
+ end
41
+
42
+ def worker_timeout(value)
43
+ timeout = Float(value || Options.env_value("POLYRUN_WORKER_TIMEOUT_SEC", 0))
44
+ raise ArgumentError, "worker timeout must be finite and nonnegative" unless timeout.finite? && timeout >= 0
45
+
46
+ timeout if timeout > 0
47
+ end
48
+
49
+ def log_directory(value)
50
+ directory = value || Options.env_value("POLYRUN_WORKER_LOG_DIR", nil)
51
+ if !directory && %w[1 true yes].include?(ENV["POLYRUN_WORKER_OUTPUT_ROUTING"].to_s.downcase)
52
+ directory = "tmp/polyrun/workers"
53
+ end
54
+ FileUtils.mkdir_p(directory) if directory
55
+ directory
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,132 @@
1
+ module Polyrun
2
+ module Legacy
3
+ module ShardCommands
4
+ module_function
5
+
6
+ def run(name, argv, suite, config)
7
+ arguments, tail = Options.split_command(argv)
8
+ settings = run_settings(config, suite)
9
+ parser = run_parser(name, settings)
10
+ return 0 unless Options.parse(parser, arguments)
11
+
12
+ command, explicit = local_arguments(tail, arguments, settings, suite)
13
+ paths = local_paths(tail, explicit, settings, suite)
14
+
15
+ workers = Options.integer(settings[:workers], "workers", 1)
16
+ plan = Partition::Plan.new(paths, workers, settings)
17
+ settings[:run_empty] = paths.empty?
18
+ status = start_workers(name, config, command, plan.buckets, workers, settings)
19
+ merge_results(status, settings)
20
+ end
21
+
22
+ def run_settings(config, suite)
23
+ settings = config.shard_settings
24
+ settings[:workers] = config.workers
25
+ settings[:merge_coverage] = !!suite
26
+ formats = config.section("coverage")["formats"]
27
+ settings[:coverage_format] = Array(formats).join(",") if formats
28
+ settings
29
+ end
30
+
31
+ def start_workers(name, config, command, buckets, workers, settings)
32
+ if name == "start" && !%w[1 true yes].include?(ENV["POLYRUN_SKIP_PREPARE"].to_s.downcase)
33
+ status = Lifecycle.prepare_steps(config, false, false)
34
+ return status unless status == 0
35
+ end
36
+
37
+ RunShards.run_buckets(command, buckets, workers, settings)
38
+ end
39
+
40
+ def run_parser(name, settings)
41
+ OptionParser.new do |flags|
42
+ flags.banner = "Usage: polyrun #{name} [options] [PATH ...] -- COMMAND [ARG ...]"
43
+ flags.separator "For a command with its own arguments, put paths before the command or use a second --."
44
+ partition_flags(flags, settings)
45
+ flags.on("--workers N", "Number of workers") { |value| settings[:workers] = value }
46
+ flags.on("--worker-timeout SEC", "Maximum time per worker") { |value| settings[:worker_timeout] = value }
47
+ flags.on("--worker-log-dir DIR", "Write worker logs to this directory") { |value| settings[:worker_log_dir] = value }
48
+ flags.on("--[no-]merge-coverage", "Merge coverage after a successful run") { |value| settings[:merge_coverage] = value }
49
+ flags.on("--merge-output FILE", "Merged coverage path") { |value| settings[:coverage_output] = value }
50
+ flags.on("--merge-format LIST", "Merged coverage formats") { |value| settings[:coverage_format] = value }
51
+ flags.on("--merge-failures", "Merge worker failure reports") { settings[:merge_failures] = true }
52
+ flags.on("--merge-failures-output FILE", "Merged failures path") { |value| settings[:failures_output] = value }
53
+ flags.on("--merge-failures-format NAME", "Merged failures format") { |value| settings[:failures_format] = value }
54
+ end
55
+ end
56
+
57
+ def local_arguments(tail, explicit, settings, suite)
58
+ if tail.nil?
59
+ raise ArgumentError, "specify a command after --" unless suite
60
+
61
+ return [Paths.runner(suite), explicit]
62
+ end
63
+ boundary = tail.index("--")
64
+ return [tail.take(boundary), explicit + tail.drop(boundary + 1)] if boundary
65
+ return [tail, explicit] if suite || !explicit.empty? || settings[:cli_path_source]
66
+
67
+ [tail.take(1), tail.drop(1)]
68
+ end
69
+
70
+ def local_paths(tail, explicit, settings, suite)
71
+ if !suite && explicit.empty? && Array(tail).include?("--") && !settings[:cli_path_source]
72
+ return []
73
+ end
74
+
75
+ paths = Paths.resolve(settings, explicit, suite)
76
+ source = suite || settings[:paths_file] || !settings[:globs].empty?
77
+ raise ArgumentError, "no test paths found" if paths.empty? && source
78
+
79
+ paths
80
+ end
81
+
82
+ def merge_results(status, settings)
83
+ FailureReports.after_shards(settings) if settings[:merge_failures]
84
+ return status unless status == 0 && settings[:merge_coverage]
85
+
86
+ CoverageReports.after_shards(settings[:coverage_output], settings[:coverage_format])
87
+ rescue ArgumentError, SystemCallError => error
88
+ raise if status == 0
89
+
90
+ warn "polyrun: #{error.message}"
91
+ status
92
+ end
93
+
94
+ def build_paths(argv, config)
95
+ output = config.partition["paths_file"] || "spec/spec_paths.txt"
96
+ globs = []
97
+ parser = OptionParser.new do |flags|
98
+ flags.banner = "Usage: polyrun build-paths [--paths-file FILE] [--glob PATTERN] [PATTERN ...]"
99
+ flags.on("--paths-file FILE", "--output FILE", "Destination path list") { |value| output = value }
100
+ flags.on("--glob PATTERN", "Test file glob (repeatable)") { |value| globs << value }
101
+ end
102
+ return 0 unless Options.parse(parser, argv)
103
+
104
+ globs.concat(argv)
105
+ globs = config.paths_globs if globs.empty?
106
+ globs << Paths::SUITE_GLOBS["rspec"] if globs.empty?
107
+ paths = Paths.glob(globs)
108
+ raise ArgumentError, "no test paths found" if paths.empty?
109
+
110
+ Compat.write_report(output, paths.join("\n") + "\n")
111
+ puts File.expand_path(output)
112
+ 0
113
+ end
114
+
115
+ def partition_flags(flags, settings)
116
+ flags.on("--paths-file FILE", "Read paths from a file") do |value|
117
+ settings[:paths_file] = value
118
+ settings[:cli_path_source] = true
119
+ end
120
+ flags.on("--paths-glob PATTERN", "Find paths by glob (repeatable)") do |value|
121
+ settings[:globs] = [] unless settings[:cli_path_source] && !settings[:paths_file]
122
+ settings[:paths_file] = nil
123
+ settings[:globs] << value
124
+ settings[:cli_path_source] = true
125
+ end
126
+ flags.on("--strategy NAME", "Partition strategy") { |value| settings[:strategy] = value }
127
+ flags.on("--timing FILE", "Use a timing report for partition weights") { |value| settings[:timing] = value }
128
+ flags.on("--seed VALUE", "Partition seed") { |value| settings[:seed] = value }
129
+ end
130
+ end
131
+ end
132
+ end
@@ -0,0 +1,34 @@
1
+ module Polyrun
2
+ module Legacy
3
+ module ShardEnv
4
+ CI_KEYS = [
5
+ %w[CI_NODE_INDEX CI_NODE_TOTAL],
6
+ %w[BUILDKITE_PARALLEL_JOB BUILDKITE_PARALLEL_JOB_COUNT],
7
+ %w[CIRCLE_NODE_INDEX CIRCLE_NODE_TOTAL]
8
+ ].freeze
9
+
10
+ module_function
11
+
12
+ def defaults(partition = {})
13
+ index = partition["shard_index"] || partition["shard"] || "0"
14
+ total = partition["shard_total"] || partition["total"] || "1"
15
+ if %w[1 true yes].include?(ENV["CI"].to_s.downcase)
16
+ keys = CI_KEYS.find { |pair| pair.any? { |key| !ENV[key].to_s.empty? } }
17
+ index, total = Options.env_value(keys.first, index), Options.env_value(keys.last, total) if keys
18
+ end
19
+ [Options.env_value("POLYRUN_SHARD_INDEX", index), Options.env_value("POLYRUN_SHARD_TOTAL", total)]
20
+ end
21
+
22
+ def for_shard(index, total, database = nil)
23
+ raise ArgumentError, "shard_index out of range" if index < 0 || index >= total
24
+
25
+ settings = {"POLYRUN_SHARD_INDEX" => index.to_s, "POLYRUN_SHARD_TOTAL" => total.to_s}
26
+ settings["TEST_ENV_NUMBER"] = (index + 1).to_s if total > 1
27
+ if database
28
+ settings["POLYRUN_TEST_DATABASE"] = database.gsub(/%\{shard\}|%<shard>d/, index.to_s)
29
+ end
30
+ settings
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,35 @@
1
+ module Polyrun
2
+ module Legacy
3
+ module Partition
4
+ class ShardHeap
5
+ def initialize(count)
6
+ @loads = Array.new(count) { |index| [0.0, index] }
7
+ end
8
+
9
+ def assign(weight)
10
+ lightest = @loads.first
11
+ lightest[0] += weight
12
+ sift_down
13
+ lightest[1]
14
+ end
15
+
16
+ private
17
+
18
+ def sift_down
19
+ index = 0
20
+ loop do
21
+ left = 2 * index + 1
22
+ break if left >= @loads.length
23
+
24
+ right = left + 1
25
+ child = (right < @loads.length && (@loads[right] <=> @loads[left]) < 0) ? right : left
26
+ break if (@loads[index] <=> @loads[child]) <= 0
27
+
28
+ @loads[index], @loads[child] = @loads[child], @loads[index]
29
+ index = child
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end