Skip to content

Instantly share code, notes, and snippets.

@adiii717
Forked from smola/k8s-jprofiler-attach.sh
Last active August 31, 2021 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adiii717/867549d1a949186e246c9a60212d075e to your computer and use it in GitHub Desktop.
Save adiii717/867549d1a949186e246c9a60212d075e to your computer and use it in GitHub Desktop.
Attach JProfiler agent to a JVM running in a Kubernetes pod
#!/bin/bash
set -ex
usage()
{
echo "usage: k8s-jprofiler-attach.sh pod_name"
}
k8s_jvm_pod="${1}"
if [[ -z $k8s_jvm_pod ]]; then
echo "Pod name not defined"
usage
exit 1
fi
EXEC="kubectl exec $k8s_jvm_pod"
CP="kubectl cp $k8s_jvm_pod"
PORT_FORWARD="kubectl port-forward $k8s_jvm_pod"
JPROFILER_PACKAGE="jprofiler_linux_12_0_3.tar.gz"
if [[ ! -f ${JPROFILER_PACKAGE} ]]; then
wget https://download-gcdn.ej-technologies.com/jprofiler/jprofiler_linux_12_0_3.tar.gz -O jprofiler_linux_12_0_3.tar.gz
fi
if ! ${EXEC} -- find /root/${JPROFILER_PACKAGE} &>/dev/null; then
echo "${JPROFILER_PACKAGE} not found on the server, copying..."
kubectl cp "${JPROFILER_PACKAGE}" "$k8s_jvm_pod:/root/${JPROFILER_PACKAGE}"
else
echo "${JPROFILER_PACKAGE} already found in the server"
fi
JPROFILER_PORT=31757
K8S_JVM_PID="$(${EXEC} -- /bin/ps -ef | grep "java" | grep -v "grep" | awk '{print $2}')"
if [[ -z ${K8S_JVM_PID} ]]; then
echo "K8S_JVM_PID not defined, pick one:"
${EXEC} jps 2>/dev/null
exit 1
fi
${EXEC} -- tar -C /root -xf "/root/${JPROFILER_PACKAGE}"
${EXEC} -- /root/jprofiler12.0.3/bin/jpenable --pid=${K8S_JVM_PID} --port=${JPROFILER_PORT} --noinput --gui
${PORT_FORWARD} ${JPROFILER_PORT}
@adiii717
Copy link
Author

Run and Installation

curl -s https://gist.githubusercontent.com/Adiii717/867549d1a949186e246c9a60212d075e/raw/1a754eff5cae3a8d603b22d47cc6a9cf99c7c699/k8s-jprofiler-attach.sh -o k8s-jprofiler-attach.sh
chmod +x k8s-jprofiler-attach.sh
k8s-jprofiler-attach.sh pod_id

@CsBigDataHub
Copy link

hey @adiii717,

I have been getting this error, have you come across this?

image

a springboot app is running on PID 8

@adiii717
Copy link
Author

@CsBigDataHub so seems like the JVM is running against another user, or might be the PID is different.

Better to try kubectl exec -it POD_NAME -- bash
then check the user who runs the spring-boot app

ps -u $USER
or 
ps -aux

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment