Repository navigation
Expand file tree
/
Copy pathRakefile
More file actions
580 lines (518 loc) · 20.3 KB
/
Copy pathRakefile
File metadata and controls
580 lines (518 loc) · 20.3 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# frozen_string_literal: true
require "bundler"
require "rubygems/package_task"
require "fileutils"
require "yaml"
VERSION_MANAGERS = {
:chruby => {
:env => "#!/bin/bash\nsource /usr/local/opt/chruby/share/chruby/chruby.sh",
:switch_command => lambda { |version| "chruby #{version}" }
},
:rbenv => {
:env => "#!/bin/bash",
:switch_command => lambda { |version| "rbenv local #{version}" }
},
:rvm => {
:env => "#!/bin/bash --login",
:switch_command => lambda { |version| "rvm use --default #{version}" }
}
}.freeze
SPEC_COVERAGE_AUDIT_JOB_NAME = "Spec coverage audit"
def build_job(ruby_version, ruby_gem: nil, runs_on: DEFAULT_RUNS_ON)
name = "Ruby #{ruby_version}"
name = "#{name} - #{ruby_gem}" if ruby_gem
name = "#{name} (#{runs_on})" if runs_on != DEFAULT_RUNS_ON
{
"name" => name,
"needs" => "validation",
"runs-on" => runs_on,
"steps" => [
{
"name" => "Check out repository",
"uses" => "actions/checkout@v4"
},
{
"name" => "Install Ruby",
"uses" => "ruby/setup-ruby@v1",
"with" => {
"ruby-version" => ruby_version,
"bundler-cache" => true
}
},
{
"name" => "Install gem extension",
"run" => "./script/bundler_wrapper exec rake extension:install"
},
{
"name" => "Print extension install report",
"run" => "[ -e ext/install.report ] && cat ext/install.report || echo 'No ext/install.report file found'" # rubocop:disable Layout/LineLength
},
{
"name" => "Print Makefile log file",
"run" => "[ -f ext/mkmf.log ] && cat ext/mkmf.log || echo 'No ext/mkmf.log file found'"
}
]
}
end
# Every test job uploads the example list its run wrote, named after the job so
# the audit can say which combination is missing one. Uploaded even when the run
# fails, because the list is written either way and the audit needs to tell a
# crashed job apart from a combination that legitimately runs nothing.
def example_list_upload_step(key)
{
"name" => "Upload example list",
"if" => "always()",
"uses" => "actions/upload-artifact@v4",
"with" => {
"name" => key,
"path" => "tmp/examples-*.json",
"if-no-files-found" => "error",
"retention-days" => 1
}
}
end
# Compares the examples defined in the source against the union of every job's
# example list.
#
# It cannot wait for the test jobs through `needs`. Naming all 426 of them puts
# the workflow over a limit on how many dependency edges GitHub accepts, and
# GitHub then refuses to create the run without reporting anything: no run
# appears, the pull request shows no checks, and the runs API stays empty.
# Grouping the dependencies behind intermediate jobs does not help, because the
# same number of edges still has to exist. So this job starts with the others
# and waits by polling the run it belongs to.
def spec_coverage_audit_job
{
"name" => SPEC_COVERAGE_AUDIT_JOB_NAME,
"needs" => "validation",
"runs-on" => DEFAULT_RUNS_ON,
# Reports without failing the build. The examples it currently finds are
# covered by separate work; removing this line is what makes it enforcing.
"continue-on-error" => true,
# Long enough for the whole matrix, and short enough that a stuck job does
# not hold a runner for the six hours GitHub would otherwise allow.
"timeout-minutes" => 180,
"permissions" => {
"actions" => "read",
"contents" => "read"
},
"steps" => [
{
"name" => "Check out repository",
"uses" => "actions/checkout@v4"
},
{
"name" => "Install Ruby",
"uses" => "ruby/setup-ruby@v1",
"with" => { "ruby-version" => "3.4" }
},
{
"name" => "Wait for the test jobs to upload their example lists",
"env" => { "GH_TOKEN" => "${{ secrets.GITHUB_TOKEN }}" },
"run" => <<~SHELL
jobs="repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/jobs"
filter='.jobs[]
| select(.name != "#{SPEC_COVERAGE_AUDIT_JOB_NAME}")
| select(.status != "completed")
| .name'
while :; do
pending=$(gh api --paginate "$jobs?per_page=100" --jq "$filter" | wc -l)
if [ "$pending" -eq 0 ]; then break; fi
echo "Waiting for $pending jobs."
sleep 60
done
SHELL
},
{
"name" => "Download example lists",
"uses" => "actions/download-artifact@v4",
"with" => { "path" => "artifacts" }
},
{
"name" => "Audit spec coverage",
"run" => "ruby script/audit_spec_coverage.rb artifacts"
}
]
}
end
def build_matrix_key(ruby_version, ruby_gem: nil, runs_on: DEFAULT_RUNS_ON)
base = "ruby_#{ruby_version}"
base = "#{base}__#{ruby_gem}" if ruby_gem
base = "#{base}_#{runs_on}"
base.downcase.gsub(/\W/, "-")
end
def gems_with_gemfiles
YAML.load_file("build_matrix.yml")["matrix"]["gems"].map { |g| g["gem"] }.freeze
end
GITHUB_ACTION_WORKFLOW_FILE = ".github/workflows/ci.yml"
PRIMARY_JOB_GEMSET = "no_dependencies"
DEFAULT_RUNS_ON = "ubuntu-latest"
COLLECTOR_GEMFILE_PARTIAL = "collector.rb"
namespace :build_matrix do
namespace :gemfiles do
# Generates a `<base>-collector.gemfile` next to each base gemfile. The
# variant layers the optional OpenTelemetry gems (`gemfiles/collector.rb`)
# on top of the base, so collector-mode test runs resolve them while the
# base gemfiles (and the gemspec) stay OpenTelemetry-free. Regenerate
# whenever a base gemfile is added or removed.
task :generate do
base_gemfiles =
Dir["gemfiles/*.gemfile"]
.map { |path| File.basename(path) }
.reject { |name| name.end_with?("-collector.gemfile") }
.sort
base_gemfiles.each do |base|
name = base.sub(/\.gemfile\z/, "")
contents =
"# DO NOT EDIT\n" \
"# This is a generated file by the " \
"`rake build_matrix:gemfiles:generate` task.\n" \
"# It layers the optional OpenTelemetry gems (gemfiles/" \
"#{COLLECTOR_GEMFILE_PARTIAL}) on top of #{base}.\n" \
"\n" \
"eval_gemfile File.expand_path(#{base.inspect}, __dir__)\n" \
"eval_gemfile File.expand_path(" \
"#{COLLECTOR_GEMFILE_PARTIAL.inspect}, __dir__)\n"
File.write("gemfiles/#{name}-collector.gemfile", contents)
end
puts "Generated #{base_gemfiles.count} `-collector` gemfiles."
end
task :validate => :generate do
output = `git status --porcelain gemfiles`
if output.include?("-collector.gemfile")
puts "The `-collector` gemfiles are out of date. The changes were not committed."
puts "Please run `rake build_matrix:gemfiles:generate` and commit the changes."
exit 1
end
end
end
namespace :github do
task :generate do
yaml = YAML.load_file("build_matrix.yml")
matrix = yaml["matrix"]
github = yaml["github"]
builds = {}
matrix["ruby"].each do |ruby|
ruby_version = ruby["ruby"]
gemset_for_ruby(ruby, matrix).each do |ruby_gem|
next unless included_for_ruby?(matrix, ruby_gem, ruby)
is_primary_job = ruby_gem["gem"] == PRIMARY_JOB_GEMSET
job =
if is_primary_job
build_job(ruby_version)
else
build_job(ruby_version, :ruby_gem => ruby_gem["gem"])
end
job["env"] = matrix["env"]
.merge("BUNDLE_GEMFILE" => "gemfiles/#{ruby_gem["gem"]}.gemfile")
test_step = {
"name" => "Run tests",
"run" => "./script/bundler_wrapper exec rake test"
}
if is_primary_job
job["steps"] << test_step
# Only test the failure scenarios once per Ruby version
job["steps"] << {
"name" => "Run tests without extension",
"run" => "./script/bundler_wrapper exec rake test:failure"
}
job["steps"] << example_list_upload_step(build_matrix_key(ruby["ruby"]))
builds[build_matrix_key(ruby["ruby"])] = job
else
job["needs"] = build_matrix_key(ruby["ruby"])
job["steps"] << test_step
gem_key = build_matrix_key(ruby["ruby"], :ruby_gem => ruby_gem["gem"])
job["steps"] << example_list_upload_step(gem_key)
builds[gem_key] = job
end
# On collector-capable Rubies, additionally run the gem's
# `-collector` gemfile (base gems + optional OpenTelemetry gems) so
# collector-mode specs are exercised. These always depend on the
# primary job for the Ruby version and run on Ubuntu only.
next unless collector_ruby?(matrix, ruby_version)
collector_gem = "#{ruby_gem["gem"]}-collector"
collector_job = build_job(ruby_version, :ruby_gem => collector_gem)
collector_job["env"] = matrix["env"]
.merge("BUNDLE_GEMFILE" => "gemfiles/#{collector_gem}.gemfile")
collector_job["needs"] = build_matrix_key(ruby["ruby"])
collector_job["steps"] << test_step
collector_key = build_matrix_key(ruby["ruby"], :ruby_gem => collector_gem)
collector_job["steps"] << example_list_upload_step(collector_key)
builds[collector_key] = collector_job
end
# Add build for macOS
ruby_gem = PRIMARY_JOB_GEMSET
runs_on = "macos-15"
job = build_job(ruby_version, :runs_on => runs_on)
job["env"] = matrix["env"]
.merge("BUNDLE_GEMFILE" => "gemfiles/#{ruby_gem}.gemfile")
job["steps"] << {
"name" => "Run tests",
"run" => "./script/bundler_wrapper exec rake test"
}
job["steps"] << {
"name" => "Run tests without extension",
"run" => "./script/bundler_wrapper exec rake test:failure"
}
macos_key = build_matrix_key(ruby["ruby"], :runs_on => runs_on)
job["steps"] << example_list_upload_step(macos_key)
builds[macos_key] = job
end
builds["spec_coverage_audit"] = spec_coverage_audit_job
github["jobs"] = github["jobs"].merge(builds)
job_count = github["jobs"].count
header = "# DO NOT EDIT\n" \
"# This is a generated file by the `rake build_matrix:github:generate` task.\n" \
"# See `build_matrix.yml` for the build matrix.\n" \
"# Generate this file with `rake build_matrix:github:generate`.\n" \
"# Generated job count: #{job_count}\n"
generated_yaml = header + YAML.dump(github)
File.write(GITHUB_ACTION_WORKFLOW_FILE, generated_yaml)
puts "Generated `#{GITHUB_ACTION_WORKFLOW_FILE}`"
puts "Job count: #{job_count}"
end
task :validate => :generate do
output = `git status`
if output.include? GITHUB_ACTION_WORKFLOW_FILE
puts "The `#{GITHUB_ACTION_WORKFLOW_FILE}` is modified. The changes were not committed."
puts "Please run `rake build_matrix:github:generate` and commit the changes."
exit 1
end
end
end
namespace :local do
task :generate do
yaml = YAML.load_file("build_matrix.yml")
matrix = yaml["matrix"]
defaults = matrix["defaults"]
VERSION_MANAGERS.each do |version_manager, config|
out = []
out << config[:env]
out << "rm -f .ruby-version"
out << "echo 'Using #{version_manager}'"
matrix["ruby"].each do |ruby|
ruby_version = ruby["ruby"]
out << "echo 'Switching to #{ruby_version}'"
# rubocop:disable Layout/LineLength
out << "#{config[:switch_command].call(ruby_version)} || { echo 'Switching Ruby failed'; exit 1; }"
out << "ruby -v"
out << "echo 'Compiling extension'"
out << "./script/bundler_wrapper exec rake extension:install"
out << "rm -f gemfiles/*.gemfile.lock"
gemset_for_ruby(ruby, matrix).each do |gem|
next unless included_for_ruby?(matrix, gem, ruby)
gemfile = gem["gem"]
out << "echo 'Bundling #{gemfile} in #{ruby_version}'"
rubygems = gem["rubygems"] || ruby["rubygems"] || defaults["rubygems"]
rubygems_version = "env _RUBYGEMS_VERSION=#{rubygems_version}" if rubygems
bundler = gem["bundler"] || ruby["bundler"] || defaults["bundler"]
bundler_version = "env _BUNDLER_VERSION=#{bundler}" if bundler
gemfile_env = "env BUNDLE_GEMFILE=gemfiles/#{gemfile}.gemfile"
out << "#{bundler_version} #{rubygems_version} ./script/install_deps"
out << "#{bundler_version} #{gemfile_env} ./script/bundler_wrapper install --quiet || { echo 'Bundling failed'; exit 1; }"
out << "echo 'Running #{gemfile} in #{ruby_version}'"
out << "#{bundler_version} #{gemfile_env} ./script/bundler_wrapper exec rspec || { echo 'Running specs failed'; exit 1; }"
next unless collector_ruby?(matrix, ruby_version)
collector_env = "env BUNDLE_GEMFILE=gemfiles/#{gemfile}-collector.gemfile"
out << "echo 'Bundling #{gemfile}-collector in #{ruby_version}'"
out << "#{bundler_version} #{collector_env} ./script/bundler_wrapper install --quiet || { echo 'Bundling failed'; exit 1; }"
out << "echo 'Running #{gemfile}-collector in #{ruby_version}'"
out << "#{bundler_version} #{collector_env} ./script/bundler_wrapper exec rspec || { echo 'Running specs failed'; exit 1; }"
end
# rubocop:enable Layout/LineLength
out << ""
end
out << "rm -f .ruby-version"
out << "echo 'Successfully ran specs for all environments'"
script = "bundle_and_spec_all_#{version_manager}"
FileUtils.rm_f(script)
File.write(script, out.join("\n"))
File.chmod(0o775, script)
puts "Generated #{script}"
end
end
end
def collector_ruby?(matrix, ruby_version)
Array(matrix.dig("collector", "ruby")).include?(ruby_version)
end
def gemset_for_ruby(ruby, matrix)
gems = matrix["gems"]
if ruby["gems"]
# Only a specific gemset for this Ruby
selected_gems = matrix["gemsets"].fetch(ruby["gems"])
gems.select { |g| selected_gems.include?(g["gem"]) }
else
# All gems for this Ruby
gems
end
end
def included_for_ruby?(matrix, gem, ruby)
included_rubies = gem.dig("only", "ruby") || []
excluded_rubies = gem.dig("exclude", "ruby") || []
if included_rubies.any? && excluded_rubies.any?
raise "Both `only` and `exclude` config options for gem `#{gem["gem"]}` are configured. " \
"Only use one of the two config options."
end
if included_rubies.any?
# If this gem only runs on these specific Ruby version
included_rubies.each { |version| check_if_ruby_version_exists!(matrix, version) }
true if included_rubies.include?(ruby["ruby"])
else
# If this gem is excluded from running on this Ruby version
excluded_rubies.each { |version| check_if_ruby_version_exists!(matrix, version) }
true unless excluded_rubies.include?(ruby["ruby"])
end
end
def check_if_ruby_version_exists!(matrix, ruby_version)
return if matrix["ruby"].find { |ruby| ruby["ruby"] == ruby_version }
raise "Ruby version `#{ruby_version}` is not known by the build matrix."
end
end
namespace :build do
def base_gemspec
eval(File.read("appsignal.gemspec")) # rubocop:disable Security/Eval
end
def modify_base_gemspec(&block)
base_gemspec.tap(&block)
end
def define_build_task(task_name, base_gemspec, &block)
Gem::PackageTask.new(base_gemspec, &block)
rescue StandardError => e
puts "Warning: An error occurred defining `build:#{task_name}:gem` Rake task."
puts "This task will not be available."
if ENV["DEBUG"]
puts "#{e}: #{e.message}"
puts e.backtrace
else
puts "For more information, run the same command with `DEBUG=true`."
end
puts
end
namespace :ruby do
# Extension default set in `appsignal.gemspec`
define_build_task(:ruby, base_gemspec) { |_pkg| } # rubocop:disable Lint/EmptyBlock
end
namespace :jruby do
spec = modify_base_gemspec do |s|
s.platform = "java"
# Override extensions config with JRuby extension installer
# Default set in `appsignal.gemspec`
s.extensions = %w[ext/Rakefile]
s.add_dependency "ffi"
end
define_build_task(:jruby, spec) { |_pkg| } # rubocop:disable Lint/EmptyBlock
end
desc "Build all gem versions"
task :all => ["ruby:gem", "jruby:gem"]
desc "Build every package in this repository"
task :packages => :all do
# Build the companion gem by delegating to its own Rakefile rather than
# duplicating its build logic here. mono builds each package directly, so
# this task is only a convenience for developers building from the root.
#
# Clear the Bundler environment first so the sub-build resolves against the
# package's own Gemfile instead of inheriting this repository's
# BUNDLE_GEMFILE. Install its dependencies first, then build it.
Bundler.with_unbundled_env do
Dir.chdir("packages/opentelemetry") do
sh "bundle install"
sh "bundle exec rake build:all"
end
end
end
desc "Clean up all gem build artifacts"
task :clean do
FileUtils.rm_rf File.expand_path("pkg", __dir__)
end
end
desc "Install the AppSignal gem, extension and all possible dependencies."
task :install => "extension:install" do
Bundler.with_clean_env do
gems_with_gemfiles.each do |gemfile|
system "bundle --gemfile gemfiles/#{gemfile}.gemfile"
end
end
end
task :spec_all_gemfiles do
Bundler.with_clean_env do
gems_with_gemfiles.each do |gemfile|
puts "Running tests for #{gemfile}"
unless system("env BUNDLE_GEMFILE=gemfiles/#{gemfile}.gemfile bundle exec rspec")
raise "Not successful"
end
end
end
end
task :console do
require "irb"
require "irb/completion"
require "appsignal"
Appsignal.configure(:console)
ARGV.clear
IRB.start
end
namespace :extension do
desc "Install the AppSignal gem extension"
task :install => :clean do
if RUBY_PLATFORM == "java"
system "cd ext && rake"
else
system "cd ext && ruby extconf.rb && make clean && make"
end
end
desc "Clean the AppSignal gem extension directory of installation artifacts"
task :clean do
system <<-COMMAND
cd ext &&
rm -f appsignal.bundle \
appsignal-agent \
appsignal.h \
appsignal_extension.o \
appsignal_extension.so \
appsignal_extension.bundle \
install.report \
libappsignal.* \
appsignal.version \
Makefile \
mkmf.log
COMMAND
end
end
begin
require "rspec/core/rake_task"
is_jruby = defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
excludes = ["spec/integration/diagnose/**/*_spec.rb"]
excludes << "spec/lib/appsignal/extension/jruby_spec.rb" unless is_jruby
exclude_pattern = "--exclude-pattern=#{excludes.join(",")}" if excludes.any?
# Written alongside the human-readable output so the coverage audit can tell
# which examples this Ruby and gemfile combination actually ran. Every CI job
# uploads its list. Nothing else reveals that a dependency guard is false in
# every combination, because a guarded example is then never defined at all.
def example_list_opts(name)
"--format json --out tmp/examples-#{name}.json"
end
desc "Run the AppSignal gem test suite."
RSpec::Core::RakeTask.new :test do |t|
t.rspec_opts = "#{exclude_pattern} --format documentation " \
"#{example_list_opts("test")}"
end
namespace :test do
RSpec::Core::RakeTask.new :rspec_failure do |t|
t.rspec_opts = "#{exclude_pattern} --format documentation " \
"--tag extension_installation_failure " \
"#{example_list_opts("failure")}"
end
desc "Intentionally fail the extension installation"
task :prepare_failure do
# ENV var to make sure installation fails on purpurse
ENV["_TEST_APPSIGNAL_EXTENSION_FAILURE"] = "true"
# Run extension installation with intentional failure
`rake extension:install`
end
desc "Run the Appsignal gem test in an extension failure scenario"
task :failure => [:prepare_failure, :rspec_failure]
end
rescue LoadError
# When running rake install, there is no RSpec yet.
end
task :default => [:generate_bundle_and_spec_all, :spec_all_gemfiles]