Part 4 · Operations and troubleshooting · Lesson 07 · 55 minutes
Troubleshoot CPU and memory problems
- Find a runaway process and a zombie and say how each one is dealt with
- Limit the CPU and the memory of a process with a control group, and read an out-of-memory kill
- Read memory pressure and swap and say what the numbers mean
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A server answers slowly at the end of every month. The load average is high, and sometimes a service is gone in the morning with no message of its own. Your lead says: "Find what takes the CPU. Find what takes the memory. Show me why the service died." You plant the same problems in your practice system, with small scripts, and find each one with the tools that you already know and one or two new ones.
Recall
The load average is 8 on a machine with 4 CPUs. What does it say?
On average eight tasks wanted a CPU or waited for the disk, for four CPUs. The machine is overloaded, or the tasks wait for the disk. Read top and vmstat to see which (lesson 2 of Part 2).
Which state letter does ps show for a zombie, and why can you not kill it with kill -9?
Z. A zombie is already dead: it only waits for its parent to read its exit code, so there is nothing left to kill (lesson 5 of Part 2).
The idea
Three resources run out, and each one fails in its own way.
| Resource | What you see | Tool |
|---|---|---|
| CPU | One process at 100%, a high load, slow answers | ps --sort=-pcpu, top |
| Memory | Free memory near zero, swap in use, a process that vanishes | free, /proc/pressure/memory, the journal |
| Process table | A growing list of Z entries | ps with the state and the parent |
A runaway process uses a CPU for nothing, usually a loop that never ends. A zombie is a finished child whose parent never collected its exit code. The fix for a zombie is its parent: a fix for the child does not exist. When memory runs out, the kernel starts the out-of-memory killer (OOM killer): it picks a process by a score that grows with its memory use, and ends it with SIGKILL. A control group (cgroup) lets you set a limit for one service, so that the kill falls on the guilty service, not on a random one. systemd sets the limit with MemoryMax= and CPUQuota=.
- You → systemd-run: start it with MemoryMax=50M
- systemd-run → Process: run inside its own cgroup
- Process → Kernel: asks for more memory
- Kernel → Process: the cgroup is full: SIGKILL
- Kernel → Journal: oom-kill is written
Worked example
Use the scripts of this lesson. The commands with sudo need administrator rights. The outputs come from a virtual machine with 4 CPUs and 4 GB of memory, so your numbers differ.
1. Plant a runaway and find it
Save the runaway as spin.sh. Start it in the background and look at the processes sorted by CPU. ps -eo FIELDS chooses the columns, and --sort=-pcpu puts the busiest first. $! is the PID of the last background job.
spin.sh
#!/bin/bash
# spin.sh - a runaway process: it does nothing, as fast as it can
while :; do :; donecd ~/krlab/linux-operations
chmod +x spin.sh
./spin.sh &
SPIN=$!
sleep 3
ps -eo pid,pcpu,ni,stat,args --sort=-pcpu | head -n 3 PID %CPU NI STAT COMMAND
587 100 0 R /bin/bash ./spin.sh
576 8.2 0 Ss /usr/lib/systemd/systemd --userThe state R is running, and the first process uses almost a whole CPU. %CPU of ps is an average over the life of the process, which is fine for a process that has spun since it started.
2. Slow it down, then end it
renice -n 19 -p PID makes the process the most polite one, so that other work goes first (lesson 5 of Part 2). It does not reduce the load when the CPUs are idle. A hard limit does. systemd-run starts a command as a temporary service, --unit names it and -p CPUQuota=20% allows it one fifth of one CPU. top -b -n 2 -d 3 -p PID prints two reports three seconds apart, in batch mode; the second one shows the current use.
kill $SPIN
sudo systemd-run --unit krlab-spin -p CPUQuota=20% "$PWD/spin.sh"
sleep 3
top -b -n 2 -d 3 -p $(systemctl show -p MainPID --value krlab-spin) | tail -n 1
sudo systemctl set-property --runtime krlab-spin CPUQuota=5%
sleep 3
top -b -n 2 -d 3 -p $(systemctl show -p MainPID --value krlab-spin) | tail -n 1
sudo systemctl stop krlab-spinRunning as unit: krlab-spin.service; invocation ID: 4f619728a4914605a1f9f2f50838e93b
593 root 20 0 9944 3644 3388 R 20.0 0.1 0:01.27 spin.sh
593 root 20 0 9944 3644 3388 R 5.0 0.1 0:01.58 spin.shThe %CPU column went from 20 to 5 while the process ran. On some machines set-property also prints a warning that the unit changed on disk: it is harmless for this temporary unit. set-property --runtime changes the limit of a running unit until the next reboot. The limit is a way to keep a service alive while you find the cause.
3. Find a zombie
Save zombie.py. The parent makes a child, the child ends at once, and the parent sleeps without calling wait. awk '$3 ~ /^Z/' keeps the lines whose third field (the state) starts with Z.
zombie.py
#!/usr/bin/env python3
"""zombie.py - a parent that never collects its child, so the child stays as a zombie."""
import os
import time
if os.fork() == 0:
os._exit(0) # the child ends at once
time.sleep(600) # the parent sleeps and never calls wait()chmod +x zombie.py
./zombie.py &
PARENT=$!
sleep 1
ps -eo pid,ppid,stat,args | awk '$3 ~ /^Z/' 610 608 Z [python3] <defunct>Read the line like this:
The zombie holds only a slot of the process table, but thousands of them can fill it. Find the parent in the list, read what it is, and end it: init then adopts the zombie and clears it.
ps -o pid,stat,args -p $PARENT
kill $PARENT
sleep 1
ps -eo stat | grep -c '^Z' PID STAT COMMAND
608 S python3 ./zombie.py
0The count is 0 unless another program on your machine has a zombie of its own.
4. Read the memory
Save memhog.py. It takes memory in steps of 10 MB and keeps it. The second argument hold makes it wait ten minutes at the end.
memhog.py
#!/usr/bin/env python3
"""memhog.py - takes memory in steps of 10 MB and keeps it. Usage: memhog.py MEGABYTES [hold]"""
import sys
import time
chunks = []
for mb in range(10, int(sys.argv[1]) + 1, 10):
chunks.append(bytearray(10 * 1024 * 1024)) # bytearray fills the memory with zeros, so it is really used
print(f"holding {mb} MB", flush=True)
time.sleep(0.2)
time.sleep(600 if len(sys.argv) > 2 else 2)
print("done", flush=True)free -m shows memory in megabytes. /proc/pressure/memory is the pressure stall information: the share of time in which tasks had to wait for memory. A value near zero is healthy.
chmod +x memhog.py
./memhog.py 100 hold > /dev/null &
HOG=$!
sleep 3
ps -o pid,rss,args -p $HOG
free -m | head -n 2
cat /proc/pressure/memory
kill $HOG PID RSS COMMAND
617 111896 python3 ./memhog.py 100 hold
total used free shared buff/cache available
Mem: 3824 433 3467 23 113 3391
some avg10=0.00 avg60=0.00 avg300=0.00 total=104
full avg10=0.00 avg60=0.00 avg300=0.00 total=39The pressure lines have five parts:
RSS is the memory that the process really holds in RAM, in kilobytes: about 109 MB here. Watch the column available of free: it counts memory that the system can give back. Trouble starts when it is small and the pressure numbers rise.
5. Read an out-of-memory kill
Run the program as a service that may use 50 MB. --wait waits until it ends and prints the result, and --collect removes the unit afterwards even if it failed, so that you can reuse the name. In the next command, journalctl -u reads the log of one unit, --no-pager prints without a pager, and -o cat prints only the message text. MemorySwapMax=0 forbids swap, so that the limit works the same on every machine. The program wants 200 MB.
sudo systemd-run --wait --collect --unit krlab-hog -p MemoryMax=50M -p MemorySwapMax=0 python3 "$PWD/memhog.py" 200
sudo journalctl -u krlab-hog --no-pager -o cat | tail -n 3
sudo journalctl -k --no-pager | grep "out of memory" | tail -n 1 | cut -c1-100Running as unit: krlab-hog.service; invocation ID: a7f4089192a84d728eeb83f92289549e
Finished with result: oom-kill
Main processes terminated with: code=killed/status=KILL
Service runtime: 890ms
CPU time consumed: 86ms
Memory peak: 50.0M
Memory swap peak: 0B
krlab-hog.service: A process of this unit has been killed by the OOM killer.
krlab-hog.service: Main process exited, code=killed, status=9/KILL
krlab-hog.service: Failed with result 'oom-kill'.
Nov 21 18:57:07 krbox kernel: Memory cgroup out of memory: Killed process 628 (python3) total-vm:716The result oom-kill and the signal 9 tell the story. The service was killed by the kernel, and not by a bug in its own code, so its own log has no error message. The kernel log (journalctl -k, or sudo dmesg) names the victim: Memory cgroup out of memory means that the limit of one group was reached. When the whole machine runs out of memory, the line starts with Out of memory: Killed process instead. Run the program again with a limit that is large enough:
sudo systemd-run --wait --collect --unit krlab-ok -p MemoryMax=300M -p MemorySwapMax=0 python3 "$PWD/memhog.py" 100 2>&1 | grep "result"Finished with result: success6. Read swap
Swap is disk space that the kernel uses when RAM is full: it moves memory that is not in use to the disk. A little swap is normal. Swap that is read and written all the time (thrashing) makes the machine very slow. swapon --show lists the swap areas, and the columns si and so of vmstat show memory swapped in and out each second (lesson 2 of Part 2). If swapon --show prints nothing, your system has no swap: add a swap file of 1 GB as in lesson 4 of Part 2 (sudo swapon FILE starts it).
This time the memory holder gets a limit of 100 MB but no MemorySwapMax=0, so the kernel may move the rest of its memory to swap. systemctl status shows the memory and the swap of the unit.
sudo systemd-run --unit krlab-swap -p MemoryMax=100M python3 "$PWD/memhog.py" 200 hold
sleep 8
systemctl status krlab-swap --no-pager | grep Memory:
swapon --show
free -m | grep -i swap
cat /proc/pressure/memory
sysctl vm.swappiness
sudo systemctl stop krlab-swapRunning as unit: krlab-swap.service; invocation ID: 77e5ac31c9e14d2787a31355704e77c7
Memory: 99.8M (max: 100.0M available: 192.0K peak: 100.0M swap: 105.2M swap peak: 105.2M)
NAME TYPE SIZE USED PRIO
/root/kr/swapfile file 1024M 105.9M -2
Swap: 1023 105 918
some avg10=1.30 avg60=0.44 avg300=0.10 total=385080
full avg10=1.30 avg60=0.44 avg300=0.10 total=382655
vm.swappiness = 60The unit holds 100 MB in RAM and the other 105 MB in swap, so it was not killed. The pressure numbers rose above zero: tasks waited while the kernel wrote memory to the disk. vm.swappiness (0 to 200) says how willing the kernel is to swap before it drops cache. Swap gives time, not memory: the cure for a lasting shortage is to find the process that holds the memory, or to add RAM.
Your turn
Save plant.sh. It starts the three scripts above in the background: a runaway, a zombie parent and a memory holder. Run bash plant.sh, wait three seconds, and find them with ps (ps -eo pid,ppid,stat,rss,args). The parent of the zombie is the number in the column ppid of the line with the state Z. Then run bash plant.sh stop, and run the memory test with systemd-run as in step 5, but with other sizes.
plant.sh
#!/bin/bash
# plant.sh - starts three misbehaving processes. "bash plant.sh stop" ends them.
cd "$(dirname "$0")"
chmod +x spin.sh zombie.py memhog.py
if [ "${1:-}" = "stop" ]; then
kill $(cat plant.pids) 2> /dev/null
rm -f plant.pids
echo "stopped"
exit 0
fi
./spin.sh &
echo $! > plant.pids
./zombie.py &
echo $! >> plant.pids
./memhog.py 60 hold > /dev/null &
echo $! >> plant.pids
echo "planted: 3 processes"Check yourself
A zombie shows in ps. You run kill -9 on it, and it stays. What do you do?
Find its parent (the PPID column) and fix or end the parent. The zombie is only an exit code that nobody has read. When the parent ends, init adopts the zombie and removes it.
A service died in the night with no error in its own log. Which two things do you look at?
The status of the unit and the journal for oom-kill, which show a kill by the kernel, and the kernel log for "Out of memory". A process that receives SIGKILL cannot write a last message.
Why is a CPU quota a better first aid than kill for a production service?
The service stays up and serves requests, slower, while you search for the cause. kill ends it, and a service that restarts by itself will often start the same loop again.
The load average is high, but top shows the CPUs idle. What may be wrong?
Tasks wait for the disk (state D) and count in the load. Check vmstat for the column wa, and iostat for a busy disk (lesson 2 of Part 2).
Field notes
- Set
MemoryMax=andCPUQuota=(andTasksMax=) in the unit files of services that can misbehave, so that one service cannot take the whole machine. - Give the services that must survive a lower chance of being chosen by the OOM killer with
OOMScoreAdjust=in the unit, for example a negative value. Never make a service immune and the rest of the system weak. - Memory that "disappears" is often a leak. Compare the
RSSof the same process over hours; a slow steady rise is the sign. Restart on a schedule only as a bridge to a real fix. - A fork bomb or a leak of file descriptors fills other tables.
ulimit -ashows the limits of your shell, andTasksMax=andLimitNOFILE=set them for a service. - Write down the numbers before and after each change. "It got better" is not a measurement.