27
27
from urllib .request import build_opener , Request , HTTPHandler
28
28
from urllib .parse import quote_plus , parse_qs , urlparse
29
29
30
-
31
30
CONTENT_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"""
33
32
34
33
PYTHON26_OR_OLDER = sys .version_info < (2 , 7 )
35
34
36
35
37
36
def 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
+
39
39
def prometheus_app (environ , start_response ):
40
40
params = parse_qs (environ .get ('QUERY_STRING' , '' ))
41
41
r = registry
@@ -48,6 +48,7 @@ def prometheus_app(environ, start_response):
48
48
headers = [(str ('Content-type' ), content_type )]
49
49
start_response (status , headers )
50
50
return [output ]
51
+
51
52
return prometheus_app
52
53
53
54
@@ -68,22 +69,22 @@ def start_wsgi_server(port, addr='', registry=REGISTRY):
68
69
69
70
70
71
def 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."""
72
73
73
- def sample_line (s ):
74
- if s .labels :
74
+ def sample_line (line ):
75
+ if line .labels :
75
76
labelstr = '{{{0}}}' .format (',' .join (
76
77
['{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 ())]))
79
80
else :
80
81
labelstr = ''
81
82
timestamp = ''
82
- if s .timestamp is not None :
83
+ if line .timestamp is not None :
83
84
# Convert to milliseconds.
84
- timestamp = ' {0:d}' .format (int (float (s .timestamp ) * 1000 ))
85
+ timestamp = ' {0:d}' .format (int (float (line .timestamp ) * 1000 ))
85
86
return '{0}{1} {2}{3}\n ' .format (
86
- s .name , labelstr , floatToGoString (s .value ), timestamp )
87
+ line .name , labelstr , floatToGoString (line .value ), timestamp )
87
88
88
89
output = []
89
90
for metric in registry .collect ():
@@ -121,7 +122,7 @@ def sample_line(s):
121
122
except Exception as exception :
122
123
exception .args = (exception .args or ('' ,)) + (metric ,)
123
124
raise
124
-
125
+
125
126
for suffix , lines in sorted (om_samples .items ()):
126
127
output .append ('# TYPE {0}{1} gauge\n ' .format (metric .name , suffix ))
127
128
output .extend (lines )
@@ -134,7 +135,7 @@ def choose_encoder(accept_header):
134
135
if accepted .split (';' )[0 ].strip () == 'application/openmetrics-text' :
135
136
return (openmetrics .generate_latest ,
136
137
openmetrics .CONTENT_TYPE_LATEST )
137
- return ( generate_latest , CONTENT_TYPE_LATEST )
138
+ return generate_latest , CONTENT_TYPE_LATEST
138
139
139
140
140
141
class MetricsHandler (BaseHTTPRequestHandler ):
@@ -196,10 +197,10 @@ def start_http_server(port, addr='', registry=REGISTRY):
196
197
197
198
198
199
def write_to_textfile (path , registry ):
199
- ''' Write metrics to the given path.
200
+ """ Write metrics to the given path.
200
201
201
202
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."""
203
204
tmppath = '%s.%s.%s' % (path , os .getpid (), threading .current_thread ().ident )
204
205
with open (tmppath , 'wb' ) as f :
205
206
f .write (generate_latest (registry ))
@@ -208,9 +209,10 @@ def write_to_textfile(path, registry):
208
209
209
210
210
211
def 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."""
212
215
213
- Used by the push_to_gateway functions. Can be re-used by other handlers.'''
214
216
def handle ():
215
217
request = Request (url , data = data )
216
218
request .get_method = lambda : method
@@ -225,13 +227,14 @@ def handle():
225
227
226
228
227
229
def 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.
229
231
230
232
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
+
232
235
def handle ():
233
- ''' Handler that implements HTTP Basic Auth.
234
- '''
236
+ """ Handler that implements HTTP Basic Auth.
237
+ """
235
238
if username is not None and password is not None :
236
239
auth_value = '{0}:{1}' .format (username , password ).encode ('utf-8' )
237
240
auth_token = base64 .b64encode (auth_value )
@@ -245,7 +248,7 @@ def handle():
245
248
def push_to_gateway (
246
249
gateway , job , registry , grouping_key = None , timeout = 30 ,
247
250
handler = default_handler ):
248
- ''' Push metrics to the given pushgateway.
251
+ """ Push metrics to the given pushgateway.
249
252
250
253
`gateway` the url for your push gateway. Either of the form
251
254
'http://pushgateway.local', or 'pushgateway.local'.
@@ -282,14 +285,14 @@ def push_to_gateway(
282
285
Message Body.
283
286
284
287
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."""
286
289
_use_gateway ('PUT' , gateway , job , registry , grouping_key , timeout , handler )
287
290
288
291
289
292
def pushadd_to_gateway (
290
293
gateway , job , registry , grouping_key = None , timeout = 30 ,
291
294
handler = default_handler ):
292
- ''' PushAdd metrics to the given pushgateway.
295
+ """ PushAdd metrics to the given pushgateway.
293
296
294
297
`gateway` the url for your push gateway. Either of the form
295
298
'http://pushgateway.local', or 'pushgateway.local'.
@@ -308,13 +311,13 @@ def pushadd_to_gateway(
308
311
for implementation requirements.
309
312
310
313
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."""
312
315
_use_gateway ('POST' , gateway , job , registry , grouping_key , timeout , handler )
313
316
314
317
315
318
def delete_from_gateway (
316
319
gateway , job , grouping_key = None , timeout = 30 , handler = default_handler ):
317
- ''' Delete metrics from the given pushgateway.
320
+ """ Delete metrics from the given pushgateway.
318
321
319
322
`gateway` the url for your push gateway. Either of the form
320
323
'http://pushgateway.local', or 'pushgateway.local'.
@@ -332,7 +335,7 @@ def delete_from_gateway(
332
335
for implementation requirements.
333
336
334
337
This deletes metrics with the given job and grouping_key.
335
- This uses the DELETE HTTP method.'''
338
+ This uses the DELETE HTTP method."""
336
339
_use_gateway ('DELETE' , gateway , job , None , grouping_key , timeout , handler )
337
340
338
341
@@ -359,7 +362,7 @@ def _use_gateway(method, gateway, job, registry, grouping_key, timeout, handler)
359
362
360
363
361
364
def 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."""
363
366
with closing (socket .socket (socket .AF_INET , socket .SOCK_DGRAM )) as s :
364
367
s .connect (('localhost' , 0 ))
365
368
return {'instance' : s .getsockname ()[0 ]}
0 commit comments