Investigating and Resolving AWS EC2 Freezing Issues: Troubleshooting Low Memory

English

My EC2 instance occasionally starts hanging. 2022/03/31
This started happening after setting up the WordPress environment. I was careful about storage capacity during installation and everything seemed fine. This is a memo of the investigation.

Investigation 1

It happens about once every 1 to 2 days, always sometime in the middle of the night. AWS monitoring shows that CPU utilization spikes to 100%, followed by a status check failure, and every 30 minutes, network access for backups drops off. SSH login also becomes impossible. (※ When it happened the first time, it was barely clinging to life and SSH was extremely sluggish.)

Checking EC2 Monitoring Logs

CPU utilization pins at 100%, after which CPU credits are exhausted, bringing CPU utilization down to 0%, and the system hangs completely. While there were still CPU credits left, SSH was probably just barely working.

According to AWS EC2 monitoring, CPU utilization started climbing on 3/31 at 3:35, staying at 100% from 3:40 to 4:00.
At 4:10, CPU credits hit 0, and CPU utilization dropped to 0.

Linux System Log Investigation

There are suspicious records in the system logs.
I checked the system log at /var/log/syslog. There are logs showing the OS hanging and dumping.
This is my first time analyzing a Linux hang, but it's pretty interesting.

—-Is this where the kernel starts screaming?——
Mar 31 04:06:49 ip-172-31-45-138 systemd-networkd[402]: eth0: Could not set DHCPv4 address: Connection timed out
Mar 31 04:08:24 ip-172-31-45-138 systemd-networkd[402]: eth0: Failed

Wait, the Ethernet interface is dead?!

–From here on, the kernel is screaming and dumping logs—–
Mar 31 04:09:30 ip-172-31-45-138 kernel: [101314.179745] systemd invoked oom-killer: gfp_mask=0x100cca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0
Mar 31 04:09:31 ip-172-31-45-138 kernel: [101314.179754] CPU: 0 PID: 1 Comm: systemd Not tainted 5.13.0-1019-aws #21~20.04.1-UbuntuMar 31 04:09:31 ip-172-31-45-138 kernel: [101314.179757] Hardware name: Xen HVM domU, BIOS 4.11.amazon 08/24/2006systemd invoked oom-killer:

What is the oom-killer?! Looking it up, oom stands for Out Of Memory, and it seems to be a log where [systemd] selected and killed a process to prevent out-of-memory conditions. This is likely a log of the system trying to recover after something went rogue and consumed infinite CPU and memory. The process that got killed was the Minecraft server; looking at the oom-killer process logs, it definitely seems to have been eating up the most memory. Let's check right around that time.

Most things running periodically seem to be executed via cron.
・Minecraft backup → Done intentionally


Mar 31 03:30:01 ip-172-31-45-138 CRON[15399]: (ubuntu) CMD (/home/ubuntu/MinecraftServerBedrock/worlds/mc_backup_hourly_YuikaAndB.sh)
Mar 31 03:30:31 ip-172-31-45-138 CRON[15398]: (CRON) info (No MTA installed, discarding output)
・(CRON) info (No MTA installed, discarding output)

→ This log appears when mail settings are not configured. If configured, it apparently emails error details.
Could something in the backup script be throwing an error? Since it also appears before the hang occurs, it doesn't seem to be related to the hang.

・Next is php's phpsessionclean.service: Succeeded. → Is this cleaning up PHP installed for WordPress? PHP-related things are suspicious because the installation froze halfway, but the logs show it succeeding.

・Next is apt updates, daily updates perhaps?
Mar 31 03:39:23 ip-172-31-45-138 systemd[1]: Starting Daily apt download activities…
  :
Mar 31 03:39:28 ip-172-31-45-138 systemd[1]: Started PackageKit Daemon.
Mar 31 03:44:56 ip-172-31-45-138 PackageKit: daemon quit

Mar 31 03:49:18 ip-172-31-45-138 packagekitd[15843]: Error releasing name org.freedesktop.PackageKit: Timeout was reached
↑ That's a major error showing up. Could this error have triggered the hang? It looks like a network timeout, but it could be caused by something else. Still, I suspect it straight-up killed the apt processes. Indeed, when installing PHP via apt, it froze midway. Could this be the cause?

