Search code examples
kubernetescroncontainers

How to terminate a pod based on the amount of PIDs in a container?


Setup: Multi-server K8s cluster

I want to terminate a container/pod when the number of PIDs running in the container from a specific user is below a certain count. For example: If "user" has less than 15 PIDs running in the container, I want the container and pod to terminate so that it spins up a new copy. Ideally I would have a cronjob run in the cluster that queries the number of PIDs that user has running, and if it is below 15, terminate the pod. I don't know how to query the PIDs running inside a container from the outside. Any ideas that might work?


Solution

  • Did you mean you need a pod restart?

    You can try this with livenessProbe as described here: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/

    Example:

    apiVersion: v1
    kind: Pod
    metadata:
      labels:
        test: liveness
      name: liveness-exec
    spec:
      containers:
      - name: liveness
        image: k8s.gcr.io/busybox
        args:
        - /bin/sh
        - -c
        - touch /tmp/healthy; sleep 30; rm -f /tmp/healthy; sleep 600
        livenessProbe:
          exec:
            command:
            - cat
            - /tmp/healthy
          initialDelaySeconds: 5
          periodSeconds: 5
    

    You can implement your logic in command for counting processes