from ..config import config from ..utils import o11y, utils import csv import time class Metrics: """ Metrics class for the SDK. """ def __init__(self, cfg: config.Config): self.api = o11y.O11yAPI(cfg) def getMetrics(self, clusterId: str, rules: config.RulesConfig, startTimestemp: int, endTimestemp: int, step: int = 15): """ Get metrics data from o11y. """ # we need to get the cluster info first cluster = self.api.getO11yClusterInfo(clusterId) # get ds path dsPath = utils.getO11yMetricsPath( cluster.vendor, cluster.region, cluster.clusterID) # get metrics data part by part metricsData = dict() # query metrics data every 15 min startTimeRange = startTimestemp endTimeRange = startTimestemp while endTimeRange < endTimestemp: endTimeRange = endTimeRange+15*60 if endTimeRange + \ 15*60 < endTimestemp else endTimestemp print('get metrics data from {} to {}\n'.format( startTimeRange, endTimeRange)) for rule in rules.rules: partMetrics = self.api.getO11yMetrics( dsPath, rule.expr, startTimeRange, endTimeRange, step) for metric in partMetrics: lables = [] for k, v in metric["metric"].items(): if k == '__name__': continue lables.append('"{}":"{}"'.format(k, v)) lables = '{{{}}}'.format(','.join(lables)) # join lables and metrics name name = '{}{}'.format(rule.name, lables) if metricsData.get(name) is None: metricsData[name] = [None] * \ ((endTimestemp-startTimestemp)//step+1) # get the index of the part metrics for value in metric['values']: index = (value[0]-startTimestemp)//step metricsData[name][index] = value[1] startTimeRange = endTimeRange # sleep 0.5s~1.5s to avoid too many requests time.sleep(0.5+int(time.time()) % 1) return metricsData def writeToCSV(self, metricsData: dict, filePath: str): """ Write metrics data to csv file. """ with open(filePath, 'w') as f: csvwriter = csv.writer(f, delimiter=',',) # write header csvwriter.writerow(list(metricsData.keys())) # write data for i in range(len(metricsData[list(metricsData.keys())[0]])): row = [] for name in metricsData.keys(): row.append(metricsData[name][i]) csvwriter.writerow(row)