My server falls apart when I get home (and AppArmor wouldn't let Postgres hang up)

Share
My server falls apart when I get home (and AppArmor wouldn't let Postgres hang up)
Bears are not family friendly, they hang up the elephant family reunion

For a few days now my home server has this nice habit: it works perfectly all day, and then it falls apart exactly when I get home. Pods restarting, Grafana timing out, the Matrix bot screaming at me about things being down (except if Uptime Kuma goes down first, it's nice and quite at least). Very rude.

My first suspect was Nextcloud. My phone is set to upload photos when I'm on wifi, and I arrive on wifi, so the timing fits. Well. Turns out the story was a bit longer than that.

The boring part: it's RAM (it's always the RAM)

The box is an N100 mini PC with 8 GB of RAM, bought three years ago, seems like it's getting old and starting to have memory issues, like me. During the "falling apart" the memory was at ~94%, load average was 15 on a 4 core machine, and half the processes were waiting for disk. Even the k3s API server was starving, so coredns and cert-manager were restarting just because they couldn't talk to it.

First look, nothing fancy:

free -h
vmstat 1 5                      # high "wa" = waiting for disk, "si/so" = swapping
ps -eo stat,pid,wchan:20,cmd | awk '$1 ~ /^D/'    # who is stuck waiting for I/O
sudo k3s crictl stats           # memory per container

The biggest guy was Frigate with ~3.5 GB, almost half of the RAM, mostly because I run a medium YOLOv9 detector on four cameras. It also renders a birdseye view by default, a nice mosaic of all cameras that nobody ever looks at. I turned that off:

birdseye:
  enabled: False

My plan was "just buy more RAM". I was a bit scared to open the machine, so I never did. Then my rubber duck suggested to use dmidecode and it told me the memory type is "Row Of Chips". It's soldered LPDDR5, there won't be any chips to be swapped.

sudo dmidecode -t memory | grep -E 'Type:|Form Factor|Size'

(Side note: my rubber duck also told me to disable the desktop environment to save memory. There was no desktop environment running. Good catch, duck.)

While I was at it, I also did some spring cleaning, because it's winter. The disk was full of stuff nobody needs:

sudo k3s crictl rmi --prune                 # remove unused container images

Then Nextcloud decided to upgrade itself

While I was playing with Frigate's restart, Nextcloud pod went to Running but gave me Bad Gateway. My image tag was latest, so on restart it pulled a newer version and started upgrading 35.0.2.2 → 35.0.3.2. Apparently latest is not a deployment strategy, who knew.

Also, Running doesn't mean ready. I had no readiness probe, so Kubernetes was happily telling me everything is fine while Apache returned errors.

The first things I always check:

kubectl -n nextcloud get pods
kubectl -n nextcloud logs deploy/nextcloud --tail=50
kubectl -n nextcloud get endpoints          # empty = nobody is behind the Service
kubectl -n nextcloud exec deploy/nextcloud -- su -s /bin/sh www-data -c "php /var/www/html/occ status"

The official image does an rsync of the files and then runs occ upgrade. The rsync got stuck at the very end. Same file descriptors, same state, hours later. A quick way to see if a process is really working or just sitting there:

ls -l /proc/<PID>/fd            # same files open every time you look?
sudo strace -p <PID>            # stuck in the same syscall = stuck

I killed it. The next start only said this:

Another process is initializing Nextcloud. Waiting...

A lock file from the killed run. OK, removed that. Then occ upgrade itself hung on "Update app memories from App Store". Nope.

Wrong theories (again, there were a few)

I blamed the network first, because the App Store step was the one hanging. Funny thing: ss on the host showed nothing, because the pod has its own network namespace. You have to jump in:

sudo nsenter -t <PID> -n ss -tnp

So the network was fine, the App Store was reachable. Then I looked at the database and found a pile of sessions that were stuck forever, from the old Nextcloud processes:

kubectl -n nextcloud exec deploy/postgres -- psql -U oc_admin -d nextcloud -c \
  "SELECT pid, state, wait_event_type, wait_event, now()-state_change AS age, left(query,60) AS query
   FROM pg_stat_activity WHERE datname='nextcloud' ORDER BY age DESC;"

Fine, I'll just kill them:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname='nextcloud' AND pid <> pg_backend_pid();

and the answer was:

pg_terminate_backend ... Permission denied

As the database owner. On my own database. Okaaay.

Then I restarted Postgres (scale to 0, then to 1, if you didn't set the Recreate strategy, because rollout restart on a database is how you get two Postgres on the same data dir), and it went into a recovery loop:

could not signal for checkpoint: Permission denied

A process that is not allowed to send a signal to its own children. That is not a Postgres problem, that is someone else's problem.

The actual culprit: AppArmor

dmesg had a couple of hundred lines like this, all apparmor="DENIED", operation signal, from the postgres container:

sudo dmesg -T | grep -i 'apparmor="DENIED"' | tail
sudo dmesg | grep 'apparmor="DENIED"' | grep -o 'profile="[^"]*"' | sort | uniq -c | sort -rn

This is my best understanding, so don't quote me: containerd gives the pod a default AppArmor profile, and my readiness probe (pg_isready through exec) creates a stacked profile that denies signal. Postgres 16 uses signals to wake up its backends, so sessions could not be woken up or terminated, and they just piled up. And I guess every hung session also kept a PHP worker waiting, which could explain why the whole server felt dead when the photo upload started. I'm not 100% sure about that last part, I'll watch it for some evenings.

The fix was this in the Postgres pod spec:

securityContext:
  runAsUser: 70
  runAsGroup: 70
  appArmorProfile:
    type: Unconfined

Applied it, Postgres started clean, the upgrade finished ("Update successful", I almost cried), and Nextcloud worked again.

Before I touched the database I made a pg_dump (21 MB, so tiny). It saved me no trouble this time, but I slept better:

kubectl -n nextcloud exec deploy/postgres -- pg_dump -U oc_admin nextcloud | gzip > ~/nc-pre-upgrade.sql.gz

After the upgrade, don't forget to turn off the maintenance mode, I had to do it twice:

kubectl -n nextcloud exec deploy/nextcloud -- su -s /bin/sh www-data -c "php /var/www/html/occ maintenance:mode --off"

Still not perfect

Nextcloud still complains about a missing table (oc_federated_invites) and an unexpected index. Both look cosmetic, and occ db:schema:check -v only talks properly when maintenance mode is off. I will deal with them later, probably when they ruin another weekend.

Making sure it doesn't happen again

Pin the image, add a readiness probe, and put a memory limit on the hungry ones:

image: nextcloud:35-apache        # not "latest"
readinessProbe:
  httpGet:
    path: /status.php
    port: 80
  periodSeconds: 10
  failureThreshold: 6
kubectl -n nextcloud set resources deploy/nextcloud --requests=memory=512Mi --limits=memory=1536Mi

Lessons (that I will totally forget)

  1. Pin your image tags. nextcloud:35-apache, not latest.
  2. Back up the database before any upgrade. Takes one minute.
  3. "Permission denied" for the owner means look at dmesg. AppArmor and friends do not write to your app log.
  4. Check dmidecode before you plan a RAM upgrade.
  5. Set memory limits. Frigate should not eat half of the machine just because it can.
  6. Never trust an rsync that looks "progressing" at night. In the morning it was the same. Sleep is also a debugging tool.

So, did I fix the "falls apart when I get home" problem? Ask me again next week.