Skip to content

Instantly share code, notes, and snippets.

@SpencerMalone
Last active April 11, 2019 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpencerMalone/6da736b50ff2413a5d0745eb608a6750 to your computer and use it in GitHub Desktop.
Save SpencerMalone/6da736b50ff2413a5d0745eb608a6750 to your computer and use it in GitHub Desktop.
Help find your worst prometheus metric sources by tokenizing metric names

./get-prom-metric-tree.py https://myprom.com 5 should dump the top 5 metric roots. When run against our prom...

{
    "kube": {
        "tree_count": 104
    }, 
    "stuff": {
        "tree_count": 14896
    }, 
    "nginx": {
        "tree_count": 14189
    }, 
    "node": {
        "tree_count": 915
    }, 
    "redis": {
        "tree_count": 75
    }
}

./get-prom-metric-tree.py https://myprom.com 5 2 would dump more context from the tree

#!/usr/bin/env python2.7
import requests
import json
import sys
import operator
numberofentries = 5
depth = 1
if len(sys.argv) > 2:
numberofentries = int(sys.argv[2])
if len(sys.argv) > 3:
depth = int(sys.argv[3])
if len(sys.argv) > 4 or len(sys.argv) < 2:
print("Usage: <" + sys.argv[0] + "> <Prom URL> <number of worst results to return (def: 5)> <depth (def: 1)>")
sys.exit(1)
URL = sys.argv[1] + "/api/v1/label/__name__/values"
r = requests.get(url = URL)
data = r.json()
def limitdictsize(d, n=1):
if n > depth:
if "tree_count" not in d:
return d
else:
return {'tree_count': d["tree_count"]}
for k, v in d.iteritems():
if isinstance(v, dict):
d[k] = limitdictsize(v, n + 1)
return d
tree = {}
bigtree = {}
for metric_name in data['data']:
current_level = tree
path = metric_name.split("_")
old_path = ""
cur_depth = 0
for part in path:
if "tree_count" not in current_level:
current_level["tree_count"] = 0
if part not in current_level:
current_level[part] = {}
current_level["tree_count"] = current_level["tree_count"] + 1;
old_path = part
current_level = current_level[part]
cur_depth = cur_depth + 1
for metric_part in tree:
current_level = metric_part
bigtree = dict(sorted(tree.iteritems(), key=lambda t: t[1], reverse=True)[:numberofentries])
bigtree = limitdictsize(bigtree)
print(json.dumps(bigtree, indent=4, sort_keys=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment