Ana içeriğe geç

Periodic Monitoring of Instant Thread Counts of Pods

vi Thread_Count.sh
#!/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."
sudo chmod +x Thread_Count.sh

If you want to use it manually, you can run it with the following command.

./Thread_Count.sh <Namespace1> <Namespace2> <Namespace3>

If you wish, you can ensure the script runs at a specific time or time period. Cron can be used for this.

sudo crontab -e

Add the line below to the opened file. In example usage, the script will run every 5 minutes.

*/5 * * * * /path/Thread_Count.sh namespace1 namespace2 namespace3