---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  labels:
    app.kubernetes.io/name: systemd-reloader
    app.kubernetes.io/version: v0.2
  name: systemd-reloader
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: systemd-reloader
  template:
    metadata:
      labels:
        app.kubernetes.io/name: systemd-reloader
        app.kubernetes.io/version: v0.2
    spec:
      containers:
        - command:
            - /usr/bin/env
            - bash
            - -c
            - |
              set -euo pipefail
              if [[ "$(id -u)" != 0 ]]; then
                printf 'This script must be run as root (uid=0), not uid=%d!\n' "$(id -u)" >&2
                exit 1
              fi
              if [[ -z "${RESET_INACTIVE_THRESHOLD:-}" ]]; then
                RESET_INACTIVE_THRESHOLD=32768
              fi

              prev=""
              while true; do
                count="$(chroot /host \
                       systemctl list-units --all | grep -wc inactive)"
                if [[ "$count" != "$prev" ]]; then
                  printf 'Number of inactive systemd units: %s (threshold=%d)\n' \
                    "$count" "$RESET_INACTIVE_THRESHOLD"
                  prev="$count"
                fi
                if [[ "$count" -lt "$RESET_INACTIVE_THRESHOLD" ]]; then
                  sleep "$CHECK_INTERVAL"
                  continue
                fi
                printf 'Resetting failed units because %d ≥ %d...\n' \
                  "$count" "$RESET_INACTIVE_THRESHOLD"
                chroot /host systemctl reset-failed
                sleep "$CHECK_INTERVAL"
              done
          image: registry.access.redhat.com/ubi8:latest
          env:
            # how often to check for inactive units
            - name: CHECK_INTERVAL
              value: 5m
            # the minimum number of inactive systemd units triggering a systemctl reset-failed
            # NOTE: systemd can keep track of up to 128k units
            - name: RESET_INACTIVE_THRESHOLD
              value: "32768"
          imagePullPolicy: Always
          name: reloader
          resources:
            requests:
              cpu: 8m
              memory: 50Mi
            limits:
              memory: 100Mi
          securityContext:
            privileged: true
            runAsUser: 0
          volumeMounts:
            - mountPath: /host
              mountPropagation: HostToContainer
              name: root
              readOnly: true
      dnsPolicy: ClusterFirst
      hostPID: true
      nodeSelector:
        kubernetes.io/os: linux
      restartPolicy: Always
      serviceAccount: systemd-reloader
      terminationGracePeriodSeconds: 30
      volumes:
        - hostPath:
            path: /
            type: ""
          name: root
  updateStrategy:
    rollingUpdate:
      maxUnavailable: 50%
    type: RollingUpdate
