Repository navigation
Backward: Add friendly stack trace capability. - #833
Conversation
Use the Backward-cpp project (https://github.com/bombela/backward-cpp) to log stack traces on demand as desired for debugging and in response to serious errors like PANIC() and assertion failures. Unfortunately the best output from Backward-cpp requires significant dependencies (elfutils, or worse GPL binutils) that we don't want to pull in. Instead, a Python script provides automated de-interleaving of stack trace output from multiple threads and calls addr2line to decode the addresses in the stack trace using the DWARF info present in the binary. The tool accepts Envoy log output on stdin or takes arguments for a command to run as a child process and backtrace enhance the output. For example, this command will run a single test under the backtrace enhancer and show the output: bazel test -c dbg //test/common/common:backwards_test --run_under=`pwd`/tools/stack_decode.py --strategy=TestRunner=standalone --cache_test_results=no --test_output=all Since this is intended only as a debugging tool the test care merely exercises the code to ensure it does not crash without an affirmative passing case.
htuch
left a comment
There was a problem hiding this comment.
This is great and well-written, it will make developer life that much better.
Can you add docs in bazel/README.md, similar to the ones there for gdb on how to us this?
| name = "assert_lib", | ||
| hdrs = ["assert.h"], | ||
| deps = [ | ||
| ":backward_lib", |
There was a problem hiding this comment.
We need a way to kill this dependency when we do the Google import (and also for folks who do their own stack traces. We can probably use a select function in Bazel to conditionally include it, let's chat more tomorrow.
| #include "envoy/upstream/cluster_manager.h" | ||
|
|
||
| #include "common/api/api_impl.h" | ||
| #include "common/common/backward.h" |
There was a problem hiding this comment.
Where is this used in server.cc? I think it would be useful to add a signal handler (that can be easily conditioned out) in main.cc or somewhere that can trigger a backtrace on SIGSEGV, SIGILL, etc. Maybe if we do SIGABRT we don't need to modify assert_lib and can just catch the abort() here?
There was a problem hiding this comment.
This was a relic of previous testing. I was going to do the signal handler in a separate PR, I had a few questions about how to get the conditional option through the build system.
There was a problem hiding this comment.
As we came to the conclusion IRL, we want the backward dependency to be in only a few files that can be easily excluded from the build. Maybe we can add an abstract backtrace interface to include/envoy and have folks only depend on that. This would include APIs to dump stacktrace. Then, in envoy_build_system.bzl, when setting up the deps for things like envoy_cc_library, we can point it at the specific implementation that uses Backwards. For Google's (or anyone else who wants to override backwards) import, they can replace this dependency with their own.
@mattklein123 How do you override the signal handlers in the Lyft build? We would like to be able to wrap main() with our own extras for initialization (and others might want to as well).
There was a problem hiding this comment.
We don't currently, we just use the built-in libevent signal processing functionality for SIGTERM, SIGHUP, etc. We let Envoy crash and dump and then have an external process which sucks up the core dump and does stuff with it.
I think it makes sense to document which signals Envoy itself handles and then just allow people to override things like SIGABRT, SIGSEGV, etc. in main if they want. I'm open to whatever solution here makes the most sense. We could have a stub signal setup library that is called from main that is empty in the OSS build, and you could override?
Also, while we are on this topic, my vote would be to make the backtrace stuff opt-in on production builds, and default on debug builds.
There was a problem hiding this comment.
I think we should refactor main.cc into site and non-site specific files, where the site-specific file is where the main symbol lives. It will be necessary for some site to have additional flag, logging, core dump, signal handler, memory management and other deployment specific init code that might want to run before we jump into Envoy proper (and teardown code on the way out). This can be largely opaque to the regular OSS build as long as we don't put too much code inside main() and can replace it with our own.
There was a problem hiding this comment.
Yup that works for me. (Basically what you did for test main).
| #endif | ||
| backward::TraceResolver resolver; | ||
| resolver.load_stacktrace(stack_trace_); | ||
| // Our own call to Capture() should generate at least 3 stack frames, so we |
There was a problem hiding this comment.
Not that I don't think sanity checks are a good thing, but is the 3 stack frame minimum technically true with an optimizing compiler, header definition and non-virtual class?
There was a problem hiding this comment.
It might not be - and will also be untrue if I do the signal handler implementation as I realized last night. I'll update this.
There was a problem hiding this comment.
Related to this, there isn't actually any way in the current set of build options to achieve optimizations plus -g, and without -g there isn't really any useful information in the backtrace. Is -g really a runtime performance issue? It increases the size of the binary but the DWARF symbols should never be loaded unless they are accessed by something like gdb or addr2line.
There was a problem hiding this comment.
Nevermind, there is --define debug_symbols=yes. But it seems like doing it this way eliminates useful debug information for production.
There was a problem hiding this comment.
We added --define debug_symbols=yes for this purpose. You can use this for opt or any other build type.
There was a problem hiding this comment.
I don't mind making this the default for -c opt and override Bazel's opinion on this. @mattklein123 thoughts?
| return # EOF | ||
| begin_trace_match = trace_begin_re.search(line) | ||
| if begin_trace_match: | ||
| (log_prefix, objfile, thread_id) = begin_trace_match.groups() |
There was a problem hiding this comment.
Nit: I prefer not to use parentheses here when destructing as it's cleaner (but https://google.github.io/styleguide/pyguide.html#Parentheses allows it in this case, so make of that what you will).
There was a problem hiding this comment.
I defer to your preference on this, my Python experience is mostly at the hack level.
| (log_prefix, objfile, thread_id) = begin_trace_match.groups() | ||
| traces[thread_id] = (log_prefix, objfile, []) | ||
| continue | ||
| match = stackaddr_re.search(line) |
| match = stackaddr_re.search(line) | ||
| if match: | ||
| (thread_id, frame_idx, address) = match.groups() | ||
| traces[thread_id][2].append((frame_idx, address)) |
There was a problem hiding this comment.
Probably cleaner to use namedtuple to avoid having magic indexes into tuples here.
There was a problem hiding this comment.
Today (well last night) I learned about namedtuple. Useful!
| (output_stdout, output_stderr) = addr2line.communicate(piped_input) | ||
| output_lines = output_stdout.split('\n') | ||
|
|
||
| resolved_stack_frames = zip(range(1, len(output_lines)), output_lines) |
There was a problem hiding this comment.
| for stack_frame in stack: | ||
| piped_input += (stack_frame[1] + '\n') | ||
| addr2line = subprocess.Popen(['addr2line', '-Cpisfe', object_file], stdin=subprocess.PIPE, stdout=subprocess.PIPE) | ||
| (output_stdout, output_stderr) = addr2line.communicate(piped_input) |
There was a problem hiding this comment.
If you're not using output_stderr, it might be clearer to write output_stdout, _ = ...
There was a problem hiding this comment.
Another Python feature I didn't know about, cool!
| # build a dictionary indexed by thread_id: | ||
| # value is a tuple (log_prefix, obj_file, [list of addresses]) | ||
| while True: | ||
| line = input_source.readline() |
There was a problem hiding this comment.
How ctrl-c safe is this? If I run a test, then mid-way ctrl-c, killing Bazel and this script, does the child also die, or does it get turned into a zombie? It might be totally fine, I'm just curious as I've written subprocess code that creates zombies in the past this way, so could be good to quickly validate.
There was a problem hiding this comment.
If I start an Envoy like this:
tools/stack_decode.py bazel-bin/source/exe/envoy-static -c config.json
Then ctrl-C does the right thing. It does the expected thing when the output is piped into stack_decode.py too. I can add a catch for KeyboardInterrupt to avoid the ugly stack trace, though...
Added more documentation to bazel/REAMDE.md Don't ignore any part of the stack trace when printing Handle KeyboardInterrupt in a more friendly manner Python style fixes Added an additional test that verifies if Capture() wasn't able to capture any stack trace we don't crash when attempting to log.
|
|
||
| # build a dictionary indexed by thread_id: | ||
| # value is a namedtuple (log_prefix, obj_file, [list of addresses]) | ||
| Backtrace = collections.namedtuple('Backtrace', 'log_prefix obj_file, address_list') |
There was a problem hiding this comment.
General preference for declaring types that are used by multiple functions at the outer scope. You don't need to destruct the traceinfo in output_stacktrace if you do this.
| begin_trace_match = trace_begin_re.search(line) | ||
| if begin_trace_match: | ||
| log_prefix, objfile, thread_id = begin_trace_match.groups() | ||
| traces[thread_id] = Backtrace(log_prefix = log_prefix, |
There was a problem hiding this comment.
Can you run the Google pyformat on this file? I think it prefers x=y over x = y here.
There was a problem hiding this comment.
Yes, it did (and also likes " instead of ')
| thread_id = trace_end_match.groups()[0] | ||
| output_stacktrace(thread_id, traces[thread_id]) | ||
| else: | ||
| print line, # Pass through print all other log lines |
| # options | ||
| def output_stacktrace(thread_id, traceinfo): | ||
| log_prefix, object_file, stack = traceinfo | ||
| piped_input = "" |
There was a problem hiding this comment.
Nit: should be consistent about quoting style in Python. Pick either '' or "", I have a personal preference for '', but it doesn't matter as long as it's consistent.
| log_prefix, object_file, stack = traceinfo | ||
| piped_input = "" | ||
| for stack_frame in stack: | ||
| piped_input += (stack_frame[1] + '\n') |
There was a problem hiding this comment.
Best to document why you start at this stack frame.
There was a problem hiding this comment.
This index operation is actually picking the address out of the tuple (first element captured is the thread ID). I'm going to change this slightly to have better clarity.
| #include "envoy/upstream/cluster_manager.h" | ||
|
|
||
| #include "common/api/api_impl.h" | ||
| #include "common/common/backward.h" |
There was a problem hiding this comment.
As we came to the conclusion IRL, we want the backward dependency to be in only a few files that can be easily excluded from the build. Maybe we can add an abstract backtrace interface to include/envoy and have folks only depend on that. This would include APIs to dump stacktrace. Then, in envoy_build_system.bzl, when setting up the deps for things like envoy_cc_library, we can point it at the specific implementation that uses Backwards. For Google's (or anyone else who wants to override backwards) import, they can replace this dependency with their own.
@mattklein123 How do you override the signal handlers in the Lyft build? We would like to be able to wrap main() with our own extras for initialization (and others might want to as well).
| * Indicate a panic situation and exit. | ||
| */ | ||
| #define PANIC(X) \ | ||
| BACKTRACE_PROD_LOG(); \ |
There was a problem hiding this comment.
Maybe remove these from this PR and wait until the signal handler PR one so that we can just trigger on sigabrt.
Python style updates Relocated to source/server Bazel build options adjusted and redocumented Cleaned up some other items
htuch
left a comment
There was a problem hiding this comment.
LGTM modulo comments. I'm assuming you're leaving the backtrace_lib link step to the followup PRs..
| "//conditions:default": ["-DTCMALLOC"], | ||
| }) + select({ | ||
| # Allow debug symbols to be added to opt/fastbuild as well. | ||
| repository + "//bazel:debug_symbols": ["-ggdb3"], |
There was a problem hiding this comment.
Can you also remove debug_symbols from bazel/BUILD?
| output_lines = output_stdout.split('\n') | ||
| output_lines = output_stdout.split("\n") | ||
|
|
||
| resolved_stack_frames = list(enumerate(output_lines, start=1)) |
There was a problem hiding this comment.
Nit: shouldn't need to convert to list, leaving as an iterator is fine (and more efficient, not that it matters here) as it is consumed only in the for loop below.
| print "%s Backtrace (most recent call first) from thread %s:" % ( | ||
| traceinfo.log_prefix, thread_id) | ||
| for stack_frame in resolved_stack_frames: | ||
| print " #%s %s" % (stack_frame[0], stack_frame[1]) |
There was a problem hiding this comment.
Nit: this can just be written % stack_frame.
| else: | ||
| print line, # Pass through print all other log lines | ||
| # Pass through print all other log lines: | ||
| print line, |
There was a problem hiding this comment.
Trailing , inhibits print from adding the extra newline, it's deliberate.
There was a problem hiding this comment.
I learnt something new about Python today.
Remove no longer used option from bazel/BUILD Python style nits
Because: print foo_string_ending_in_newline, just looks ridiculous.
| import sys | ||
|
|
||
| Backtrace = collections.namedtuple("Backtrace", | ||
| "log_prefix obj_file, address_list") |
There was a problem hiding this comment.
nit: any reason why there isn't a comma after log_prefix, or switching to whitespace between obj_file and address_list? From docs it looks like both are valid but seems odd to use both?
There was a problem hiding this comment.
No reason, I think it came from my originally using commas and pyformat tool mangling it. I'll push one more fix for this.
|
@dnoe also needs a master merge. |
|
complete envoy noob question here but : is there a build mode or runtime flag of envoy to not try to trap crashes at all and just fall back to generating a core (or even better a wrapper that gdb "bt all" after crash) |
Use the Backward-cpp project (https://github.com/bombela/backward-cpp)
to log stack traces on demand as desired for debugging and in response
to serious errors like PANIC() and assertion failures.
Unfortunately the best output from Backward-cpp requires significant
dependencies (elfutils, or worse GPL binutils) that we don't want to
pull in. Instead, a Python script provides automated de-interleaving of
stack trace output from multiple threads and calls addr2line to decode
the addresses in the stack trace using the DWARF info present in the
binary. The tool accepts Envoy log output on stdin or takes arguments
for a command to run as a child process and backtrace enhance the
output. For example, this command will run a single test under the
backtrace enhancer and show the output:
bazel test -c dbg //test/common/common:backwards_test
--run_under=
pwd/tools/stack_decode.py--strategy=TestRunner=standalone --cache_test_results=no
--test_output=all
Since this is intended only as a debugging tool the test care merely
exercises the code to ensure it does not crash without an affirmative
passing case.