Towards the end of the dump,
—The Minecraft server is being killed due to insufficient memory.—
Mar 31 04:09:31 ip-172-31-45-138 kernel: [101314.180132] Out of memory: Killed process 10850 (bedrock_server) total-vm:1026932kB, anon-rss:376956kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:1016kB oom_score_adj:0
Followed by logs of various things being stopped.

After that, cron logs for the Minecraft backup and PHP cleanup appear periodically. It doesn't seem completely dead.
Daily apt updates are also succeeding.

Modifying Settings to Record Cron Logs

■ Configuring rsyslog to record cron logs
It felt like the cron Minecraft backup script was throwing errors, but I couldn't find any cron logs. Ubuntu apparently disables cron logs by default, so I'll change the settings to record them.


$ cd /etc/rsyslog.d
$ sudo cp -p 50-default.conf 50-default.conf_$(date “+%Y%m%d_%H%M%S”)
$ sudo emacs 50-default.conf
cron.* /var/log/cron.log # Before editing

↓
cron.* /var/log/cron.log # After editing

$ sudo systemctl restart rsyslog

Logs are located at /var/log/cron
Logs started appearing, but they contain the exact same content as syslog. Useless.

The Cause is Out of Memory

■ systemd invoked oom-killer:
What is the OOM Killer?
"Have you ever experienced a critical application process suddenly dying on Linux, yet checking the application logs reveals no errors outputted? In such cases, the OOM Killer may have terminated the process due to system memory exhaustion."
There is no doubt that running out of memory due to some factor is what's breaking things.

■ Checking memory usage with the top command
Since it's a memory shortage, I want to check which processes are consuming memory. You can see this with the top command. Top displays process information updated in real-time. It looks like you can sort using the following shortcuts. This is definitely worth taking a note of.
・shift+m: Sort by memory usage
・shift+p: Sort by CPU usage (default)

■ Checking memory usage with the ps command
It turns out you can also sort using the classic ps command.
ps aux --sort -%mem |head -n30
For -%mem, it seems if you input the column header name from the first line of the ps command, it will sort by that.
Copy and paste the output into Excel.


Since the unit for RSS during a dump isn't very clear, I calculated and analyzed the ratio between the dump's RSS and the top command's RSS.

dump-rss topRSS Ratio Process Name
94239 139876 1.484268721 bedrock_server
34864 120444 3.454681046 s3fs
17076 70996 4.157648161 mysqld
12044 apt-check
9675 43672 3.626037861 apache2
9178 42488 4.391524548 apache2
8926 41216 4.490738723 apache2
8903 39672 4.444544029 apache2
8758 39436 4.42951814 apache2
8517 39400 4.498744005 apache2
4500 18000 2.113420218 multipathd

As a result, the Minecraft server normally uses about 140M, which is the highest consumer. During abnormal times, relative to everything else, it feels like it's consuming an abnormal amount. The next highest is s3fs, the command that mounts AWS S3. It consumes a whopping 120M. Let's get rid of it.

■ When someone logs into the Minecraft server, it takes up about 33% memory.
Free memory at startup: 69M = 7%
$ free -m
total used free shared buff/cache available
Mem: 967 743 69 21 154 60

■ Is it actually running out of memory?
Since the logs show the OOM killer triggering at the end, meaning out-of-memory,
It's possible that when various things run simultaneously in the middle of the night, the system actually runs out of memory.
Ubuntu apparently has 0 swap by default. Checking confirms it is indeed 0, so setting up swap might be a quick way to verify if it's a memory shortage.
——Checking memory, including swap
$ free
total used free shared buff/cache available
Mem: 991160 591828 130884 3344 268448 240460
Swap: 0 0 0

…Not swapping.

Countermeasure 1: Try enabling swap.

■ Try enabling swap.
This might be a temporary fix, but if it stops crashing, then memory was indeed lacking. If it still crashes, then something is running wild and no amount of memory will help. At that point, I'll rebuild the server.

What should the swap size be?

According to Red Hat documentation:

Physical Memory Amount and Swap Size
Physical memory 2GB or less: About 2 to 3 times the memory
2-8GB: About equal to 2 times the memory
8-64GB: About 1.5 times the memory

