#!/bin/bash
OUTPUT_FILE="threadCount"
# It continues every 10 seconds for a total of 5 minutes.
INTERVAL=10
DURATION=300
END_TIME=$((SECONDS + DURATION))
# Clear or create previous file
echo "" > $OUTPUT_FILE
# Start loop for each namespace
while [ $SECONDS -lt $END_TIME ]; do
for NAMESPACE in "${@}"; do
echo "Processing namespace: $NAMESPACE at $(date)" >> $OUTPUT_FILE
# List all pods in namespace
pods=$(kubectl get pods -n $NAMESPACE -o jsonpath='{.items[*].metadata.name}')
# Start loop for each pod
for pod in $pods; do
echo " Processing pod: $pod" >> $OUTPUT_FILE
# Get the number of threads in the pod
thread_count=$(kubectl exec -n $NAMESPACE $pod -- ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END { print num_threads }' 2>/dev/null)
# If thread count is not available, mark it as 'N/A'
if [ -z "$thread_count" ]; then
thread_count="N/A"
fi
# Write results to file
echo "$NAMESPACE/$pod: $thread_count" >> $OUTPUT_FILE
done
done
# Wait for INTERVAL time
sleep $INTERVAL
done
echo "Thread counts have been written to $OUTPUT_FILE."
CODE
sudo chmod +x Thread_Count.sh
CODE
If you want to use it manually, you can run it with the command below.
./Thread_Count.sh <Namespace1> <Namespace2> <Namespace3>
CODE
If you wish, you can have the script run at a specific time or time period. Cron can be used for this.
Add the following line to the opened file.In the example usage, the script will run every 5 minutes.
*/5 * * * * /path/to/Thread_Count.sh namespace1 namespace2 namespace3
CODE