6 from dnsdisttests
import DNSDistTest
8 @unittest.skipIf('SKIP_PROMETHEUS_TESTS' in os
.environ
, 'Prometheus tests are disabled')
9 class TestPrometheus(DNSDistTest
):
13 _webServerBasicAuthPassword
= 'secret'
14 _webServerAPIKey
= 'apisecret'
15 _config_params
= ['_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey']
16 _config_template
= """
17 newServer{address="127.0.0.1:%s"}
18 webserver("127.0.0.1:%s", "%s", "%s")
21 def checkPrometheusContentBasic(self
, content
):
22 for line
in content
.splitlines():
23 if line
.startswith('# HELP'):
24 tokens
= line
.split(' ')
25 self
.assertGreaterEqual(len(tokens
), 4)
26 elif line
.startswith('# TYPE'):
27 tokens
= line
.split(' ')
28 self
.assertEquals(len(tokens
), 4)
29 self
.assertIn(tokens
[3], ['counter', 'gauge', 'histogram'])
30 elif not line
.startswith('#'):
31 tokens
= line
.split(' ')
32 self
.assertEquals(len(tokens
), 2)
33 if not line
.startswith('dnsdist_'):
34 raise AssertionError('Expecting prometheus metric to be prefixed by \'dnsdist_\', got: "%s"' % (line
))
36 def checkPrometheusContentPromtool(self
, content
):
39 testcmd
= ['promtool', 'check', 'metrics']
40 process
= subprocess
.Popen(testcmd
, stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
, stderr
=subprocess
.STDOUT
, close_fds
=True)
41 output
= process
.communicate(input=content
)
42 except subprocess
.CalledProcessError
as exc
:
43 raise AssertionError('%s failed (%d): %s' % (testcmd
, process
.returncode
, process
.output
))
45 # commented out because promtool returns 3 because of the "_total" suffix warnings
46 #if process.returncode != 0:
47 # raise AssertionError('%s failed (%d): %s' % (testcmd, process.returncode, output))
49 for line
in output
[0].splitlines():
50 if line
.endswith(b
"should have \"_total\" suffix"):
52 raise AssertionError('%s returned an unexpected output. Faulty line is "%s", complete content is "%s"' % (testcmd
, line
, output
))
54 def testMetrics(self
):
56 Prometheus: Retrieve metrics
58 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/metrics'
59 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPassword
), timeout
=self
._webTimeout
)
61 self
.assertEquals(r
.status_code
, 200)
62 self
.checkPrometheusContentBasic(r
.text
)
63 self
.checkPrometheusContentPromtool(r
.content
)