coco_apm_dashboard_cleaner/main.py

75 lines
2.6 KiB
Python

import os
import dynatraceAPI
import logging
from decouple import config
import yaml
import pandas as pd
from dynatrace import Dynatrace
from dynatrace import TOO_MANY_REQUESTS_WAIT
from dynatrace.environment_v2.tokens_api import SCOPE_METRICS_READ, SCOPE_METRICS_INGEST
def getD(DTURL, DTTOKEN, metricSelector, resolution, fromDate, toDate):
# Create a Dynatrace client
dt = Dynatrace(DTURL, DTTOKEN)
for metric in dt.metrics.query(metricSelector, resolution, fromDate, toDate):
with open('metrics.txt', 'w') as f:
f.write(str(metric))
def getDashboardsWithViewCount(DTAPIToken, DTENV, metricSelector, resolution,
fromDate, toDate):
dtclient = dynatraceAPI.Dynatrace(DTENV, DTAPIToken,
logging.Logger("ERROR"), None, None, 0,
2 * 1000)
params = {
"metricSelector": f"{metricSelector}",
"resolution": f"{resolution}",
"fromDate": f"{fromDate}",
"toDate": f"{toDate}"
}
api_url_report = "/api/v2/metrics/query"
pages = dtclient.returnPageination(api_url_report, params, "data")
df = pd.DataFrame(pages.elements)
return df
def getDashboards(DTAPIToken, DTENV):
dtclient = dynatraceAPI.Dynatrace(DTENV, DTAPIToken,
logging.Logger("ERROR"), None, None, 0,
2 * 1000)
my_params = {
"owner": "",
"tags": [],
}
api_url_report = "/api/config/v1/dashboards"
pages = dtclient.returnPageination(api_url_report, my_params, "dashboards")
df = pd.DataFrame(pages.elements)
return df
if __name__ == "__main__":
metricSelector = "builtin:dashboards.viewCount:splitBy(id):sort(value(auto,ascending))"
resolution = "1M"
fromDate = "now-6M"
toDate = "now"
with open(os.path.basename("./env-config.yaml")) as env_cfg:
env_config = yaml.safe_load(env_cfg)
for item, doc in env_config.items():
token = dict(doc[2])
url = dict(doc[1])
print(item, " crawling through ...")
print(item, " checking token ...")
if config(token.get("env-token-name"), default='') != "":
print(item, " fetching all dashboards ...")
DTTOKEN = config(token.get("env-token-name"), default='')
DTURL = url.get("env-url")
getDashboards(DTTOKEN, DTURL)
getDashboardsWithViewCount(DTTOKEN, DTURL, metricSelector,
resolution, fromDate, toDate)
getD(DTURL, DTTOKEN, metricSelector, resolution, fromDate, toDate)