This sizing is apparently meant to hibernate and back up all memory to disk when sleeping. Nowadays, with massive amounts of memory, dedicating e.g. 64GB of storage just to dump 64GB of RAM takes way too long and is pointless. With memory being plentiful nowadays, is it normal not to swap or sleep at all?
Since it's a server, there's no need to hibernate as before, but maybe that's a different setting?

My EC2 Swap Size

Memory size: 1GB
Remaining storage capacity: 3GB/8GB
Since I also want to keep storage usage to a minimum, I'll set the swap size to 1GB.

Execution

The Amazon documentation explains the procedure thoroughly.
https://aws.amazon.com/premiumsupport/knowledge-center/ec2-memory-swap-file/

1. Create a 1GB swap file.
1GB = 128MB x 8. I don't know why the block size is 128M, but I'll follow the example.
$ sudo dd if=/dev/zero of=/swapfile bs=128M count=8
8+0 records in
8+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 15.2512 s, 70.4 MB/s
Takes a little bit of time.

2. Update read/write permissions for the swap file.
$ sudo chmod 600 /swapfile

3. Set up Linux swap space
$ sudo mkswap /swapfile
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=6c93a3d7-008d-49be-b566-926ac00bc892

Add the swap file to the swap space so that it can be used immediately.
$ sudo swapon /swapfile
Verify that the procedure completed successfully.
$ sudo swapon -s
Filename Type Size Used Priority
/swapfile file 1048572 2304 -2
It's already swapping.
ubuntu@ip-172-31-45-138:~$ free
total used free shared buff/cache available
Mem: 991160 609344 80148 21352 301668 202472
Swap: 1048572 2304 1046268
Edit the /etc/fstab file so the swap file enables upon startup.
Open the file in an editor.
$ sudo emacs /etc/fstab
Add the following new line to the end of the file, save, and exit.

/swapfile swap swap defaults 0 0

How is the storage capacity?
$ df /
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/root 8065444 6516508 1532552 81% /

81% used, leaving 1.5GB.
It's tight—barely enough to last a year once WordPress is running.

Investigation 2

■ Checking hang logs from other days

3/31 3:35: Same as described above. Triggered by Daily apt, eth0 dies, oom-killer activates, and bedrock_server is killed. snapd throws a SIGABRT afterwards.
Around 3/31 19:00: snapd throws a SIGABRT. Triggered by Daily apt, eth0 dies, oom-killer activates, and bedrock_server is killed.
4/2 5:40: snapd throws a SIGABRT. Triggered by Daily apt, eth0 dies, but oom-killer doesn't run.
Mostly the same pattern.

■ snapd looks suspicious. Can I stop it? How do I stop it?
What is snapd?
A package management tool similar to apt.

–Applications installable via snapd
Listing frequently used applications:

certbot
mysql
postgresql
aws-cli
Google Cloud SDK
heroku
VSCode

Did it get installed when I added MariaDB? → Probably not.
$ snap list
Name Version Rev Tracking Publisher Notes
amazon-ssm-agent 3.1.715.0 5163 latest/stable/… aws✓ classic
core18 20220309 2344 latest/stable canonical✓ base
core20 20220318 1405 latest/stable canonical✓ base
lxd 4.0.9-8e2046b 22753 4.0/stable/… canonical✓ –
snapd 2.54.4 15177 latest/stable canonical✓ snapd

Did it install when I added some Amazon tool?
Is it included by default?

■ Countermeasure 2: Stop mounting S3.

Mounting S3 is consuming more memory than expected.

1. Install the AWS CLI to manage S3 via CLI commands like mv

I used this as a reference. Since I've previously configured S3 and its access settings, this is just for installation and authentication setup. https://qiita.com/uhooi/items/e915873ddabdf6e27fd7

2. Modify the Minecraft backup script

Instead of mounting S3 and doing regular mv operations for Minecraft backups inside a standard directory,
I'll replace them with AWS CLI commands.


