Skip to content

Instantly share code, notes, and snippets.

@BR0kEN-
Last active July 14, 2017 09:39
Show Gist options
  • Save BR0kEN-/d7a60f84b33f55aaf66037ebf73bdc2f to your computer and use it in GitHub Desktop.
Save BR0kEN-/d7a60f84b33f55aaf66037ebf73bdc2f to your computer and use it in GitHub Desktop.
Flush Memcache or only prefixed entries from a command line
#!/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
}
@BR0kEN-
Copy link
Author

BR0kEN- commented Jul 13, 2017

Useful Drupal-related usage:

# Do not use "drush vget" because it's bootstrap Drupal which may lead to
# facing a fatal error which we trying to avoid by clearing the Memcache.
# Also, "drsuh vset" may contain warnings/errors in "stdout" and in this
# case prefix will not be correct.
memcache_clear_by_prefix "$(\drush sql-connect | \awk -F '--database=' '{print $2}' | \awk '{print $1}')"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment