Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ dist
*.swp
.coverage.*
.coverage
.idea
.tox
2 changes: 0 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ language: python

matrix:
include:
- python: "2.6"
env: TOXENV=py26
- python: "2.7"
env: TOXENV=py27
- python: "2.7"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -481,5 +481,5 @@ system.
from prometheus_client.parser import text_string_to_metric_families
for family in text_string_to_metric_families(u"my_gauge 1.0\n"):
for sample in family.samples:
print("Name: {0} Labels: {1} Value: {2}".format(*sample))
print("Name: {} Labels: {} Value: {}".format(*sample))
```
4 changes: 2 additions & 2 deletions prometheus_client/bridge/graphite.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ def push(self, prefix=''):
for name, labels, value in metric.samples:
if labels:
labelstr = '.' + '.'.join(
['{0}.{1}'.format(
['{}.{}'.format(
_sanitize(k), _sanitize(v))
for k, v in sorted(labels.items())])
else:
labelstr = ''
output.append('{0}{1}{2} {3} {4}\n'.format(
output.append('{}{}{} {} {}\n'.format(
prefixstr, _sanitize(name), labelstr, float(value), now))

conn = socket.create_connection(self._address, self._timeout)
Expand Down
6 changes: 3 additions & 3 deletions prometheus_client/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ def _init_value(self, key):
encoded = key.encode('utf-8')
# Pad to be 8-byte aligned.
padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8))
value = struct.pack('i{0}sd'.format(len(padded)).encode(), len(encoded), padded, 0.0)
value = struct.pack('i{}sd'.format(len(padded)).encode(), len(encoded), padded, 0.0)
while self._used + len(value) > self._capacity:
self._capacity *= 2
self._f.truncate(self._capacity)
Expand All @@ -360,7 +360,7 @@ def _read_all_values(self):
while pos < self._used:
encoded_len = struct.unpack_from(b'i', self._m, pos)[0]
pos += 4
encoded = struct.unpack_from('{0}s'.format(encoded_len).encode(), self._m, pos)[0]
encoded = struct.unpack_from('{}s'.format(encoded_len).encode(), self._m, pos)[0]
padded_len = encoded_len + (8 - (encoded_len + 4) % 8)
pos += padded_len
value = struct.unpack_from(b'd', self._m, pos)[0]
Expand Down Expand Up @@ -421,7 +421,7 @@ def __reset(self):
file_prefix = typ
if file_prefix not in files:
filename = os.path.join(
os.environ['prometheus_multiproc_dir'], '{0}_{1}.db'.format(file_prefix, pid['value']))
os.environ['prometheus_multiproc_dir'], '{}_{}.db'.format(file_prefix, pid['value']))
files[file_prefix] = _MmapedDict(filename)
self._file = files[file_prefix]
self._key = json.dumps((metric_name, name, labelnames, labelvalues))
Expand Down
24 changes: 11 additions & 13 deletions prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
CONTENT_TYPE_LATEST = str('text/plain; version=0.0.4; charset=utf-8')
'''Content type of the latest text format'''

PYTHON26_OR_OLDER = tuple(int(val) for val in sys.version.split()[0].split('.')) < (2, 7, 0)

def make_wsgi_app(registry=core.REGISTRY):
'''Create a WSGI app which serves the metrics from a registry.'''
def prometheus_app(environ, start_response):
Expand Down Expand Up @@ -66,18 +64,18 @@ def generate_latest(registry=core.REGISTRY):
'''Returns the metrics from the registry in latest text format as a string.'''
output = []
for metric in registry.collect():
output.append('# HELP {0} {1}'.format(
output.append('# HELP {} {}'.format(
metric.name, metric.documentation.replace('\\', r'\\').replace('\n', r'\n')))
output.append('\n# TYPE {0} {1}\n'.format(metric.name, metric.type))
output.append('\n# TYPE {} {}\n'.format(metric.name, metric.type))
for name, labels, value in metric.samples:
if labels:
labelstr = '{{{0}}}'.format(','.join(
['{0}="{1}"'.format(
labelstr = '{{{}}}'.format(','.join(
['{}="{}"'.format(
k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
for k, v in sorted(labels.items())]))
else:
labelstr = ''
output.append('{0}{1} {2}\n'.format(name, labelstr, core._floatToGoString(value)))
output.append('{}{} {}\n'.format(name, labelstr, core._floatToGoString(value)))
return ''.join(output).encode('utf-8')


Expand Down Expand Up @@ -138,7 +136,7 @@ def handle():
request.add_header(k, v)
resp = build_opener(HTTPHandler).open(request, timeout=timeout)
if resp.code >= 400:
raise IOError("error talking to pushgateway: {0} {1}".format(
raise IOError("error talking to pushgateway: {} {}".format(
resp.code, resp.msg))

return handle
Expand All @@ -153,7 +151,7 @@ def handle():
'''Handler that implements HTTP Basic Auth.
'''
if username is not None and password is not None:
auth_value = '{0}:{1}'.format(username, password).encode('utf-8')
auth_value = '{}:{}'.format(username, password).encode('utf-8')
auth_token = base64.b64encode(auth_value)
auth_header = b'Basic ' + auth_token
headers.append(['Authorization', auth_header])
Expand Down Expand Up @@ -253,17 +251,17 @@ def delete_from_gateway(gateway, job, grouping_key=None, timeout=None, handler=d

def _use_gateway(method, gateway, job, registry, grouping_key, timeout, handler):
gateway_url = urlparse(gateway)
if not gateway_url.scheme or (PYTHON26_OR_OLDER and gateway_url.scheme not in ['http', 'https']):
gateway = 'http://{0}'.format(gateway)
url = '{0}/metrics/job/{1}'.format(gateway, quote_plus(job))
if not gateway_url.scheme:
gateway = 'http://{}'.format(gateway)
url = '{}/metrics/job/{}'.format(gateway, quote_plus(job))

data = b''
if method != 'DELETE':
data = generate_latest(registry)

if grouping_key is None:
grouping_key = {}
url = url + ''.join(['/{0}/{1}'.format(quote_plus(str(k)), quote_plus(str(v)))
url = url + ''.join(['/{}/{}'.format(quote_plus(str(k)), quote_plus(str(v)))
for k, v in sorted(grouping_key.items())])

headers=[('Content-Type', CONTENT_TYPE_LATEST)]
Expand Down
4 changes: 2 additions & 2 deletions prometheus_client/multiprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def mark_process_dead(pid, path=None):
"""Do bookkeeping for when one process dies in a multi-process setup."""
if path is None:
path = os.environ.get('prometheus_multiproc_dir')
for f in glob.glob(os.path.join(path, 'gauge_livesum_{0}.db'.format(pid))):
for f in glob.glob(os.path.join(path, 'gauge_livesum_{}.db'.format(pid))):
os.remove(f)
for f in glob.glob(os.path.join(path, 'gauge_liveall_{0}.db'.format(pid))):
for f in glob.glob(os.path.join(path, 'gauge_liveall_{}.db'.format(pid))):
os.remove(f)
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
from setuptools import setup

setup(
Expand All @@ -16,14 +15,14 @@
'twisted': ['twisted'],
},
test_suite="tests",
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
Expand Down
10 changes: 2 additions & 8 deletions tests/test_exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@

import sys
import threading

if sys.version_info < (2, 7):
# We need the skip decorators from unittest2 on Python 2.6.
import unittest2 as unittest
else:
import unittest
import unittest

from prometheus_client import Gauge, Counter, Summary, Histogram, Metric
from prometheus_client import CollectorRegistry, generate_latest
Expand Down Expand Up @@ -42,7 +37,6 @@ def test_summary(self):
s.labels('c', 'd').observe(17)
self.assertEqual(b'# HELP ss A summary\n# TYPE ss summary\nss_count{a="c",b="d"} 1.0\nss_sum{a="c",b="d"} 17.0\n', generate_latest(self.registry))

@unittest.skipIf(sys.version_info < (2, 7), "Test requires Python 2.7+.")
def test_histogram(self):
s = Histogram('hh', 'A histogram', registry=self.registry)
s.observe(0.05)
Expand Down Expand Up @@ -111,7 +105,7 @@ def do_PUT(self):
do_DELETE = do_PUT

httpd = HTTPServer(('localhost', 0), TestHandler)
self.address = 'http://localhost:{0}'.format(httpd.server_address[1])
self.address = 'http://localhost:{}'.format(httpd.server_address[1])
class TestServer(threading.Thread):
def run(self):
httpd.handle_request()
Expand Down
9 changes: 1 addition & 8 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
from __future__ import unicode_literals

import sys

if sys.version_info < (2, 7):
# We need the skip decorators from unittest2 on Python 2.6.
import unittest2 as unittest
else:
import unittest
import unittest

from prometheus_client.core import *
from prometheus_client.exposition import *
Expand Down Expand Up @@ -185,7 +179,6 @@ def test_timestamps_discarded(self):
b = CounterMetricFamily("b", "help", value=2)
self.assertEqual([a, b], list(families))

@unittest.skipIf(sys.version_info < (2, 7), "Test requires Python 2.7+.")
def test_roundtrip(self):
text = """# HELP go_gc_duration_seconds A summary of the GC invocation durations.
# TYPE go_gc_duration_seconds summary
Expand Down
7 changes: 1 addition & 6 deletions tests/test_twisted.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
from __future__ import absolute_import, unicode_literals

import sys

if sys.version_info < (2, 7):
from unittest2 import skipUnless
else:
from unittest import skipUnless
from unittest import skipUnless

from prometheus_client import Counter
from prometheus_client import CollectorRegistry, generate_latest
Expand Down
4 changes: 1 addition & 3 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tox]
envlist = coverage-clean,py26,py27,py34,py35,py36,pypy,{py27,py36}-nooptionals,coverage-report
envlist = coverage-clean,py27,py34,py35,py36,pypy,{py27,py36}-nooptionals,coverage-report


[base]
Expand All @@ -10,8 +10,6 @@ deps =
[testenv]
deps =
{[base]deps}
py26: unittest2
; Twisted does not support Python 2.6.
{py27,py34,py35,py36,pypy}: twisted
commands = coverage run --parallel -m pytest {posargs}

Expand Down