2727 from urllib .request import build_opener , Request , HTTPHandler
2828 from urllib .parse import quote_plus , parse_qs , urlparse
2929
30-
3130CONTENT_TYPE_LATEST = str ('text/plain; version=0.0.4; charset=utf-8' )
32- ''' Content type of the latest text format'''
31+ """ Content type of the latest text format"""
3332
3433PYTHON26_OR_OLDER = sys .version_info < (2 , 7 )
3534
3635
3736def make_wsgi_app (registry = REGISTRY ):
38- '''Create a WSGI app which serves the metrics from a registry.'''
37+ """Create a WSGI app which serves the metrics from a registry."""
38+
3939 def prometheus_app (environ , start_response ):
4040 params = parse_qs (environ .get ('QUERY_STRING' , '' ))
4141 r = registry
@@ -48,6 +48,7 @@ def prometheus_app(environ, start_response):
4848 headers = [(str ('Content-type' ), content_type )]
4949 start_response (status , headers )
5050 return [output ]
51+
5152 return prometheus_app
5253
5354
@@ -68,22 +69,22 @@ def start_wsgi_server(port, addr='', registry=REGISTRY):
6869
6970
7071def generate_latest (registry = REGISTRY ):
71- ''' Returns the metrics from the registry in latest text format as a string.'''
72+ """ Returns the metrics from the registry in latest text format as a string."""
7273
73- def sample_line (s ):
74- if s .labels :
74+ def sample_line (line ):
75+ if line .labels :
7576 labelstr = '{{{0}}}' .format (',' .join (
7677 ['{0}="{1}"' .format (
77- k , v .replace ('\\ ' , r'\\' ).replace ('\n ' , r'\n' ).replace ('"' , r'\"' ))
78- for k , v in sorted (s .labels .items ())]))
78+ k , v .replace ('\\ ' , r'\\' ).replace ('\n ' , r'\n' ).replace ('"' , r'\"' ))
79+ for k , v in sorted (line .labels .items ())]))
7980 else :
8081 labelstr = ''
8182 timestamp = ''
82- if s .timestamp is not None :
83+ if line .timestamp is not None :
8384 # Convert to milliseconds.
84- timestamp = ' {0:d}' .format (int (float (s .timestamp ) * 1000 ))
85+ timestamp = ' {0:d}' .format (int (float (line .timestamp ) * 1000 ))
8586 return '{0}{1} {2}{3}\n ' .format (
86- s .name , labelstr , floatToGoString (s .value ), timestamp )
87+ line .name , labelstr , floatToGoString (line .value ), timestamp )
8788
8889 output = []
8990 for metric in registry .collect ():
@@ -121,7 +122,7 @@ def sample_line(s):
121122 except Exception as exception :
122123 exception .args = (exception .args or ('' ,)) + (metric ,)
123124 raise
124-
125+
125126 for suffix , lines in sorted (om_samples .items ()):
126127 output .append ('# TYPE {0}{1} gauge\n ' .format (metric .name , suffix ))
127128 output .extend (lines )
@@ -134,7 +135,7 @@ def choose_encoder(accept_header):
134135 if accepted .split (';' )[0 ].strip () == 'application/openmetrics-text' :
135136 return (openmetrics .generate_latest ,
136137 openmetrics .CONTENT_TYPE_LATEST )
137- return ( generate_latest , CONTENT_TYPE_LATEST )
138+ return generate_latest , CONTENT_TYPE_LATEST
138139
139140
140141class MetricsHandler (BaseHTTPRequestHandler ):
@@ -196,10 +197,10 @@ def start_http_server(port, addr='', registry=REGISTRY):
196197
197198
198199def write_to_textfile (path , registry ):
199- ''' Write metrics to the given path.
200+ """ Write metrics to the given path.
200201
201202 This is intended for use with the Node exporter textfile collector.
202- The path must end in .prom for the textfile collector to process it.'''
203+ The path must end in .prom for the textfile collector to process it."""
203204 tmppath = '%s.%s.%s' % (path , os .getpid (), threading .current_thread ().ident )
204205 with open (tmppath , 'wb' ) as f :
205206 f .write (generate_latest (registry ))
@@ -208,9 +209,10 @@ def write_to_textfile(path, registry):
208209
209210
210211def default_handler (url , method , timeout , headers , data ):
211- '''Default handler that implements HTTP/HTTPS connections.
212+ """Default handler that implements HTTP/HTTPS connections.
213+
214+ Used by the push_to_gateway functions. Can be re-used by other handlers."""
212215
213- Used by the push_to_gateway functions. Can be re-used by other handlers.'''
214216 def handle ():
215217 request = Request (url , data = data )
216218 request .get_method = lambda : method
@@ -225,13 +227,14 @@ def handle():
225227
226228
227229def basic_auth_handler (url , method , timeout , headers , data , username = None , password = None ):
228- ''' Handler that implements HTTP/HTTPS connections with Basic Auth.
230+ """ Handler that implements HTTP/HTTPS connections with Basic Auth.
229231
230232 Sets auth headers using supplied 'username' and 'password', if set.
231- Used by the push_to_gateway functions. Can be re-used by other handlers.'''
233+ Used by the push_to_gateway functions. Can be re-used by other handlers."""
234+
232235 def handle ():
233- ''' Handler that implements HTTP Basic Auth.
234- '''
236+ """ Handler that implements HTTP Basic Auth.
237+ """
235238 if username is not None and password is not None :
236239 auth_value = '{0}:{1}' .format (username , password ).encode ('utf-8' )
237240 auth_token = base64 .b64encode (auth_value )
@@ -245,7 +248,7 @@ def handle():
245248def push_to_gateway (
246249 gateway , job , registry , grouping_key = None , timeout = 30 ,
247250 handler = default_handler ):
248- ''' Push metrics to the given pushgateway.
251+ """ Push metrics to the given pushgateway.
249252
250253 `gateway` the url for your push gateway. Either of the form
251254 'http://pushgateway.local', or 'pushgateway.local'.
@@ -282,14 +285,14 @@ def push_to_gateway(
282285 Message Body.
283286
284287 This overwrites all metrics with the same job and grouping_key.
285- This uses the PUT HTTP method.'''
288+ This uses the PUT HTTP method."""
286289 _use_gateway ('PUT' , gateway , job , registry , grouping_key , timeout , handler )
287290
288291
289292def pushadd_to_gateway (
290293 gateway , job , registry , grouping_key = None , timeout = 30 ,
291294 handler = default_handler ):
292- ''' PushAdd metrics to the given pushgateway.
295+ """ PushAdd metrics to the given pushgateway.
293296
294297 `gateway` the url for your push gateway. Either of the form
295298 'http://pushgateway.local', or 'pushgateway.local'.
@@ -308,13 +311,13 @@ def pushadd_to_gateway(
308311 for implementation requirements.
309312
310313 This replaces metrics with the same name, job and grouping_key.
311- This uses the POST HTTP method.'''
314+ This uses the POST HTTP method."""
312315 _use_gateway ('POST' , gateway , job , registry , grouping_key , timeout , handler )
313316
314317
315318def delete_from_gateway (
316319 gateway , job , grouping_key = None , timeout = 30 , handler = default_handler ):
317- ''' Delete metrics from the given pushgateway.
320+ """ Delete metrics from the given pushgateway.
318321
319322 `gateway` the url for your push gateway. Either of the form
320323 'http://pushgateway.local', or 'pushgateway.local'.
@@ -332,7 +335,7 @@ def delete_from_gateway(
332335 for implementation requirements.
333336
334337 This deletes metrics with the given job and grouping_key.
335- This uses the DELETE HTTP method.'''
338+ This uses the DELETE HTTP method."""
336339 _use_gateway ('DELETE' , gateway , job , None , grouping_key , timeout , handler )
337340
338341
@@ -359,7 +362,7 @@ def _use_gateway(method, gateway, job, registry, grouping_key, timeout, handler)
359362
360363
361364def instance_ip_grouping_key ():
362- ''' Grouping key with instance set to the IP Address of this host.'''
365+ """ Grouping key with instance set to the IP Address of this host."""
363366 with closing (socket .socket (socket .AF_INET , socket .SOCK_DGRAM )) as s :
364367 s .connect (('localhost' , 0 ))
365368 return {'instance' : s .getsockname ()[0 ]}
0 commit comments