—–シェルスクリプトはこんな感じ-
S3にaws s3 コマンドで直接アップするための設定
BK_TIME=date +%Y%m%d-%H%M00 #aws s3でもこれを使う
S3_PATH=”s3://minecraft-xxxx/worlds_backup”
S3_PATH_NAME=”$S3_PATH/mc_backup_hourly_${BK_TIME}.tar.gz”
:
:
#ファイル名をテンポラリから日付付きの名前にして所定の場所に移動する
aws s3 mv $TMP_BK_NAME $S3_PATH_NAME #S3をマウントするとメモリを食うので、やめて、aws cliでS3に移す。
#古いのを消す
aws s3 rm $S3_PATH/mc_backup_hourly_date +%Y%m%d-%H%M00 -d ‘1 days ago’.tar.gz
———-

Check 1: First, run it directly to verify that the backup file is created in S3. However, since there is no corresponding file from the previous day yet, I can't verify the deletion of old files.
move: ./backup_worls_tmp.tar.gz to s3://minecraft-nyanpu/worlds_backup/mc_backup_hourly_20220402-174300.tar.gz
delete: s3://minecraft-nyanpu/worlds_backup/mc_backup_hourly_20220401-174300*.tar.gz

Add block
The messages indicate it went well.

Check 2: Cron time arrived, let's verify if it ran.
$ aws s3 ls s3://minecraft-xxxx/worlds_backup/
2022-02-03 19:18:16 0
2022-04-01 17:00:17 96091068 mc_backup_hourly_20220401-170000.tar.gz
2022-04-01 18:00:17 96092421 mc_backup_hourly_20220401-180000.tar.gz
2022-04-01 18:30:18 96093334 mc_backup_hourly_20220401-183000.tar.gz
2022-04-01 19:00:17 96091126 mc_backup_hourly_20220401-190000.tar.gz
2022-04-01 19:30:18 96093343 mc_backup_hourly_20220401-193000.tar.gz
2022-04-01 20:00:17 96092129 mc_backup_hourly_20220401-200000.tar.gz
2022-04-01 20:30:18 96093290 mc_backup_hourly_20220401-203000.tar.gz
2022-04-01 21:00:18 96092316 mc_backup_hourly_20220401-210000.tar.gz
2022-04-01 21:30:18 96093032 mc_backup_hourly_20220401-213000.tar.gz
2022-04-01 22:00:17 96085400 mc_backup_hourly_20220401-220000.tar.gz
2022-04-01 22:30:18 96058526 mc_backup_hourly_20220401-223000.tar.gz
2022-04-01 23:00:18 96032978 mc_backup_hourly_20220401-230000.tar.gz
2022-04-01 23:30:17 96033248 mc_backup_hourly_20220401-233000.tar.gz
2022-04-02 00:00:18 96032998 mc_backup_hourly_20220402-000000.tar.gz
2022-04-02 00:30:18 96033463 mc_backup_hourly_20220402-003000.tar.gz
2022-04-02 01:00:18 96033570 mc_backup_hourly_20220402-010000.tar.gz
2022-04-02 01:30:17 96033759 mc_backup_hourly_20220402-013000.tar.gz
2022-04-02 02:00:18 96033309 mc_backup_hourly_20220402-020000.tar.gz
2022-04-02 02:30:17 96034411 mc_backup_hourly_20220402-023000.tar.gz
2022-04-02 03:00:18 96034247 mc_backup_hourly_20220402-030000.tar.gz
2022-04-02 03:30:17 96034380 mc_backup_hourly_20220402-033000.tar.gz
2022-04-02 04:00:18 96033521 mc_backup_hourly_20220402-040000.tar.gz
2022-04-02 04:30:18 96035310 mc_backup_hourly_20220402-043000.tar.gz
2022-04-02 05:00:17 96034982 mc_backup_hourly_20220402-050000.tar.gz
2022-04-02 05:30:18 96033875 mc_backup_hourly_20220402-053000.tar.gz
2022-04-02 10:30:18 96272026 mc_backup_hourly_20220402-103000.tar.gz
2022-04-02 11:00:19 96242165 mc_backup_hourly_20220402-110000.tar.gz
2022-04-02 11:30:18 96179239 mc_backup_hourly_20220402-113000.tar.gz
2022-04-02 12:00:18 96173663 mc_backup_hourly_20220402-120000.tar.gz
2022-04-02 12:30:17 96133847 mc_backup_hourly_20220402-123000.tar.gz
2022-04-02 13:00:17 96085045 mc_backup_hourly_20220402-130000.tar.gz
2022-04-02 13:30:17 95996627 mc_backup_hourly_20220402-133000.tar.gz
2022-04-02 14:00:17 95997197 mc_backup_hourly_20220402-140000.tar.gz
2022-04-02 14:30:17 95997985 mc_backup_hourly_20220402-143000.tar.gz
2022-04-02 15:00:18 95997064 mc_backup_hourly_20220402-150000.tar.gz
2022-04-02 15:30:17 95997585 mc_backup_hourly_20220402-153000.tar.gz
2022-04-02 16:00:18 96556800 mc_backup_hourly_20220402-160000.tar.gz
2022-04-02 16:30:18 97773735 mc_backup_hourly_20220402-163000.tar.gz
2022-04-02 17:02:16 113338868 mc_backup_hourly_20220402-170000.tar.gz
2022-04-02 17:30:18 100512558 mc_backup_hourly_20220402-173000.tar.gz
2022-04-02 17:43:30 100518902 mc_backup_hourly_20220402-174300.tar.gz
2022-04-02 18:00:27 100497901 mc_backup_hourly_20220402-180000.tar.gz

