Skip to content

Instantly share code, notes, and snippets.

@hhue13
Last active July 26, 2024 10:18
Show Gist options
  • Save hhue13/c245bee0e6df2739a69469f0fe0bdc7a to your computer and use it in GitHub Desktop.
Save hhue13/c245bee0e6df2739a69469f0fe0bdc7a to your computer and use it in GitHub Desktop.
Collect OCP logs all pods in a namespace and some pod information
#!/bin/env bash
#########################################################################################################################
## Tail all logs of all pods in a namespace to a directory
##
## Parameters: <ns> --> Namespace which pods are logged
## <outDir> --> targetDirectory for the logoutput. Defaults to /tmp
#########################################################################################################################
set -o pipefail
NS=${1?"missing arg 1 for Namespace"}
OUTDIR=${2:-/tmp}
__check ()
{
##
## Are we logged in?
echo "Running on cluster: $(oc whoami --show-server)"
__token=$(oc whoami -t)
if [ -z "${__token}" ] ; then
echo "ERROR: No login token found. Please login first ..."
exit 1
fi
##
## Can we get pods?
oc -n ${NS} get pods 2>&1 > /dev/null
__rc=$?
if [[ ${__rc} != 0 ]] ; then
echo "ERROR: Can't get pods. Either the token is expired or you are lacking permissions to get pod information ..."
exit 1
fi
##
## DO we have pods at all
__numPods=$(oc -n ${NS} get pods -o custom-columns=NAME:.metadata.name | tail -n +2 | wc -l)
__rc=$?
if [[ ${__numPods} == 0 ]] ; then
echo "ERROR: No pods in namespace \"${NS}\". Either the namespace is incorrect or there are no pods to monitor ..."
exit 1
fi
##
## Looks like we get pod information
mkdir -p ${OUTDIR} || {
echo "ERROR: Failed to create output directory \"${OUTDIR}\" ..."
exit 1
}
##
## Do we have write permissions to $OUTDIR
if [[ ! -w ${OUTDIR} ]] ; then
echo "ERROR: Can't write to directory \"${OUTDIR}\" ..."
exit 1
fi
}
##
## Perform some checks
__check
__currentTime=$(date +"%Y%m%d_%H%M%S")
##
## Process list of pods
oc -n ${NS} get pods -o custom-columns=NAME:.metadata.name | tail -n +2 | while read line ; do
echo "INFO: Processing pod \"${line}\" ..."
oc -n ${NS} describe pod ${line} 2>&1 > ${OUTDIR}/${line}_${__currentTime}.describe
oc -n ${NS} get pod ${line} -o yaml 2>&1 > ${OUTDIR}/${line}_${__currentTime}.yaml
oc -n ${NS} logs ${line} --follow=true --all-containers=true --timestamps=true --ignore-errors=true 2>&1 > ${OUTDIR}/${line}_${__currentTime}.log &
done
echo "Started capture of POD logs to directory ${OUTDIR} ..."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment