lowrail-profile 0.1.2

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.
@@ -0,0 +1,335 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Objects allocated per request, job, mail and Action Cable action, by source
5
+ # line in your app, Rails, Ruby and gems (README-profile.md). Runs a command
6
+ # that serves requests (your test suite, a workloads file) twice with
7
+ # allocation counting on. It counts objects, not time, and never changes or
8
+ # lowers your app.
9
+ USAGE = <<~TEXT
10
+ usage: lowrail-profile [options] -- COMMAND... profile a command, such as bin/rails test
11
+ lowrail-profile [options] --workloads [FILE] replay lowrail/workloads.rb (experimental)
12
+ lowrail-profile report [DIR] report again from runs kept with --keep-runs
13
+ lowrail-profile compare BASE.json HEAD.json [--aa BASE2.json] [--min N] [--json]
14
+ list changes beyond the noise floor (a report: exit 0),
15
+ exit 2 without valid evidence
16
+
17
+ Options, all before "--" (everything after it is the command's, unchanged):
18
+ --out DIR where runs and reports go (default tmp/lowrail-profile): a new or empty
19
+ directory, or one lowrail-profile created
20
+ --runs N runs of the command (default 2; their spread is in compare's noise floor)
21
+ --top N rows per table (default 30)
22
+ --seed N SEED and --seed for every run (default 1234)
23
+ --ledger FILE a newer ledger index (contributions-index.json) than the bundled one
24
+ --no-ledger no ledger column
25
+ --timeout SECONDS stop a run and what it started that takes longer (TERM, KILL 10 s later) and exit 124
26
+ --keep-runs keep each run's raw counts (run1/, run2/) for lowrail-profile report
27
+ --record [FILE] also write the suite's requests as lowrail/workloads.rb (experimental)
28
+ --workloads [FILE] send the file's requests through the app (experimental); they are real
29
+ --allow-writes let --workloads send writes, sign-ins and setup code, and run against a
30
+ production environment whose database is not on this machine
31
+ --help, --version
32
+ TEXT
33
+ require "rbconfig"
34
+ require "fileutils"
35
+ require "digest"
36
+ require_relative "../lib/lowrail/profile_report"
37
+ require_relative "../lib/lowrail/workloads"
38
+
39
+ lib = File.expand_path("../lib", __dir__)
40
+ args = ARGV.dup
41
+ split = args.index("--")
42
+ command = split ? args[(split + 1)..] : nil
43
+ args = args[0...split] if split
44
+ if args.include?("--help") || args.include?("-h")
45
+ puts USAGE
46
+ exit
47
+ end
48
+ if args.include?("--version")
49
+ require_relative "../lib/lowrail/profile_version"
50
+ puts "lowrail-profile #{Lowrail::Profile::VERSION}"
51
+ exit
52
+ end
53
+ opt = lambda do |name, default|
54
+ i = args.index(name) or next default
55
+ value = args[i + 1] or abort "lowrail-profile: #{name} needs a value"
56
+ args.slice!(i, 2)
57
+ value
58
+ end
59
+ out = File.expand_path(opt.("--out", "tmp/lowrail-profile"))
60
+ runs = Integer(opt.("--runs", "2"))
61
+ top = Integer(opt.("--top", "30"))
62
+ seed = opt.("--seed", "1234")
63
+ ledger = opt.("--ledger", File.expand_path("../data/contributions-index.json", __dir__))
64
+ ledger = nil if args.delete("--no-ledger")
65
+ abort "lowrail-profile: no ledger index #{ledger}" if ledger && !File.file?(ledger)
66
+ allow_writes = args.delete("--allow-writes")
67
+ keep_runs = args.delete("--keep-runs")
68
+ timeout = opt.("--timeout", nil)&.then { Float(_1) }
69
+ abort "lowrail-profile: --timeout must be a positive number of seconds" if timeout && timeout <= 0
70
+ # --workloads and --record take an optional FILE.
71
+ flag = lambda do |name|
72
+ next unless (i = args.index(name))
73
+ value = args[i + 1] if args[i + 1] && !args[i + 1].start_with?("-")
74
+ args.slice!(i, value ? 2 : 1)
75
+ value || :default
76
+ end
77
+ workloads = flag.("--workloads")
78
+ record = flag.("--record")
79
+ abort "lowrail-profile: --paths was replaced by --workloads FILE (lowrail/workloads.rb, README-profile.md)" if args.include?("--paths")
80
+
81
+ if args.first == "report"
82
+ dir = File.expand_path(args[1] || out)
83
+ unless File.directory?(dir) && Lowrail::ProfileReport.run_dirs(dir).any?
84
+ abort "lowrail-profile: no runs in #{dir}: they are deleted after the report unless you profile with --keep-runs"
85
+ end
86
+ report = Lowrail::ProfileReport.new(dir, ledger: ledger, top: top)
87
+ report.write
88
+ puts report.markdown
89
+ $stderr.puts "lowrail-profile: #{report.parallel_warning}" if report.parallel_warning
90
+ exit
91
+ end
92
+
93
+ # compare BASE.json HEAD.json --aa BASE2.json [--min N] [--json]: lists changes
94
+ # beyond the noise floor of the A/A pair BASE and BASE2 and exits 0, or 2 when
95
+ # the reports are not valid evidence for a comparison.
96
+ if args.first == "compare"
97
+ require_relative "../lib/lowrail/profile_compare"
98
+ min = Float(opt.("--min", "1"))
99
+ aa = opt.("--aa", nil)
100
+ json = args.delete("--json")
101
+ abort "usage: lowrail-profile compare BASE.json HEAD.json [--aa BASE2.json] [--min N] [--json]" unless args.size == 3
102
+ compare = Lowrail::ProfileCompare.new(args[1], args[2], aa: aa, min: min, top: top)
103
+ puts json ? JSON.pretty_generate(compare.to_h) : compare.markdown
104
+ exit compare.status
105
+ end
106
+
107
+ usage = "#{USAGE.lines.first(5).join}(lowrail-profile --help for options)"
108
+ abort "lowrail-profile: Windows is not supported (Linux and macOS are)" if Gem.win_platform?
109
+ if workloads
110
+ abort "lowrail-profile: --workloads runs its own command; drop the one after --" if command
111
+ abort usage unless args.empty?
112
+ file = File.expand_path(workloads == :default ? Lowrail::Workloads::PATH : workloads)
113
+ abort "lowrail-profile: no #{file}; write one (README-profile.md) or record one: lowrail-profile --record -- bin/rails test" unless File.exist?(file)
114
+ command = ["bin/rails", "runner", File.join(lib, "lowrail/profile_workloads.rb"), file, File.join(out, "workloads.json")]
115
+ elsif command
116
+ abort usage unless args.empty?
117
+ else
118
+ command = args
119
+ end
120
+ abort usage if command.empty?
121
+ abort "lowrail-profile: --record records a command's requests; drop --workloads" if record && workloads
122
+ abort "lowrail-profile: --allow-writes is for --workloads" if allow_writes && !workloads
123
+ abort "lowrail-profile: --runs must be at least 1" if runs < 1
124
+
125
+ # Built once per Ruby build and per version of the counter's sources, outside
126
+ # the app and never during its boot. Another checkout's counter has another
127
+ # digest, so it is never picked up; lowrail/profile also refuses one whose API
128
+ # differs.
129
+ source = File.expand_path("../ext/lowrail_profile", __dir__)
130
+ # Listed, not globbed: a gem home may have [, { or * in its path.
131
+ sources = Dir.children(source).sort.map { File.join(source, _1) }
132
+ inputs = sources.map { "#{File.basename(_1)}\0#{File.binread(_1)}" }
133
+ inputs << RbConfig::CONFIG.values_at("CC", "CFLAGS", "LDFLAGS", "DLEXT", "rubyhdrdir", "rubyarchhdrdir").join("\0")
134
+ variant = [RUBY_ENGINE, RUBY_VERSION, RUBY_REVISION, RUBY_PLATFORM].join("-")
135
+ cache = File.join(ENV.fetch("XDG_CACHE_HOME", File.expand_path("~/.cache")), "lowrail", "profile", variant,
136
+ Digest::SHA256.hexdigest(inputs.join("\0"))[0, 16])
137
+ name = "lowrail_profile.#{RbConfig::CONFIG.fetch("DLEXT")}"
138
+ ext = File.join(cache, name)
139
+ unless File.exist?(ext)
140
+ # Built aside and moved in whole, so a failed or concurrent build never leaves half an extension.
141
+ tmp = "#{cache}.tmp-#{Process.pid}"
142
+ FileUtils.rm_rf(tmp)
143
+ FileUtils.mkdir_p(tmp)
144
+ log = File.join(tmp, "build.log")
145
+ # Built from a copy: mkmf escapes a srcdir with spaces in a way make's VPATH cannot follow.
146
+ FileUtils.cp(sources, tmp)
147
+ build = lambda do
148
+ system(RbConfig.ruby, "extconf.rb", chdir: tmp, out: log, err: log) &&
149
+ system(RbConfig::CONFIG.fetch("MAKE", "make"), chdir: tmp, out: [log, "a"], err: [log, "a"])
150
+ end
151
+ # Outside the app's bundle: under bundle exec its Gemfile would be evaluated in tmp, where a
152
+ # relative File.read(".ruby-version") fails (Dawarich), and the build needs nothing from it.
153
+ ok = defined?(Bundler) && Bundler.respond_to?(:with_unbundled_env) ? Bundler.with_unbundled_env(&build) : build.()
154
+ unless ok && File.exist?(File.join(tmp, name))
155
+ kept = "#{cache}.build.log"
156
+ FileUtils.cp(log, kept) if File.exist?(log)
157
+ FileUtils.rm_rf(tmp)
158
+ abort "lowrail-profile: building the counter failed, see #{kept}"
159
+ end
160
+ begin
161
+ File.rename(tmp, cache)
162
+ rescue SystemCallError
163
+ FileUtils.rm_rf(tmp)
164
+ abort "lowrail-profile: could not install the counter in #{cache}" unless File.exist?(ext)
165
+ end
166
+ end
167
+
168
+ # Clears only what it wrote before, in a directory it marked; refuses any
169
+ # other existing directory.
170
+ mark = File.join(out, ".lowrail-profile")
171
+ if File.exist?(out)
172
+ unless File.directory?(out) && (File.file?(mark) || Dir.empty?(out))
173
+ abort "lowrail-profile: #{out} exists and was not created by lowrail-profile; pick another --out or remove it yourself"
174
+ end
175
+ Dir.children(out).each do |entry|
176
+ FileUtils.rm_rf(File.join(out, entry)) if entry.match?(/\Arun\d+\z/) || %w[command.txt capture.json report.md report.json workloads.json].include?(entry)
177
+ end
178
+ end
179
+ FileUtils.mkdir_p(out)
180
+ File.write(mark, "Created by lowrail-profile, which clears its runs and reports here on each run.\n")
181
+ timed_out = []
182
+ statuses = []
183
+ (1..runs).each do |n|
184
+ dir = File.join(out, "run#{n}")
185
+ FileUtils.mkdir_p(dir)
186
+ # The repeat run also records the nearest app line of every allocation
187
+ # (without allocating, so its counts stay comparable). Every internal flag
188
+ # is set or cleared here, so none leaks in from the caller's environment;
189
+ # lib goes through RUBYLIB, which, unlike RUBYOPT, takes paths with spaces,
190
+ # and through RUBYOPT when it can, for a child that sets its own RUBYLIB.
191
+ env = { "LOWRAIL_PROFILE" => dir, "LOWRAIL_PROFILE_EXT" => ext, "SEED" => seed, "LOWRAIL_PROFILE_ROOT" => Dir.pwd,
192
+ "LOWRAIL_PROFILE_ATTRIBUTE" => ("1" if n == [runs, 2].min),
193
+ "LOWRAIL_PROFILE_RECORD" => ("1" if record && n == 1),
194
+ "LOWRAIL_PROFILE_ALLOW_WRITES" => ("1" if allow_writes),
195
+ "SPEC_OPTS" => [ENV["SPEC_OPTS"], "--seed #{seed}"].compact.join(" "),
196
+ # What the suite gives the processes it starts (Lowrail::Profile.leave_env).
197
+ "LOWRAIL_PROFILE_LIB" => lib, "LOWRAIL_PROFILE_CALLER_SEED" => ENV["SEED"], "LOWRAIL_PROFILE_CALLER_SPEC_OPTS" => ENV["SPEC_OPTS"],
198
+ "RUBYLIB" => [lib, ENV["RUBYLIB"]].reject { _1.nil? || _1.empty? }.join(File::PATH_SEPARATOR),
199
+ "RUBYOPT" => [ENV["RUBYOPT"], ("-I#{lib}" unless lib.match?(/\s/)), "-rlowrail/profile"].compact.join(" ") }
200
+ # leave_env removes exactly these.
201
+ env["LOWRAIL_PROFILE_KEYS"] = env.keys.grep(/\ALOWRAIL_PROFILE/).join(",")
202
+ $stderr.puts "lowrail-profile: run #{n} of #{runs}: #{command.join(" ")}"
203
+ if timeout
204
+ # Its own process group, so the deadline stops every process it started;
205
+ # the terminal's INT and a TERM reach the group through this process.
206
+ # The traps go in before the spawn, so a signal in between is not lost.
207
+ pid = nil
208
+ pending = []
209
+ stop = ->(signal) { pid ? (Process.kill(signal, -pid) rescue Errno::ESRCH) : pending << signal }
210
+ interrupted = false
211
+ traps = %w[INT TERM HUP QUIT].to_h { |signal| [signal, trap(signal) { interrupted = true; stop.(signal) }] }
212
+ pid = Process.spawn(env, *command, pgroup: true)
213
+ waiter = Process.detach(pid)
214
+ pending.each { stop.(_1) }
215
+ unless waiter.join(timeout)
216
+ timed_out << n
217
+ $stderr.puts "lowrail-profile: run #{n} took longer than --timeout #{timeout}s; stopping it"
218
+ # Processes it started in a group of their own (selenium-webdriver's driver and browser) are not in the
219
+ # group: they are found by parent now, before an exiting parent leaves them orphans.
220
+ table = lambda do
221
+ list = IO.popen(%w[ps -A -o pid= -o ppid= -o pgid= -o stat=], err: File::NULL, &:read)
222
+ $?.success? ? list.each_line.map { |l| p, pp, g, s = l.split; [p.to_i, pp.to_i, g.to_i, s.to_s] } : nil
223
+ rescue SystemCallError
224
+ nil
225
+ end
226
+ # A descendant that leads a group of its own: the group is followed, so what joins it later (a driver's
227
+ # child started during cleanup, orphaned when the driver exits) is stopped too. A descendant in another
228
+ # group it does not lead is followed alone, so an unrelated group is never signalled.
229
+ groups, others = [], []
230
+ track = lambda do
231
+ rows = table.() or next nil
232
+ children = rows.group_by { _2 }
233
+ seen = {}
234
+ # Members of a followed group are walked too: one orphaned when its group's leader exits is still there.
235
+ queue = [pid, *others, *groups, *rows.filter_map { |p, _, g, _| p if g == pid || groups.include?(g) }]
236
+ while (parent = queue.shift)
237
+ Array(children[parent]).each do |p, _, g, _|
238
+ next if seen[p]
239
+ seen[p] = true
240
+ queue << p
241
+ next if g == pid || groups.include?(g)
242
+ g == p ? groups << g : (others << p unless others.include?(p))
243
+ end
244
+ end
245
+ rows
246
+ end
247
+ track.()
248
+ stop_all = lambda do |signal|
249
+ stop.(signal)
250
+ groups.each { |g| Process.kill(signal, -g) rescue nil }
251
+ others.each { |p| Process.kill(signal, p) rescue nil }
252
+ end
253
+ stop_all.("TERM")
254
+ # The whole group gets 10 s, then KILL, also when the leader exited on TERM at once:
255
+ # a worker that ignores TERM outlives it.
256
+ grace = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10
257
+ # A zombie is not waited for: an orphan whose new parent never reaps it (a container's PID 1 without init).
258
+ running = lambda do
259
+ # A ps that fails lists no one; the group may still be cleaning up.
260
+ next (Process.kill(0, -pid) rescue false) unless (rows = track.())
261
+ rows.any? { |p, _, g, s| (g == pid || groups.include?(g) || others.include?(p)) && !s.start_with?("Z") }
262
+ end
263
+ # ps reads /proc one process at a time: a child forked while its parent exits can be missing from one listing.
264
+ sleep 0.1 while (running.() || running.()) && Process.clock_gettime(Process::CLOCK_MONOTONIC) < grace
265
+ stop_all.("KILL")
266
+ waiter.join
267
+ end
268
+ traps.each { |signal, handler| trap(signal, handler) }
269
+ result = waiter.value
270
+ else
271
+ system(env, *command)
272
+ result = $?
273
+ end
274
+ # A shell's convention: the exit status, or 128 + the signal that ended it; 124 for --timeout, as timeout(1).
275
+ status = timed_out.include?(n) ? 124 : result.exitstatus || 128 + result.termsig.to_i
276
+ # A workloads run that stops (a refused write, a response outside expect:) measured nothing to repeat.
277
+ if workloads && status != 0
278
+ $stderr.puts "lowrail-profile: the workloads run exited #{status}; nothing measured"
279
+ exit status
280
+ end
281
+ statuses << status
282
+ break if timed_out.any? || interrupted
283
+ end
284
+ # The first failed run's status is the command's; profiling never hides a failure.
285
+ failed = timed_out.any? ? 124 : statuses.find { _1 != 0 }
286
+ File.write(File.join(out, "command.txt"), "#{command.join(" ")}\nseed #{seed}\nexit #{statuses.join(" ")}\n")
287
+ # What compare checks two captures against: the workloads (their manifest and
288
+ # what was measured, from the receipt) or the command's arguments, never the
289
+ # output directory; argv stays apart for diagnostics.
290
+ identity = workloads ? { "mode" => "workloads", "host" => ENV.fetch("LOWRAIL_PROFILE_HOST", "localhost") } : { "mode" => "command", "argv" => command }
291
+ File.write(File.join(out, "capture.json"), JSON.generate("format" => 1, "identity" => identity, "argv" => command, "seed" => seed,
292
+ "runs" => runs, "exit" => statuses, "timed_out" => timed_out, "timeout" => timeout) + "\n")
293
+
294
+ begin
295
+ report = Lowrail::ProfileReport.new(out, ledger: ledger, top: top)
296
+ report.write
297
+ puts report.markdown
298
+ $stderr.puts "lowrail-profile: #{report.parallel_warning}" if report.parallel_warning
299
+ rescue StandardError => error
300
+ $stderr.puts "lowrail-profile: no report: #{error.message}; the command exited #{statuses.join(", ")}"
301
+ exit(failed || 1)
302
+ end
303
+ begin
304
+ if record
305
+ target = File.expand_path(record == :default ? Lowrail::Workloads::PATH : record)
306
+ target = File.join(out, "workloads.rb") if record == :default && File.exist?(target)
307
+ run1 = File.join(out, "run1")
308
+ shapes = Dir.children(run1).grep(/\.shapes\.json\z/).sort.flat_map { JSON.parse(File.read(File.join(run1, _1))) }
309
+ merged = shapes.group_by { _1.values_at("verb", "template", "json", "xhr", "format", "accept", "unfiltered") }
310
+ .map { |_, list| list.first.merge("count" => list.sum { _1["count"] }) }
311
+ if merged.empty?
312
+ $stderr.puts "lowrail-profile: --record saw no routed requests; nothing written"
313
+ else
314
+ FileUtils.mkdir_p(File.dirname(target))
315
+ File.write(target, Lowrail::Workloads.render(Lowrail::Workloads.recorded(merged, 20), <<~TEXT))
316
+ Workloads for lowrail-profile --workloads (README-profile.md).
317
+ Recorded by `lowrail-profile --record -- #{command.join(" ")}`: the #{[merged.size, 20].min} most frequent
318
+ request shapes of #{merged.sum { _1["count"] }} requests, most frequent first. Records are each model's first row.
319
+ Only GETs that replay as recorded are enabled. Writes keep the params one test sent and are commented out until
320
+ you make them repeatable (setup, alternate:); so is any request whose params were filtered or shortened.
321
+ Recorded from real requests: values the app's filter_parameters hides are #{Lowrail::Workloads::FILTERED},
322
+ but check the file for other secrets before you commit it.
323
+ TEXT
324
+ $stderr.puts "lowrail-profile: wrote #{target} from real requests (filter_parameters applied); check it for secrets before committing it"
325
+ end
326
+ end
327
+ rescue StandardError => error
328
+ $stderr.puts "lowrail-profile: --record: #{error.message}"
329
+ exit(failed || 1)
330
+ end
331
+ # compare reads only report.json; the raw counts are as large as the suite is.
332
+ Lowrail::ProfileReport.run_dirs(out).each { FileUtils.rm_rf(_1) } unless keep_runs
333
+ $stderr.puts "lowrail-profile: report in #{File.join(out, "report.md")}"
334
+ $stderr.puts "lowrail-profile: the command exited #{statuses.join(", ")}" unless statuses.all?(0)
335
+ exit(failed || 0)
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "mkmf"
4
+ create_makefile("lowrail_profile")