Skip to content

Backward: Add friendly stack trace capability. - #833

Merged
mattklein123 merged 8 commits into
envoyproxy:masterfrom
dnoe:backwards
Apr 26, 2017
Merged

mattklein123 merged 8 commits into
envoyproxy:masterfrom
dnoe:backwards

Conversation

@dnoe

@dnoe dnoe commented Apr 24, 2017

Copy link
Copy Markdown
Contributor

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.

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 htuch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread source/common/common/BUILD Outdated
name = "assert_lib",
hdrs = ["assert.h"],
deps = [
":backward_lib",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread source/server/server.cc Outdated
#include "envoy/upstream/cluster_manager.h"

#include "common/api/api_impl.h"
#include "common/common/backward.h"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup that works for me. (Basically what you did for test main).

Comment thread source/common/common/backward.h Outdated
#endif
backward::TraceResolver resolver;
resolver.load_stacktrace(stack_trace_);
// Our own call to Capture() should generate at least 3 stack frames, so we

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nevermind, there is --define debug_symbols=yes. But it seems like doing it this way eliminates useful debug information for production.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We added --define debug_symbols=yes for this purpose. You can use this for opt or any other build type.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't mind making this the default for -c opt and override Bazel's opinion on this. @mattklein123 thoughts?

Comment thread tools/stack_decode.py Outdated
return # EOF
begin_trace_match = trace_begin_re.search(line)
if begin_trace_match:
(log_prefix, objfile, thread_id) = begin_trace_match.groups()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I defer to your preference on this, my Python experience is mostly at the hack level.

Comment thread tools/stack_decode.py Outdated
(log_prefix, objfile, thread_id) = begin_trace_match.groups()
traces[thread_id] = (log_prefix, objfile, [])
continue
match = stackaddr_re.search(line)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: stackaddr_match

Comment thread tools/stack_decode.py Outdated
match = stackaddr_re.search(line)
if match:
(thread_id, frame_idx, address) = match.groups()
traces[thread_id][2].append((frame_idx, address))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably cleaner to use namedtuple to avoid having magic indexes into tuples here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Today (well last night) I learned about namedtuple. Useful!

Comment thread tools/stack_decode.py Outdated
(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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Familiar story :)

Comment thread tools/stack_decode.py Outdated
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're not using output_stderr, it might be clearer to write output_stdout, _ = ...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another Python feature I didn't know about, cool!

Comment thread tools/stack_decode.py Outdated
# build a dictionary indexed by thread_id:
# value is a tuple (log_prefix, obj_file, [list of addresses])
while True:
line = input_source.readline()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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...

dnoe added 2 commits April 25, 2017 10:31
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.
Comment thread tools/stack_decode.py Outdated

# 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')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tools/stack_decode.py Outdated
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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you run the Google pyformat on this file? I think it prefers x=y over x = y here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it did (and also likes " instead of ')

Comment thread tools/stack_decode.py Outdated
thread_id = trace_end_match.groups()[0]
output_stacktrace(thread_id, traces[thread_id])
else:
print line, # Pass through print all other log lines

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: , at EOL

Comment thread tools/stack_decode.py
# options
def output_stacktrace(thread_id, traceinfo):
log_prefix, object_file, stack = traceinfo
piped_input = ""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tools/stack_decode.py Outdated
log_prefix, object_file, stack = traceinfo
piped_input = ""
for stack_frame in stack:
piped_input += (stack_frame[1] + '\n')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Best to document why you start at this stack frame.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread source/server/server.cc Outdated
#include "envoy/upstream/cluster_manager.h"

#include "common/api/api_impl.h"
#include "common/common/backward.h"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread source/common/common/assert.h Outdated
* Indicate a panic situation and exit.
*/
#define PANIC(X) \
BACKTRACE_PROD_LOG(); \

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 htuch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also remove debug_symbols from bazel/BUILD?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure

Comment thread tools/stack_decode.py Outdated
output_lines = output_stdout.split('\n')
output_lines = output_stdout.split("\n")

resolved_stack_frames = list(enumerate(output_lines, start=1))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tools/stack_decode.py Outdated
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])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this can just be written % stack_frame.

Comment thread tools/stack_decode.py Outdated
else:
print line, # Pass through print all other log lines
# Pass through print all other log lines:
print line,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: still the trailing ,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trailing , inhibits print from adding the extra newline, it's deliberate.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I learnt something new about Python today.

dnoe added 2 commits April 25, 2017 15:54
Remove no longer used option from bazel/BUILD
Python style nits
Because:

print foo_string_ending_in_newline,

just looks ridiculous.
Comment thread tools/stack_decode.py Outdated
import sys

Backtrace = collections.namedtuple("Backtrace",
"log_prefix obj_file, address_list")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No reason, I think it came from my originally using commas and pyformat tool mangling it. I'll push one more fix for this.

@mattklein123

Copy link
Copy Markdown
Member

@dnoe also needs a master merge.

@mattklein123
mattklein123 merged commit c3f486c into envoyproxy:master Apr 26, 2017
@ldemailly

Copy link
Copy Markdown

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)

@mattklein123

Copy link
Copy Markdown
Member

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants