|
| 1 | +"""A Class for metric object.""" |
| 2 | +from copy import deepcopy |
| 3 | +import datetime |
| 4 | +import pandas |
| 5 | + |
| 6 | +try: |
| 7 | + import matplotlib.pyplot as plt |
| 8 | + from pandas.plotting import register_matplotlib_converters |
| 9 | + |
| 10 | + register_matplotlib_converters() |
| 11 | + _MPL_FOUND = True |
| 12 | +except ImportError as exce: |
| 13 | + _MPL_FOUND = False |
| 14 | + |
| 15 | + |
| 16 | +class Metric: |
| 17 | + r""" |
| 18 | + A Class for `Metric` object. |
| 19 | +
|
| 20 | + :param metric: (dict) A metric item from the list of metrics received from prometheus |
| 21 | + :param oldest_data_datetime: (datetime|timedelta) Any metric values in the dataframe that are \ |
| 22 | + older than this value will be deleted when new data is added to the dataframe \ |
| 23 | + using the __add__("+") operator. |
| 24 | +
|
| 25 | + * `oldest_data_datetime=datetime.timedelta(days=2)`, will delete the \ |
| 26 | + metric data that is 2 days older than the latest metric. \ |
| 27 | + The dataframe is pruned only when new data is added to it. \n |
| 28 | + * `oldest_data_datetime=datetime.datetime(2019,5,23,12,0)`, will delete \ |
| 29 | + any data that is older than "23 May 2019 12:00:00" \n |
| 30 | + * `oldest_data_datetime=datetime.datetime.fromtimestamp(1561475156)` \ |
| 31 | + can also be set using the unix timestamp |
| 32 | +
|
| 33 | + Example Usage: |
| 34 | + ``prom = PrometheusConnect()`` |
| 35 | +
|
| 36 | + ``my_label_config = {'cluster': 'my_cluster_id', 'label_2': 'label_2_value'}`` |
| 37 | +
|
| 38 | + ``metric_data = prom.get_metric_range_data(metric_name='up', label_config=my_label_config)`` |
| 39 | + ``Here metric_data is a list of metrics received from prometheus`` |
| 40 | +
|
| 41 | + ``# only for the first item in the list`` |
| 42 | + ``my_metric_object = Metric(metric_data[0], datetime.timedelta(days=10)) `` |
| 43 | +
|
| 44 | + """ |
| 45 | + |
| 46 | + def __init__(self, metric, oldest_data_datetime=None): |
| 47 | + """Constructor for the Metric object.""" |
| 48 | + if not isinstance( |
| 49 | + oldest_data_datetime, (datetime.datetime, datetime.timedelta, type(None)) |
| 50 | + ): |
| 51 | + # if it is neither a datetime object nor a timedelta object raise exception |
| 52 | + raise TypeError( |
| 53 | + "oldest_data_datetime can only be datetime.datetime/ datetime.timedelta or None" |
| 54 | + ) |
| 55 | + |
| 56 | + if isinstance(metric, Metric): |
| 57 | + # if metric is a Metric object, just copy the object and update its parameters |
| 58 | + self.metric_name = metric.metric_name |
| 59 | + self.label_config = metric.label_config |
| 60 | + self.metric_values = metric.metric_values |
| 61 | + self.oldest_data_datetime = oldest_data_datetime |
| 62 | + else: |
| 63 | + self.metric_name = metric["metric"]["__name__"] |
| 64 | + self.label_config = deepcopy(metric["metric"]) |
| 65 | + self.oldest_data_datetime = oldest_data_datetime |
| 66 | + del self.label_config["__name__"] |
| 67 | + |
| 68 | + # if it is a single value metric change key name |
| 69 | + if "value" in metric: |
| 70 | + metric["values"] = [metric["value"]] |
| 71 | + |
| 72 | + self.metric_values = pandas.DataFrame(metric["values"], columns=["ds", "y"]).apply( |
| 73 | + pandas.to_numeric, errors="raise" |
| 74 | + ) |
| 75 | + self.metric_values["ds"] = pandas.to_datetime(self.metric_values["ds"], unit="s") |
| 76 | + |
| 77 | + # Set the metric start time and the metric end time |
| 78 | + self.start_time = self.metric_values.iloc[0, 0] |
| 79 | + self.end_time = self.metric_values.iloc[-1, 0] |
| 80 | + |
| 81 | + def __eq__(self, other): |
| 82 | + """ |
| 83 | + Overloading operator ``=``. |
| 84 | +
|
| 85 | + Check whether two metrics are the same (are the same time-series regardless of their data) |
| 86 | +
|
| 87 | + Example Usage: |
| 88 | + ``metric_1 = Metric(metric_data_1)`` |
| 89 | +
|
| 90 | + ``metric_2 = Metric(metric_data_2)`` |
| 91 | +
|
| 92 | + ``print(metric_1 == metric_2) # will print True if they belong to the same time-series`` |
| 93 | +
|
| 94 | + :return: (bool) If two Metric objects belong to the same time-series, |
| 95 | + i.e. same name and label config, it will return True, else False |
| 96 | + """ |
| 97 | + return bool( |
| 98 | + (self.metric_name == other.metric_name) and (self.label_config == other.label_config) |
| 99 | + ) |
| 100 | + |
| 101 | + def __str__(self): |
| 102 | + """ |
| 103 | + Make it print in a cleaner way when print function is used on a Metric object. |
| 104 | +
|
| 105 | + Example Usage: |
| 106 | + ``metric_1 = Metric(metric_data_1)`` |
| 107 | +
|
| 108 | + ``print(metric_1) # will print the name, labels and the head of the dataframe`` |
| 109 | +
|
| 110 | + """ |
| 111 | + name = "metric_name: " + repr(self.metric_name) + "\n" |
| 112 | + labels = "label_config: " + repr(self.label_config) + "\n" |
| 113 | + values = "metric_values: " + repr(self.metric_values) |
| 114 | + |
| 115 | + return "{" + "\n" + name + labels + values + "\n" + "}" |
| 116 | + |
| 117 | + def __add__(self, other): |
| 118 | + r""" |
| 119 | + Overloading operator ``+``. |
| 120 | +
|
| 121 | + Add two metric objects for the same time-series |
| 122 | +
|
| 123 | + Example Usage: |
| 124 | + .. code-block:: python |
| 125 | +
|
| 126 | + metric_1 = Metric(metric_data_1) |
| 127 | + metric_2 = Metric(metric_data_2) |
| 128 | + metric_12 = metric_1 + metric_2 # will add the data in ``metric_2`` to ``metric_1`` |
| 129 | + # so if any other parameters are set in ``metric_1`` |
| 130 | + # will also be set in ``metric_12`` |
| 131 | + # (like ``oldest_data_datetime``) |
| 132 | +
|
| 133 | + :return: (`Metric`) Returns a `Metric` object with the combined metric data \ |
| 134 | + of the two added metrics |
| 135 | +
|
| 136 | + :raises: (TypeError) Raises an exception when two metrics being added are \ |
| 137 | + from different metric time-series |
| 138 | + """ |
| 139 | + if self == other: |
| 140 | + new_metric = deepcopy(self) |
| 141 | + new_metric.metric_values = new_metric.metric_values.append( |
| 142 | + other.metric_values, ignore_index=True |
| 143 | + ) |
| 144 | + new_metric.metric_values = new_metric.metric_values.dropna() |
| 145 | + new_metric.metric_values = ( |
| 146 | + new_metric.metric_values.drop_duplicates("ds") |
| 147 | + .sort_values(by=["ds"]) |
| 148 | + .reset_index(drop=True) |
| 149 | + ) |
| 150 | + # if oldest_data_datetime is set, trim the dataframe and only keep the newer data |
| 151 | + if new_metric.oldest_data_datetime: |
| 152 | + if isinstance(new_metric.oldest_data_datetime, datetime.timedelta): |
| 153 | + # create a time range mask |
| 154 | + mask = new_metric.metric_values["ds"] >= ( |
| 155 | + new_metric.metric_values.iloc[-1, 0] - abs(new_metric.oldest_data_datetime) |
| 156 | + ) |
| 157 | + else: |
| 158 | + # create a time range mask |
| 159 | + mask = new_metric.metric_values["ds"] >= new_metric.oldest_data_datetime |
| 160 | + # truncate the df within the mask |
| 161 | + new_metric.metric_values = new_metric.metric_values.loc[mask] |
| 162 | + |
| 163 | + # Update the metric start time and the metric end time for the new Metric |
| 164 | + new_metric.start_time = new_metric.metric_values.iloc[0, 0] |
| 165 | + new_metric.end_time = new_metric.metric_values.iloc[-1, 0] |
| 166 | + |
| 167 | + return new_metric |
| 168 | + |
| 169 | + if self.metric_name != other.metric_name: |
| 170 | + error_string = "Different metric names" |
| 171 | + else: |
| 172 | + error_string = "Different metric labels" |
| 173 | + raise TypeError("Cannot Add different metric types. " + error_string) |
| 174 | + |
| 175 | + def plot(self): |
| 176 | + """Plot a very simple line graph for the metric time-series.""" |
| 177 | + if _MPL_FOUND: |
| 178 | + fig, axis = plt.subplots() |
| 179 | + axis.plot_date(self.metric_values.ds, self.metric_values.y, linestyle=":") |
| 180 | + fig.autofmt_xdate() |
| 181 | + # if matplotlib was not imported |
| 182 | + else: |
| 183 | + raise ImportError("matplotlib was not found") |
0 commit comments