Skip to content

Commit 58180b5

Browse files
committed
tests: add utility to easily profile node performance with perf
Introduces `TestNode.profile_with_perf()` context manager which samples node execution to produce profiling data. Also introduces a test framework flag, `--perf`, which will run perf on all nodes for the duration of a given test.
1 parent df894fa commit 58180b5

File tree

5 files changed

+165
-4
lines changed

5 files changed

+165
-4
lines changed

test/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,26 @@ gdb /home/example/bitcoind <pid>
176176

177177
Note: gdb attach step may require `sudo`
178178

179+
##### Profiling
180+
181+
An easy way to profile node performance during functional tests is provided
182+
for Linux platforms using `perf`.
183+
184+
Perf will sample the running node and will generate profile data in the node's
185+
datadir. The profile data can then be presented using `perf report` or a graphical
186+
tool like [hotspot](https://github.com/KDAB/hotspot).
187+
188+
To generate a profile during test suite runs, use the `--perf` flag.
189+
190+
To see render the output to text, run
191+
192+
```sh
193+
perf report -i /path/to/datadir/send-big-msgs.perf.data.xxxx --stdio | c++filt | less
194+
```
195+
196+
For ways to generate more granular profiles, see the README in
197+
[test/functional](/test/functional).
198+
179199
### Util tests
180200

181201
Util tests can be run locally by running `test/util/bitcoin-util-test.py`.

test/functional/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,36 @@ Helpers for script.py
118118

119119
#### [test_framework/blocktools.py](test_framework/blocktools.py)
120120
Helper functions for creating blocks and transactions.
121+
122+
### Benchmarking with perf
123+
124+
An easy way to profile node performance during functional tests is provided
125+
for Linux platforms using `perf`.
126+
127+
Perf will sample the running node and will generate profile data in the node's
128+
datadir. The profile data can then be presented using `perf report` or a graphical
129+
tool like [hotspot](https://github.com/KDAB/hotspot).
130+
131+
There are two ways of invoking perf: one is to use the `--perf` flag when
132+
running tests, which will profile each node during the entire test run: perf
133+
begins to profile when the node starts and ends when it shuts down. The other
134+
way is the use the `profile_with_perf` context manager, e.g.
135+
136+
```python
137+
with node.profile_with_perf("send-big-msgs"):
138+
# Perform activity on the node you're interested in profiling, e.g.:
139+
for _ in range(10000):
140+
node.p2p.send_message(some_large_message)
141+
```
142+
143+
To see useful textual output, run
144+
145+
```sh
146+
perf report -i /path/to/datadir/send-big-msgs.perf.data.xxxx --stdio | c++filt | less
147+
```
148+
149+
#### See also:
150+
151+
- [Installing perf](https://askubuntu.com/q/50145)
152+
- [Perf examples](http://www.brendangregg.com/perf.html)
153+
- [Hotspot](https://github.com/KDAB/hotspot): a GUI for perf output analysis

test/functional/test_framework/test_framework.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ def main(self):
128128
help="Attach a python debugger if test fails")
129129
parser.add_argument("--usecli", dest="usecli", default=False, action="store_true",
130130
help="use bitcoin-cli instead of RPC for all commands")
131+
parser.add_argument("--perf", dest="perf", default=False, action="store_true",
132+
help="profile running nodes with perf for the duration of the test")
131133
self.add_options(parser)
132134
self.options = parser.parse_args()
133135

@@ -201,11 +203,20 @@ def main(self):
201203
node.cleanup_on_exit = False
202204
self.log.info("Note: bitcoinds were not stopped and may still be running")
203205

204-
if not self.options.nocleanup and not self.options.noshutdown and success != TestStatus.FAILED:
206+
should_clean_up = (
207+
not self.options.nocleanup and
208+
not self.options.noshutdown and
209+
success != TestStatus.FAILED and
210+
not self.options.perf
211+
)
212+
if should_clean_up:
205213
self.log.info("Cleaning up {} on exit".format(self.options.tmpdir))
206214
cleanup_tree_on_exit = True
215+
elif self.options.perf:
216+
self.log.warning("Not cleaning up dir {} due to perf data".format(self.options.tmpdir))
217+
cleanup_tree_on_exit = False
207218
else:
208-
self.log.warning("Not cleaning up dir %s" % self.options.tmpdir)
219+
self.log.warning("Not cleaning up dir {}".format(self.options.tmpdir))
209220
cleanup_tree_on_exit = False
210221

211222
if success == TestStatus.PASSED:
@@ -309,6 +320,7 @@ def add_nodes(self, num_nodes, extra_args=None, *, rpchost=None, binary=None):
309320
extra_conf=extra_confs[i],
310321
extra_args=extra_args[i],
311322
use_cli=self.options.usecli,
323+
start_perf=self.options.perf,
312324
))
313325

314326
def start_node(self, i, *args, **kwargs):

test/functional/test_framework/test_node.py

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
import time
1919
import urllib.parse
2020
import collections
21+
import shlex
22+
import sys
2123

2224
from .authproxy import JSONRPCException
2325
from .util import (
@@ -59,7 +61,13 @@ class TestNode():
5961
To make things easier for the test writer, any unrecognised messages will
6062
be dispatched to the RPC connection."""
6163

62-
def __init__(self, i, datadir, *, rpchost, timewait, bitcoind, bitcoin_cli, mocktime, coverage_dir, extra_conf=None, extra_args=None, use_cli=False):
64+
def __init__(self, i, datadir, *, rpchost, timewait, bitcoind, bitcoin_cli, mocktime, coverage_dir, extra_conf=None, extra_args=None, use_cli=False, start_perf=False):
65+
"""
66+
Kwargs:
67+
start_perf (bool): If True, begin profiling the node with `perf` as soon as
68+
the node starts.
69+
"""
70+
6371
self.index = i
6472
self.datadir = datadir
6573
self.stdout_dir = os.path.join(self.datadir, "stdout")
@@ -87,6 +95,7 @@ def __init__(self, i, datadir, *, rpchost, timewait, bitcoind, bitcoin_cli, mock
8795

8896
self.cli = TestNodeCLI(bitcoin_cli, self.datadir)
8997
self.use_cli = use_cli
98+
self.start_perf = start_perf
9099

91100
self.running = False
92101
self.process = None
@@ -95,6 +104,8 @@ def __init__(self, i, datadir, *, rpchost, timewait, bitcoind, bitcoin_cli, mock
95104
self.url = None
96105
self.log = logging.getLogger('TestFramework.node%d' % i)
97106
self.cleanup_on_exit = True # Whether to kill the node when this object goes away
107+
# Cache perf subprocesses here by their data output filename.
108+
self.perf_subprocesses = {}
98109

99110
self.p2ps = []
100111

@@ -186,6 +197,9 @@ def start(self, extra_args=None, *, stdout=None, stderr=None, **kwargs):
186197
self.running = True
187198
self.log.debug("bitcoind started, waiting for RPC to come up")
188199

200+
if self.start_perf:
201+
self._start_perf()
202+
189203
def wait_for_rpc_connection(self):
190204
"""Sets up an RPC connection to the bitcoind process. Returns False if unable to connect."""
191205
# Poll at a rate of four times per second
@@ -238,6 +252,10 @@ def stop_node(self, expected_stderr='', wait=0):
238252
except http.client.CannotSendRequest:
239253
self.log.exception("Unable to stop node.")
240254

255+
# If there are any running perf processes, stop them.
256+
for profile_name in tuple(self.perf_subprocesses.keys()):
257+
self._stop_perf(profile_name)
258+
241259
# Check that stderr is as expected
242260
self.stderr.seek(0)
243261
stderr = self.stderr.read().decode('utf-8').strip()
@@ -317,6 +335,84 @@ def assert_memory_usage_stable(self, *, increase_allowed=0.03):
317335
increase_allowed * 100, before_memory_usage, after_memory_usage,
318336
perc_increase_memory_usage * 100))
319337

338+
@contextlib.contextmanager
339+
def profile_with_perf(self, profile_name):
340+
"""
341+
Context manager that allows easy profiling of node activity using `perf`.
342+
343+
See `test/functional/README.md` for details on perf usage.
344+
345+
Args:
346+
profile_name (str): This string will be appended to the
347+
profile data filename generated by perf.
348+
"""
349+
subp = self._start_perf(profile_name)
350+
351+
yield
352+
353+
if subp:
354+
self._stop_perf(profile_name)
355+
356+
def _start_perf(self, profile_name=None):
357+
"""Start a perf process to profile this node.
358+
359+
Returns the subprocess running perf."""
360+
subp = None
361+
362+
def test_success(cmd):
363+
return subprocess.call(
364+
# shell=True required for pipe use below
365+
cmd, shell=True,
366+
stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) == 0
367+
368+
if not sys.platform.startswith('linux'):
369+
self.log.warning("Can't profile with perf; only availabe on Linux platforms")
370+
return None
371+
372+
if not test_success('which perf'):
373+
self.log.warning("Can't profile with perf; must install perf-tools")
374+
return None
375+
376+
if not test_success('readelf -S {} | grep .debug_str'.format(shlex.quote(self.binary))):
377+
self.log.warning(
378+
"perf output won't be very useful without debug symbols compiled into bitcoind")
379+
380+
output_path = tempfile.NamedTemporaryFile(
381+
dir=self.datadir,
382+
prefix="{}.perf.data.".format(profile_name or 'test'),
383+
delete=False,
384+
).name
385+
386+
cmd = [
387+
'perf', 'record',
388+
'-g', # Record the callgraph.
389+
'--call-graph', 'dwarf', # Compatibility for gcc's --fomit-frame-pointer.
390+
'-F', '101', # Sampling frequency in Hz.
391+
'-p', str(self.process.pid),
392+
'-o', output_path,
393+
]
394+
subp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
395+
self.perf_subprocesses[profile_name] = subp
396+
397+
return subp
398+
399+
def _stop_perf(self, profile_name):
400+
"""Stop (and pop) a perf subprocess."""
401+
subp = self.perf_subprocesses.pop(profile_name)
402+
output_path = subp.args[subp.args.index('-o') + 1]
403+
404+
subp.terminate()
405+
subp.wait(timeout=10)
406+
407+
stderr = subp.stderr.read().decode()
408+
if 'Consider tweaking /proc/sys/kernel/perf_event_paranoid' in stderr:
409+
self.log.warning(
410+
"perf couldn't collect data! Try "
411+
"'sudo sysctl -w kernel.perf_event_paranoid=-1'")
412+
else:
413+
report_cmd = "perf report -i {}".format(output_path)
414+
self.log.info("See perf output by running '{}'".format(report_cmd))
415+
320416
def assert_start_raises_init_error(self, extra_args=None, expected_msg=None, match=ErrorMatch.FULL_TEXT, *args, **kwargs):
321417
"""Attempt to start the node and expect it to raise an error.
322418

test/lint/lint-python-dead-code.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ fi
1515

1616
vulture \
1717
--min-confidence 60 \
18-
--ignore-names "argtypes,connection_lost,connection_made,converter,data_received,daemon,errcheck,get_ecdh_key,get_privkey,is_compressed,is_fullyvalid,msg_generic,on_*,optionxform,restype,set_privkey" \
18+
--ignore-names "argtypes,connection_lost,connection_made,converter,data_received,daemon,errcheck,get_ecdh_key,get_privkey,is_compressed,is_fullyvalid,msg_generic,on_*,optionxform,restype,set_privkey,profile_with_perf" \
1919
$(git ls-files -- "*.py" ":(exclude)contrib/" ":(exclude)test/functional/data/invalid_txs.py")

0 commit comments

Comments
 (0)