Skip to content

Instantly share code, notes, and snippets.

@uablrek
Last active September 12, 2023 08:31
Show Gist options
  • Save uablrek/849b87a8a88e19d1cd3a304922e2ece0 to your computer and use it in GitHub Desktop.
Save uablrek/849b87a8a88e19d1cd3a304922e2ece0 to your computer and use it in GitHub Desktop.
K8s - core dumps from containers

k8s-coredump

Specify a core pattern on the host:

echo "/var/log/dumps/core.%h.%e.%P" > /proc/sys/kernel/core_pattern

This is global and will be seen inside containers.

Create a binary that causes a core-dump:

// gcc -g -Wall -static -o segv segv.c        # 881K
// musl-gcc -g -Wall -static -o segv segv.c   # 20K
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
        int delay = 30;
        if (argc > 1)
                delay = atoi(argv[1]);
        sleep((unsigned int)delay);
        *((unsigned int*)0) = 55;               /* Causes a SEGV */
        for (;;)
                sleep((unsigned int)delay);
}

Compile it and create an image:

docker build -f /path/to/Dockerfile -t docker.io/uablrek/segv:latest .
Dockerfile
FROM alpine:latest
COPY /segv /bin
CMD ["/bin/sh", "-c", "ulimit -c unlimited; exec /bin/segv"]

Mount the directory in the container:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: segv
spec:
  selector:
    matchLabels:
      app: segv
  replicas: 2
  template:
    metadata:
      labels:
        app: segv
    spec:
      containers:
      - name: segv
        image: docker.io/uablrek/segv:latest
        imagePullPolicy: IfNotPresent
        volumeMounts:
        - mountPath: /var/log/dumps
          name: dump-dir
      volumes:
      - name: dump-dir
        hostPath:
          path: /var/log/dumps
          type: Directory

The PODs will segv after 30s and create a core-dump on the host fs:

# ls /var/log/dumps/
core.segv-6c67bb595d-9fsqc.segv.661
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment