#!/bin/bash
# Downloads the audit.log (and its rotated copies) from
# /var/logs/{kube-apiserver,openshift-apiserver} on each
# master node.
BASE_COLLECTION_PATH="${BASE_COLLECTION_PATH:-/must-gather}"

profile=$(oc get apiservers.v1.config.openshift.io -o jsonpath=.spec.audit.profile)
if [ -z "${profile}" ] || [ "${profile}" == None ]; then
  if [ "${1}" == "--force" ]; then
    cat <<EOF
WARNING: To raise a Red Hat support request, it is required to set the top level audit policy to
         Default, WriteRequestBodies, or AllRequestBodies to generate audit log events that can
         be analyzed by support. Try `oc edit apiservers` and set `spec.audit.profile` back to
         Default" and reproduce the issue while gathering audit logs.
EOF
  else
    cat <<EOF
ERROR: To raise a Red Hat support request, it is required to set the top level audit policy to
       Default, WriteRequestBodies, or AllRequestBodies to generate audit log events that can
       be analyzed by support. Try `oc edit apiservers` and set `spec.audit.profile` back to
       "Default" and reproduce the issue while gathering audit logs. You can use "--force" to
       override this error.
EOF
    exit 1
  fi
fi

echo "WARNING: Collecting one or more audit logs on ALL masters in your cluster. This could take a large amount of time." >&2

# the command executed by xargs below expects four parameters:
# $1 - node path under /var/logs to download
# $2 - local output path
# $3 - node name
# $4 - log file name
paths=(openshift-apiserver kube-apiserver oauth-apiserver etcd)
for path in "${paths[@]}" ; do
  output_dir="${BASE_COLLECTION_PATH}/audit_logs/$path"
  mkdir -p "$output_dir"
  oc adm node-logs --role=master --path="$path" | \
  tee "${BASE_COLLECTION_PATH}/audit_logs/$path.audit_logs_listing" | \
  grep -v ".terminating" | \
  grep -v ".lock" | \
  sed "s|^|$path $output_dir |"
done | \
xargs --max-args=4 --max-procs=45 bash -c \
  'echo "INFO: Started  downloading $1/$4 from $3";
  oc adm node-logs $3 --path=$1/$4 | gzip > $2/$3-$4.gz;
  echo "INFO: Finished downloading $1/$4 from $3"' \
  bash
echo "INFO: Audit logs collected."

# force disk flush to ensure that all data gathered is accessible in the copy container
sync
