#!/bin/sh

cluster_node_labels=${CLUSTER_NODE_LABELS:-/var/lib/tuned/ocp-node-labels.cfg}
cluster_pod_labels=${CLUSTER_POD_LABELS:-/var/lib/tuned/ocp-pod-labels.cfg}
openshift_tuned_socket=/var/lib/tuned/openshift-tuned.sock
export SYSTEMD_IGNORE_CHROOT=1

start() {
  systemctl disable tuned --now || :

  # Tuned can take ~20s to reload/start when "ulimit -Sn == 1048576".
  # See:
  # - https://github.com/redhat-performance/tuned/issues/146
  # - https://www.python.org/dev/peps/pep-0446/#closing-all-open-file-descriptors
  # - http://bugs.python.org/issue1663329
  ulimit -Sn 1024	# workaround for the issue above

  openshift-tuned \
    -v=1 \
    -node-labels $cluster_node_labels \
    -pod-labels $cluster_pod_labels \
    -watch-file /etc/tuned/recommend.d/ \
    -watch-file /var/lib/tuned/profiles-data/ \
    ${OCP_NODE_NAME}
}

stop() {
  local timeout=10	# wait $timeout [s] for a reply via the socket
  local response=$(echo stop | socat -t$timeout - UNIX-CONNECT:$openshift_tuned_socket 2>/dev/null)

  if [ "$response" != "ok" ]; then
    # provide a failure message in the event log
    echo "openshift-tuned stop response: $response" 1>&2
    return 1
  fi
}

$@
