The below script is used to delete the same memcache key or multiple memcache keys across multiple memcache hosts.

Assumption:

If below mentioned condition doesn’t satisfied then the script may fail or may not work. All you have to do is modify/tweak the script as per your requirement

  1. Script assumes that you have multiple memcache clusters listening on different port. Category your memcache cluster hosts on MEMCACHE_CLUSTER section.
  2. Script assumes that the machine has memcache python module installed on it. If not, you may need to install the module.
  3. Make sure that origin hosts (where the script runs) is able to connect to memcache port(default:11211) on all the machines.

#!/usr/bin/python
########Script to Delete Memcache Key########
#Author:Dhanasekaran N
#Email:support@pheonixsolutions.com

#Version:1.0
#############################################
import memcache
from fabric import *
from fabric.api import *

#Mention your Cluster hosts and unique name
_MEMCACHE_CLUSTER_ = {
“Cluster1” :[‘IPAddress1:<port>’,’IPaddress2:<port>’],
“Cluster2” :[‘IPaddress3:<port>’,’IPaddress:<port>’],
}
def _run_command(host_name,verify_key):
mc = memcache.Client([host_name], debug=0)
#run(‘pwd’);
print “key name:” + verify_key;
checked_key=mc.get(verify_key);
print  checked_key;
if(checked_key is None):
print “The key %s doesn’t exist ”  %(verify_key)
else:
print “Deleting %s from %s” %(verify_key,host_name)
mc.delete(verify_key)

def delete_memcache(delete_key=’none’,hosts_group=’none’,delete_multiple_keys=’none’):
all_groups=_MEMCACHE_CLUSTER_.keys();
#print delete_multiple_keys;
if (delete_key==’none’ and  delete_multiple_keys==’none’):
print “No delete Key or delete_multiple_key Mentioned”;
print “Eg:fab  delete_memcache:delete_key=’some_key1′,hosts_group=’java_api'”
elif(hosts_group ==’none’):
print “Mention the host Group while running fab”
print _MEMCACHE_CLUSTER_.keys();
else:
if(delete_multiple_keys!=’none’):
if(delete_multiple_keys):
delete_multiple_keys = delete_multiple_keys.split(“;”)
for cache_cluster in all_groups:
if(cache_cluster == hosts_group):
#print _MEMCACHE_CLUSTER_[cache_cluster];
for cache_cluster_hosts in _MEMCACHE_CLUSTER_[cache_cluster]:
print cache_cluster_hosts;
for delete_key in delete_multiple_keys:
execute(_run_command,hosts=cache_cluster_hosts,host_name=cache_cluster_hosts,verify_key=delete_key);
else:
for cache_cluster in all_groups:
if(cache_cluster == hosts_group):
for cache_cluster_hosts in _MEMCACHE_CLUSTER_[cache_cluster]:
print cache_cluster_hosts;
execute(_run_command,hosts=cache_cluster_hosts,host_name=cache_cluster_hosts,verify_key=delete_key);

Usage:

1. fab delete_memcache:delete_key=keyname,hosts_group=Cluster1 – >To delete a single key on the host group Cluster1

2. fab delete_memcache:delete_multiple_keys=keyname1;keyname2,hosts_group=Cluster1  -> To delete multiple keys on the host group Cluster1

Post your suggestions/queries incase if any issues.

Leave a Reply