docker-stats-histo/display/render.py

92 lines
2.6 KiB
Python
Raw Normal View History

2021-02-13 19:15:17 +00:00
import argparse
import json
from datetime import datetime
import pygal
PNG_OUTPUT = 'mem_usage.png'
def parse_args():
parser = argparse.ArgumentParser(
description=("Render for docker stats memory usage")
)
parser.add_argument('stats', type=str, help="Path to stats file")
parser.add_argument('--web', '-w', action='store_true',
help="Render in web browser instead of svg")
args = parser.parse_args()
return args.stats, args.web
2021-03-03 19:22:47 +00:00
def extract_names(data: list):
names = set()
for d in data:
for field in d:
name = name_from_field(field)
names.update([name])
return names
2021-02-13 19:15:17 +00:00
def name_from_field(field: str) -> str :
if field.startswith("onlyoffice-"):
return "onlyoffice"
2021-03-03 19:22:47 +00:00
name = field.split("_")[0]
name = name.replace("org-caracals-", "")
name = name.replace(".caracals.org", "")
return name
2021-02-13 19:15:17 +00:00
def main():
stats_fn, web_render = parse_args()
data = load_data(stats_fn)
2021-02-14 17:09:34 +00:00
2021-02-13 19:15:17 +00:00
render(data, web_render)
def load_data(stats_fn: str):
with open(stats_fn) as stats_f:
data = json.load(stats_f)
2021-02-14 17:09:34 +00:00
2021-03-03 19:22:47 +00:00
data_dict = {name_from_field(field): [0]*len(data) for field in extract_names(data)}
2021-02-13 19:15:17 +00:00
2021-03-03 19:22:47 +00:00
print("Found", len(data), "points")
print(" keys:", data_dict.keys())
2021-02-13 19:15:17 +00:00
for t_i, stat in enumerate(data):
for field in stat:
if field == "date": # date
2021-03-03 19:22:47 +00:00
date_ = stat[field].replace("+01:00", "+0000")
data_dict[field][t_i] = datetime.strptime(date_, "%Y-%m-%dT%H:%M:%S%z")
2021-02-13 19:15:17 +00:00
else: # float
value = stat[field].split(" ")[0]
value = value.replace("MiB", "e3")
2021-03-03 19:22:47 +00:00
value = value.replace("GiB", "e6")
2021-02-13 19:15:17 +00:00
data_dict[name_from_field(field)][t_i] += float(value) / 1000 # values are in MiB
return data_dict
def render(data: dict, web_render:bool=False):
2021-03-03 19:22:47 +00:00
style = pygal.style.Style(value_label_font_size=5, value_font_size=5, label_font_size=5, legend_font_size=5)
bar_chart = pygal.StackedBar(height=400, x_label_rotation=25, style=style, legend_box_size=5)
2021-02-13 21:00:13 +00:00
labels = [d.strftime("%B %d %H:%M") for d in data["date"]]
bar_chart.x_labels = labels
2021-02-13 19:15:17 +00:00
for k in data:
if k == "date":
continue
#if "db" in k or "database" in k or "mysql" in k or "mongo" in k or "postgre" in k:
# continue
bar_chart.add(k, data[k])
2021-02-14 17:09:34 +00:00
2021-02-13 19:15:17 +00:00
if web_render:
bar_chart.render_in_browser()
else:
bar_chart.render_to_png(PNG_OUTPUT)
print("Image generated in:", PNG_OUTPUT)
if __name__ == "__main__":
main()