Skip to content

Instantly share code, notes, and snippets.

@ARezaK
Created April 29, 2024 00:40
Show Gist options
  • Save ARezaK/f65f4845fef587f6d0d085aebdfb570c to your computer and use it in GitHub Desktop.
Save ARezaK/f65f4845fef587f6d0d085aebdfb570c to your computer and use it in GitHub Desktop.
Send Memcache stats to Slack url
#!/bin/bash
# run with cron 0 17 * * *
# Run the command and capture the output
output=$(echo "stats" | nc -q 1 localhost 11211)
# Parse the output for desired stats
bytes=$(echo "$output" | grep "STAT bytes " | awk '{print $3/1024/1024}')
limit_maxbytes=$(echo "$output" | grep "STAT limit_maxbytes " | awk '{print $3/1024/1024}')
curr_connections=$(echo "$output" | grep "STAT curr_connections " | awk '{print $3}')
max_connections=$(echo "$output" | grep "STAT max_connections " | awk '{print $3}')
listen_disabled_num=$(echo "$output" | grep "STAT listen_disabled_num " | awk '{print $3}')
cmd_flush=$(echo "$output" | grep "STAT cmd_flush " | awk '{print $3}')
get_hits=$(echo "$output" | grep "STAT get_hits " | awk '{print $3}')
get_misses=$(echo "$output" | grep "STAT get_misses " | awk '{print $3}')
# Calculate percentages using bc for floating point support
percentage_of_limit=$(echo "$bytes $limit_maxbytes" | awk '{printf "%.2f", $1 / $2 * 100}')
connections_percentage=$(echo "$curr_connections $max_connections" | awk '{printf "%.2f", $1 / $2 * 100}')
global_hitrate=$(echo "$get_hits $get_misses" | awk '{printf "%.2f", $1 / ($1 + $2) * 100}')
# Create the message body
message="Memcached Stats:
Bytes: $bytes MB
Max Limit of Bytes: $limit_maxbytes MB
Percentage of Max Limit: $percentage_of_limit%
Current Connections: $connections_percentage% of Max Connections
Listen Disabled Number: $listen_disabled_num
Flush Commands Issued: $cmd_flush
Global Hitrate: $global_hitrate"
echo -e $message
# Use jq to encode the message as JSON
json_payload=$(jq -n --arg msg "$message" '{text: $msg}')
curl -X POST -H 'Content-type: application/json' --data "$json_payload" slack_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment