migrate_redis.py
· 1.4 KiB · Python
Surowy
#!/usr/bin/env python
import argparse
import redis
def connect_redis(conn_dict):
conn = redis.StrictRedis(host=conn_dict['host'],
port=conn_dict['port'],
db=conn_dict['db'])
return conn
def conn_string_type(string):
format = '<host>:<port>/<db>'
try:
host, portdb = string.split(':')
port, db = portdb.split('/')
db = int(db)
except ValueError:
raise argparse.ArgumentTypeError('incorrect format, should be: %s' % format)
return {'host': host,
'port': port,
'db': db}
def migrate_redis(source, destination):
src = connect_redis(source)
dst = connect_redis(destination)
for key in src.keys('*'):
ttl = src.ttl(key)
# we handle TTL command returning -1 (no expire) or -2 (no key)
if ttl < 0:
ttl = 0
print "Dumping key: %s" % key
value = src.dump(key)
print "Restoring key: %s" % key
try:
dst.restore(key, ttl * 1000, value)
except:
pass
return
def run():
parser = argparse.ArgumentParser()
parser.add_argument('source', type=conn_string_type)
parser.add_argument('destination', type=conn_string_type)
options = parser.parse_args()
migrate_redis(options.source, options.destination)
if __name__ == '__main__':
run()
| 1 | #!/usr/bin/env python |
| 2 | import argparse |
| 3 | import redis |
| 4 | |
| 5 | |
| 6 | def connect_redis(conn_dict): |
| 7 | conn = redis.StrictRedis(host=conn_dict['host'], |
| 8 | port=conn_dict['port'], |
| 9 | db=conn_dict['db']) |
| 10 | return conn |
| 11 | |
| 12 | |
| 13 | def conn_string_type(string): |
| 14 | format = '<host>:<port>/<db>' |
| 15 | try: |
| 16 | host, portdb = string.split(':') |
| 17 | port, db = portdb.split('/') |
| 18 | db = int(db) |
| 19 | except ValueError: |
| 20 | raise argparse.ArgumentTypeError('incorrect format, should be: %s' % format) |
| 21 | return {'host': host, |
| 22 | 'port': port, |
| 23 | 'db': db} |
| 24 | |
| 25 | |
| 26 | def migrate_redis(source, destination): |
| 27 | src = connect_redis(source) |
| 28 | dst = connect_redis(destination) |
| 29 | for key in src.keys('*'): |
| 30 | ttl = src.ttl(key) |
| 31 | # we handle TTL command returning -1 (no expire) or -2 (no key) |
| 32 | if ttl < 0: |
| 33 | ttl = 0 |
| 34 | print "Dumping key: %s" % key |
| 35 | value = src.dump(key) |
| 36 | print "Restoring key: %s" % key |
| 37 | try: |
| 38 | dst.restore(key, ttl * 1000, value) |
| 39 | except: |
| 40 | pass |
| 41 | return |
| 42 | |
| 43 | |
| 44 | def run(): |
| 45 | parser = argparse.ArgumentParser() |
| 46 | parser.add_argument('source', type=conn_string_type) |
| 47 | parser.add_argument('destination', type=conn_string_type) |
| 48 | options = parser.parse_args() |
| 49 | migrate_redis(options.source, options.destination) |
| 50 | |
| 51 | if __name__ == '__main__': |
| 52 | run() |