Skip to content

Instantly share code, notes, and snippets.

@dsoprea
Last active September 13, 2024 18:13
Show Gist options
  • Save dsoprea/48b1b943f5715576533fe9c9719afba1 to your computer and use it in GitHub Desktop.
Save dsoprea/48b1b943f5715576533fe9c9719afba1 to your computer and use it in GitHub Desktop.
Browse and cleanup a Redis DB. Group and browse like-prefixed keys, and optionally remove.
#!/usr/bin/env python3
"""
Copyright 2024 Dustin Oprea
MIT LICENSE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# Requirements:
# redis
# tqdm
import argparse
import fnmatch
import tqdm
import redis
_DESCRIPTION = "Enumerate and group key prefixes. Can remove matches keys."
_ENCODING = 'utf-8'
def _get_args():
parser = \
argparse.ArgumentParser(
description=_DESCRIPTION)
parser.add_argument(
'redis_uri',
help="Redis URI")
parser.add_argument(
'n',
type=int,
help="Group by this number of key-prefix parts. If all yielded groups have only one member (no actual grouping; they're all leaves) this should equal the number of total dotted parts.")
parser.add_argument(
'--include',
dest='includes',
action='append',
default=[],
help="Prefix include pattern. Can be provided zero or more times.")
parser.add_argument(
'--exclude',
dest='excludes',
action='append',
default=[],
help="Prefix exclude pattern. Can be provided zero or more times.")
parser.add_argument(
'--remove',
dest='do_remove',
action='store_true',
help="Remove matching records")
args = parser.parse_args()
return args
def _yield_prefix_phrases_gen(keys, n):
for key in keys:
parts = key.split('.')
prefix = tuple(parts[:n])
prefix_phrase = '.'.join(prefix)
yield prefix_phrase, key
def _apply_includes_gen(prefix_phrases, includes):
for prefix_phrase, key in prefix_phrases:
for include_pattern in includes:
if fnmatch.fnmatch(prefix_phrase, include_pattern) is True:
yield prefix_phrase, key
break
def _apply_excludes_gen(prefix_phrases, excludes):
for prefix_phrase, key in prefix_phrases:
hit = False
for exclude_pattern in excludes:
if fnmatch.fnmatch(prefix_phrase, exclude_pattern) is True:
hit = True
break
if hit is False:
yield prefix_phrase, key
def _main():
args = _get_args()
client = redis.Redis.from_url(args.redis_uri)
pattern = '*'
keys = client.scan_iter(pattern)
grouped = {}
keys = (
key.decode(_ENCODING)
for key
in keys
)
prefix_phrases = _yield_prefix_phrases_gen(keys, args.n)
if args.includes:
prefix_phrases = _apply_includes_gen(prefix_phrases, args.includes)
if args.excludes:
prefix_phrases = _apply_excludes_gen(prefix_phrases, args.excludes)
if args.do_remove is True:
keys = [
key
for prefix_phrase, key
in prefix_phrases
]
for key in tqdm.tqdm(keys):
client.delete(key)
print('')
print("({}) keys deleted.".format(len(keys)))
else:
for prefix_phrase, key in prefix_phrases:
try:
grouped[prefix_phrase] += 1
except KeyError:
grouped[prefix_phrase] = 1
for prefix_phrase, count in sorted(grouped.items()):
print("{} ({})".format(prefix_phrase, count))
print('')
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment