11"""A Class for collection of metrics from a Prometheus Host."""
2+
23from urllib .parse import urlparse
34import bz2
45import os
@@ -41,7 +42,7 @@ class PrometheusConnect:
4142 Example: {"http_proxy": "<ip_address/hostname:port>", "https_proxy": "<ip_address/hostname:port>"}
4243 :param session (Optional) Custom requests.Session to enable complex HTTP configuration
4344 :param timeout: (Optional) A timeout (in seconds) applied to all requests
44- :param method: (Optional) (str) HTTP Method (GET or POST) to use for Query APIs that allow POST
45+ :param method: (Optional) (str) HTTP Method (GET or POST) to use for Query APIs that allow POST
4546 (/query, /query_range and /labels). Use POST for large and complex queries. Default is GET.
4647 """
4748
@@ -55,7 +56,7 @@ def __init__(
5556 proxy : dict = None ,
5657 session : Session = None ,
5758 timeout : int = None ,
58- method : str = "GET"
59+ method : str = "GET" ,
5960 ):
6061 """Functions as a Constructor for the class PrometheusConnect."""
6162 if url is None :
@@ -69,7 +70,7 @@ def __init__(
6970
7071 if not isinstance (method , str ):
7172 raise TypeError ("Method must be a string" )
72-
73+
7374 method = method .upper ()
7475 if method not in {"GET" , "POST" }:
7576 raise ValueError ("Method can only be GET or POST" )
@@ -130,7 +131,6 @@ def all_metrics(self, params: dict = None):
130131 self ._all_metrics = self .get_label_values (label_name = "__name__" , params = params )
131132 return self ._all_metrics
132133
133-
134134 def get_series (self , start : datetime , end : datetime , params : dict = None ):
135135 """
136136 Get a list series happening between start and end times.
@@ -165,7 +165,6 @@ def get_series(self, start: datetime, end: datetime, params: dict = None):
165165 )
166166 return labels
167167
168-
169168 def get_label_names (self , params : dict = None ):
170169 """
171170 Get a list of all labels.
@@ -480,7 +479,13 @@ def custom_query(self, query: str, params: dict = None, timeout: int = None):
480479 return data
481480
482481 def custom_query_range (
483- self , query : str , start_time : datetime , end_time : datetime , step : str , params : dict = None , timeout : int = None
482+ self ,
483+ query : str ,
484+ start_time : datetime ,
485+ end_time : datetime ,
486+ step : str ,
487+ params : dict = None ,
488+ timeout : int = None ,
484489 ):
485490 """
486491 Send a query_range to a Prometheus Host.
@@ -617,21 +622,20 @@ def get_metric_aggregation(
617622 raise TypeError ("Invalid operation: " + operation )
618623 return aggregated_values
619624
620-
621625 def get_scrape_pools (self ) -> list [str ]:
622626 """
623627 Get a list of all scrape pools in activeTargets.
624628 """
625629 scrape_pools = []
626- for target in self .get_targets ()[' activeTargets' ]:
627- scrape_pools .append (target [' scrapePool' ])
630+ for target in self .get_targets ()[" activeTargets" ]:
631+ scrape_pools .append (target [" scrapePool" ])
628632 return list (set (scrape_pools ))
629633
630634 def get_targets (self , state : str = None , scrape_pool : str = None ):
631635 """
632636 Get a list of all targets from Prometheus.
633637
634- :param state: (str) Optional filter for target state ('active', 'dropped', 'any').
638+ :param state: (str) Optional filter for target state ('active', 'dropped', 'any').
635639 If None, returns both active and dropped targets.
636640 :param scrape_pool: (str) Optional filter by scrape pool name
637641 :returns: (dict) A dictionary containing active and dropped targets
@@ -641,9 +645,9 @@ def get_targets(self, state: str = None, scrape_pool: str = None):
641645 """
642646 params = {}
643647 if state :
644- params [' state' ] = state
648+ params [" state" ] = state
645649 if scrape_pool :
646- params [' scrapePool' ] = scrape_pool
650+ params [" scrapePool" ] = scrape_pool
647651
648652 response = self ._session .request (
649653 method = "GET" ,
@@ -660,8 +664,7 @@ def get_targets(self, state: str = None, scrape_pool: str = None):
660664 return response .json ()["data" ]
661665 else :
662666 raise PrometheusApiClientException (
663- "HTTP Status Code {} ({!r})" .format (
664- response .status_code , response .content )
667+ "HTTP Status Code {} ({!r})" .format (response .status_code , response .content )
665668 )
666669
667670 def get_target_metadata (self , target : dict [str , str ], metric : str = None ):
@@ -679,12 +682,11 @@ def get_target_metadata(self, target: dict[str, str], metric: str = None):
679682
680683 # Convert target dict to label selector string
681684 if metric :
682- params [' metric' ] = metric
685+ params [" metric" ] = metric
683686
684687 if target :
685- match_target = "{" + \
686- "," .join (f'{ k } ="{ v } "' for k , v in target .items ()) + "}"
687- params ['match_target' ] = match_target
688+ match_target = "{" + "," .join (f'{ k } ="{ v } "' for k , v in target .items ()) + "}"
689+ params ["match_target" ] = match_target
688690
689691 response = self ._session .request (
690692 method = "GET" ,
@@ -701,8 +703,7 @@ def get_target_metadata(self, target: dict[str, str], metric: str = None):
701703 return response .json ()["data" ]
702704 else :
703705 raise PrometheusApiClientException (
704- "HTTP Status Code {} ({!r})" .format (
705- response .status_code , response .content )
706+ "HTTP Status Code {} ({!r})" .format (response .status_code , response .content )
706707 )
707708
708709 def get_metric_metadata (self , metric : str , limit : int = None , limit_per_metric : int = None ):
@@ -721,13 +722,13 @@ def get_metric_metadata(self, metric: str, limit: int = None, limit_per_metric:
721722 params = {}
722723
723724 if metric :
724- params [' metric' ] = metric
725+ params [" metric" ] = metric
725726
726727 if limit :
727- params [' limit' ] = limit
728+ params [" limit" ] = limit
728729
729730 if limit_per_metric :
730- params [' limit_per_metric' ] = limit_per_metric
731+ params [" limit_per_metric" ] = limit_per_metric
731732
732733 response = self ._session .request (
733734 method = "GET" ,
@@ -745,15 +746,16 @@ def get_metric_metadata(self, metric: str, limit: int = None, limit_per_metric:
745746 formatted_data = []
746747 for k , v in data .items ():
747748 for v_ in v :
748- formatted_data .append ({
749- "metric_name" : k ,
750- "type" : v_ .get ('type' , 'unknown' ),
751- "help" : v_ .get ('help' , '' ),
752- "unit" : v_ .get ('unit' , '' )
753- })
749+ formatted_data .append (
750+ {
751+ "metric_name" : k ,
752+ "type" : v_ .get ("type" , "unknown" ),
753+ "help" : v_ .get ("help" , "" ),
754+ "unit" : v_ .get ("unit" , "" ),
755+ }
756+ )
754757 return formatted_data
755758 else :
756759 raise PrometheusApiClientException (
757- "HTTP Status Code {} ({!r})" .format (
758- response .status_code , response .content )
760+ "HTTP Status Code {} ({!r})" .format (response .status_code , response .content )
759761 )
0 commit comments