Debugging Stuck Ruby Processes: What to do Before You Kill -9
Join the DZone community and get the full member experience.Join For Free
railsconf 2013 has begun! to celebrate, we’re publishing a series of blog post that highlight what’s new and exciting in the world of new relic’s ruby support. don’t forget to check out the entire series so far:
cross application tracing
living on the edge with rails 4 & ruby 2
thread safe apis & sidekiq support for your threading
security banners (for if you forgot to apply the latest cve patch)
if you’ve spent enough time working with a production system (or even just a continuous integration server), you’ve surely encountered a ruby process that was ‘stuck’. you know the type – not crashing, but not making any real progress either. and giving you no obvious indication of what it was doing.
when finding a stuck process, your primary goal usually is to just get the wheels of progress turning again. and the quickest path to that goal is usually to `kill -9` the stuck process and re-start it.
but i want to you to make your future self a promise. the next time this happens, don’t just kill that stuck process and move on. dig in and figure out what’s really going on. you might just discover the root cause of your problem, hone your debugging techniques or discover a clue that helps you fix that tricky bug in your favorite open source project that no one has been able to pin down.
since encountering a stuck process (especially in production) is often stressful, i find it helps to think about the debugging steps you plan to take ahead of time. create a ‘checklist’ of things to run through so you don’t forget anything or skip any steps. failing to capture enough information to reproduce a bug usually means you’ll hit it again. so make sure you seize the opportunity when it’s available.
here are the steps i follow when debugging a stuck ruby process:
who said what?
first, figure out exactly what process is stuck. this sounds trivial, but it’s especially important for systems like unicorn , passenger , resque , etc. where the system is composed of multiple processes that have different roles (often a single master process plus a number of workers).
identifying exactly which process is stuck is important in order to get a full picture of the behavior of the system as a whole. the trusty ps utility is usually my first stop here — a quick `ps aux | grep <process name>`.
i like to keep a transcript of the exact commands i’ve run, along with their output. and the ps aux output is usually the first thing that goes into that transcript.
tools like htop and pstree can also be useful here. they give you a visual tree of the relationship between the stuck process, its sibling and its parent process (e.g. a unicorn master and its workers).
grab any logs that are available
again this may seem obvious, but the goal of the checklist is to remind you of everything you need to track. this will give you the best possible chance of debugging the problem offline. before getting started, consider these questions:
* where is stdout of the stuck process being sent?
* where is stderr of the stuck process being sent?
* are there any other log files created by the stuck process? check the command line and config file used for the process. did either specify a log path?
* are there any other log files created by processes related to the stuck process?
other non-invasive basics
try gathering the following before you move into the more invasive actions:
* grab the list of open files and sockets from the process using lsof -p <pid>
* if you’re on linux, poke around in /proc/<pid> and consider gathering:
* cmdline contains the command line that was used to launch the process
* cwd is a link to the current working directory of the process
* environ is a list of environment variables set for the process
check the cpu usage of the stuck process
there are two basic flavors of hangs: static and dynamic. (note: this is my own terminology, but i think it’s a useful taxonomy.) in a static hang, the threads of the stuck process are stuck in the same exact state for an extended period of time. examples include traditional deadlocks and processes blocked for extended periods in system calls (often things like ‘read`, `select`, etc.). in a dynamic hang, the threads of the stuck process are changing state, but are caught in some kind of loop that prevents them from making progress (this is sometimes called a ‘livelock’).
the techniques used to debug the two types of hangs are different. so it’s useful to be able to differentiate between them in the wild. a quick heuristic for doing this is to check the cpu usage of the stuck process. static hangs will generally result in processes with no cpu usage, whereas dynamic hangs will result in processes with non-zero cpu usage (often very high, if the process is stuck in a tight loop).
there are a variety of tools you can use to do this, but a quick look at `top` or `ps -o cpu <pid>` is often enough.
for static hangs where the stuck process demonstrates no cpu usage, gather information on the backtraces of all threads in the stuck process. this is often the most important data. since the threads aren’t changing state, a single snapshot of thread backtraces is usually sufficient.
there are a variety of different tools for accomplishing this goal, depending on the platform you’re running on and the ruby implementation you’re using, but i’m going to focus on what is perhaps the most common case: mri on a linux host.
`gdb` is a time-tested and widely available tool that can be used to interrogate a running process on a variety of unix-ish platforms. you can attach to a running process with gdb by using the -p option, like this:
``` gdb -p ```
once gdb has successfully attached to the target process, it will drop you at a prompt. the very first thing you should do here is to gather c-level backtraces for all threads of the stuck process, like this:
``` (gdb) t a a bt ```
this is short for `thread apply all backtrace`. copy this output and save it to your transcript file, even if it’s not immediately informative.
sometimes c-level backtraces are all you need in order to debug a hang. in other cases though, you really need a ruby-level backtrace to see what’s going on. luckily, gdb can help you generate those, too.
getting a ruby backtrace with gdb
getting a ruby backtrace out of gdb involves interacting with the ruby interpreter in the running process that you’ve attached to. and to get that, the interpreter needs to be in a semi-working state. if the root cause of the issue is a ruby bug, the process may be stuck in such a way that it isn’t possible to get the backtrace at all.
that said, it’s always worth trying. here’s the technique i use:
most mechanisms for dumping ruby backtraces will output them to stdout or stderr. it’s fine if you know where the stdout and stderr for your process is going, and you have access to it. if not, first you’ll need to redirect the output streams to an accessible location.
to do this, we rely on posix conventions and some trickery. stdout and stderr are file descriptors 1 and 2 on posix-compliant systems. we want to close these file descriptors, and re-open them attached to files that we can actually read from. closing is easy:
``` (gdb) call (void) close(1) (gdb) call (void) close(2) ```
the call command tells gdb to invoke close from within the target process. next, we need to re-associate file descriptors 1 and 2 with a file we can actually read from. we could use a file on the filesystem, but it’s even more convenient to see the output directly in gdb. to do that, we want to figure out the device file corresponding to our current tty and open it twice. since file descriptors are assigned sequentially, descriptors 1 and 2 will end up being re-associated with our tty device. here’s how this looks:
``` (gdb) shell tty /dev/pts/0 (gdb) call (int) open("/dev/pts/0", 2, 0) $1 = 1 (gdb) call (int) open("/dev/pts/0", 2, 0) $2 = 2 ```
now, any output generated by the target process will be echoed directly to our console so we can see it in our gdb session.
finally, we need to get the ruby interpreter in the target process to spit out a backtrace. there are many ways to do this. but the easiest way is just to use gdb to call the rb_backtrace() function from the ruby interpreter directly:
``` (gdb) call (void)rb_backtrace() ```
with luck, you’ll see a ruby backtrace dumped to your console.
digging deeper with gdb
if you know what you’re looking for in the stuck process, there’s a lot more you can do with gdb. jon yurek at thoughtbot has a great post on this topic that explains how you can get gdb to evaluate arbitrary ruby code in the target process to inspect the values of ruby variables, get backtraces for all threads and any number of other things
a stuck process that shows high cpu usage is likely stuck in a tight loop. this means that the exact backtraces you get out of it may vary from one sample to the next, but backtraces can still be very helpful to point you in the right direction.
if you find a stuck process with high cpu usage, it may be worth gathering backtraces 2 or 3 times to get a more representative sample. (you can use gdb’s continue command to resume the process after you’ve attached).
you can also use other tracing tools to examine the behavior of the looping process. on linux, strace -p <pid> allows you to view the system calls being made by the process. if you’re on an os that has dtrace available, you can use dtruss -p <pid> instead to get a similar output.
thanks, from your future self
you might not always have the luxury of being able to spend time debugging a stuck process. but when you do dive in, you’ll probably be glad you did. i’ve only scratched the surface of the tools available for analyzing problems like this, but hopefully i’ve given you enough information that you’ll be comfortable doing more than just sighing, sigkill-ing, and waiting for your problem to reappear.
bonus: mac os x
if you happen to be debugging a stuck process on mac os x, check out this sample utility (a handy tool that ships with os x). it will automate the collection of multiple c-level backtraces, aggregate them together and print out a nicely formatted call tree report showing where the stuck process is spending most of its time.
Published at DZone with permission of Leigh Shevchik, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
A React Frontend With Go/Gin/Gorm Backend in One Project
Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
What to Pay Attention to as Automation Upends the Developer Experience
Step Into Serverless Computing