New backup created successfully. ~20220402-180000.tar.gz
However, instead of deleting the file from one day prior, it wasn't deleted. ~20220401-180000.tar.gz remains.
・Check the logs again when executed directly in the shell.
delete: s3://minecraft-nyanpu/worlds_backup/mc_backup_hourly_20220401-174300.tar.gz Ah! You can't use wildcards for S3 file paths like that! I was afraid of time lags if I didn't use a wildcard. But since I always save with "%H%M00" ensuring 00 seconds, it's fine. Wait, if that's the case, the wildcard was just left hanging.
Removing the * should fix it.
Result: OK.

3. Unmount S3

Check mount name
$ mount
:
s3fs on /mnt/s3 type fuse.s3fs (rw,relatime,user_id=0,group_id=0,allow_other)

$ ps aux --sort -%mem |head -n 5
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
ubuntu 1114 11.6 22.6 1013588 224108 pts/1 Sl+ 10:10 54:15 ./bedrock_server
root 314 0.1 11.8 708240 117356 ? Ssl 10:09 0:48 s3fs minecraft-nyanpu /mnt/s3 -o rw,allow_other,use_cache=/tmp,uid=1000,gid=1000,passwd_file=/etc/passwd-s3fs,dev,suid
www-data 663 0.0 2.5 201804 25672 ? S 10:09 0:02 /usr/sbin/apache2 -k start
www-data 643 0.0 2.5 202664 25412 ? S 10:09 0:02 /usr/sbin/apache2 -k start
It was using about 11% = 110MB of memory.

- Actually unmount
$ sudo umount /mnt/s3

$ ps aux --sort -%mem |head -n 5
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
ubuntu 1114 11.6 22.6 1013588 224108 pts/1 Sl+ 10:10 54:16 ./bedrock_server
www-data 663 0.0 2.5 201804 25672 ? S 10:09 0:02 /usr/sbin/apache2 -k start
www-data 643 0.0 2.5 202664 25412 ? S 10:09 0:02 /usr/sbin/apache2 -k start
www-data 641 0.0 2.4 202588 24656 ? S 10:09 0:02 /usr/sbin/apache2 -k start
– s3fs is gone

— Memory before —
$ free
total used free shared buff/cache available
Mem: 991160 515600 168544 10520 307016 304732
Swap: 1048572 407296 641276

— Memory after —-
$ free
total used free shared buff/cache available
Mem: 991160 402604 227372 10604 361184 417644
Swap: 1048572 391680 656892
Freed up about 110MB = 11%!

■ Result: OK. It was indeed a memory shortage.

By adding a 1GB swap space and removing the non-essential S3 mount that was hogging memory, the freezes that used to happen 1-2 times a day have completely stopped. The conclusion is that it was an out-of-memory issue during the WordPress environment setup. The actual trigger was daily apt updates via snapd. This likely completely exhausted the memory, which normally sits around 40% utilization. As another countermeasure, should I stop the memory-hungry snapd? Stopping it might be dangerous since security updates won't run, right? I'll evaluate this as we go with future operations. This time it was educational and fun.

Leave a Reply