List Memcache Keys and Expiration Dates

Posted by Tully on Fri 12 December 2014

Find out what keys are currently residing in Memcache and when those keys will expire.

The below BASH script will output this information in the format Key: KEY Expires: DATE. The output isn't all that pretty but you can easily fix that with the column utility.

Column is a program which takes input from STDIN and formats it into multiple columns. I use the -t flag below to return the output into a nicely formatted table.

How to run the script

bash memcache-stats.sh 2>&1 | column -t

Code

#!/bin/bash
#
# Purpose: 
#   Retrieve all keys in memcache and display
#   the date there going to expire.
#

MEMCACHE_IP='127.0.0.1'
MEMCACHE_PORT='11211'
MAX_CACHEDUMP_ROWS=1000

# Get unique slab identifiers
SLAB_IDS=$(echo "stats items"   
    | nc $MEMCACHE_IP $MEMCACHE_PORT   
    | grep items:   
    | awk -F: '{print $2}'   
    | uniq)

for ID in $SLAB_IDS
do
    echo "stats cachedump $ID $MAX_CACHEDUMP_ROWS"   
    | nc $MEMCACHE_IP $MEMCACHE_PORT   
    | awk '{print $2,$5}'   
    | sort -k2n   
    | while read key time
    do
        [[ -z "$key" ]] && continue
        echo "Key: $key Expires: $(date -d @$time)"
    done
done