Last active
July 14, 2017 09:39
-
-
Save BR0kEN-/d7a60f84b33f55aaf66037ebf73bdc2f to your computer and use it in GitHub Desktop.
Flush Memcache or only prefixed entries from a command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
MEMCACHE_PID=$(\pgrep -f memcache) | |
MEMCACHE_HOST="127.0.0.1" | |
MEMCACHE_PORT="11211" | |
if [ -n "${MEMCACHE_PID}" ]; then | |
# @todo Do we have an ability to use passwordless "sudo"? | |
DATA=$(\sudo \netstat -plunt | \grep "${MEMCACHE_PID}" | \awk '{print $4}' | \head -n1) | |
if [ -n "${DATA}" ]; then | |
MEMCACHE_HOST="${DATA%%:*}" | |
MEMCACHE_PORT="${DATA##*:}" | |
fi | |
fi | |
memcache_command() | |
{ | |
\echo -e "$1\nquit\n" | \nc -q2 "${MEMCACHE_HOST}" "${MEMCACHE_PORT}" | |
} | |
memcache_clear() | |
{ | |
\echo "[INFO] Clearing Memcache at ${MEMCACHE_HOST}:${MEMCACHE_PORT}..." | |
memcache_command "flush_all" | |
} | |
memcache_clear_by_prefix() | |
{ | |
if [ -n "$1" ]; then | |
local PREFIX="$1" | |
local COUNTER=0 | |
\echo "[INFO] Clearing Memcache entries prefixed by the \"${PREFIX}\" at ${MEMCACHE_HOST}:${MEMCACHE_PORT}..." | |
for SLAB_ID in $(\seq 1 $(memcache_command "stats items" | \tail -n2 | \head -n1 | \awk -F ':' '{print $2}')); do | |
for KEY in $(memcache_command "stats cachedump ${SLAB_ID} 0" | \awk '{print $2}'); do | |
if [[ -n "${KEY}" && "${KEY}" =~ ^${PREFIX} ]]; then | |
memcache_command "delete ${KEY}"> /dev/null 2>&1 | |
((COUNTER++)) | |
fi | |
done | |
done | |
\echo "[INFO] ${COUNTER} entries removed." | |
else | |
\echo "[WARN] Memcache key prefix is not set so nothing was cleared." | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useful Drupal-related usage: