python-observabilityclient 1.4.0__py3-none-any.whl → 1.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,13 +13,51 @@
13
13
  # under the License.
14
14
 
15
15
  import logging
16
+ import ssl
17
+ import urllib.parse
16
18
 
17
19
  import requests
20
+ from requests.adapters import HTTPAdapter
21
+ from urllib3.util.ssl_ import create_urllib3_context
18
22
 
19
23
 
20
24
  LOG = logging.getLogger(__name__)
21
25
 
22
26
 
27
+ _TLS_VERSIONS = {
28
+ '1.2': ssl.TLSVersion.TLSv1_2,
29
+ '1.3': ssl.TLSVersion.TLSv1_3,
30
+ }
31
+
32
+
33
+ class _PrometheusTLSAdapter(HTTPAdapter):
34
+ """HTTP adapter pinning TLS version bounds on new connections."""
35
+
36
+ def __init__(self, min_version, max_version, verify, **kwargs):
37
+ self._min_version = min_version
38
+ self._max_version = max_version
39
+ # requests/urllib3 set verify_mode and load the CA bundle per request,
40
+ # but CERT_NONE on a context with check_hostname enabled raises, so the
41
+ # context has to be built knowing whether we verify.
42
+ self._cert_reqs = None if verify else ssl.CERT_NONE
43
+ super().__init__(**kwargs)
44
+
45
+ def init_poolmanager(self, *args, **kwargs):
46
+ kwargs['ssl_context'] = create_urllib3_context(
47
+ ssl_minimum_version=self._min_version,
48
+ ssl_maximum_version=self._max_version,
49
+ cert_reqs=self._cert_reqs)
50
+ return super().init_poolmanager(*args, **kwargs)
51
+
52
+
53
+ def _resolve_tls_version(version):
54
+ if version not in _TLS_VERSIONS:
55
+ raise ValueError(
56
+ f"Unknown TLS version: {version}. Supported values are "
57
+ f"{', '.join(sorted(_TLS_VERSIONS))}")
58
+ return _TLS_VERSIONS[version]
59
+
60
+
23
61
  class PrometheusAPIClientError(Exception):
24
62
  def __init__(self, response):
25
63
  self.resp = response
@@ -53,22 +91,47 @@ class PrometheusMetric:
53
91
 
54
92
 
55
93
  class PrometheusAPIClient:
56
- def __init__(self, host, session=None, root_path="", scheme=None):
94
+ def __init__(self, host, session=None, root_path=None, scheme=None):
57
95
  self._scheme = scheme
58
96
  self._host = host
59
- if not self._host.endswith('/'):
60
- self._host += '/'
97
+ self._root_path = root_path or ''
98
+
61
99
  if session is None:
62
100
  self._session = requests.Session()
63
101
  self._session.verify = False
64
102
  else:
65
103
  self._session = session
66
- self._root_path = root_path
67
- if root_path != "" and not self._root_path.endswith('/'):
68
- self._root_path += '/'
104
+ self._min_tls_version = None
105
+ self._max_tls_version = None
69
106
 
70
107
  def set_ca_cert(self, ca_cert):
71
108
  self._session.verify = ca_cert
109
+ self._mount_tls_adapter()
110
+
111
+ def set_min_tls_version(self, version):
112
+ """Set the minimum TLS version for HTTPS connections to Prometheus.
113
+
114
+ :param version: TLS version, ``1.2`` or ``1.3``
115
+ :type version: str
116
+ """
117
+ self._min_tls_version = _resolve_tls_version(version)
118
+ self._mount_tls_adapter()
119
+
120
+ def set_max_tls_version(self, version):
121
+ """Set the maximum TLS version for HTTPS connections to Prometheus.
122
+
123
+ :param version: TLS version, ``1.2`` or ``1.3``
124
+ :type version: str
125
+ """
126
+ self._max_tls_version = _resolve_tls_version(version)
127
+ self._mount_tls_adapter()
128
+
129
+ def _mount_tls_adapter(self):
130
+ if self._min_tls_version is None and self._max_tls_version is None:
131
+ return
132
+ self._session.mount('https://', _PrometheusTLSAdapter(
133
+ self._min_tls_version, self._max_tls_version,
134
+ self._session.verify))
72
135
 
73
136
  def set_client_cert(self, client_cert, client_key):
74
137
  self._session.cert = (client_cert, client_key)
@@ -81,7 +144,11 @@ class PrometheusAPIClient:
81
144
  scheme = 'https' if self._session.verify else 'http'
82
145
  else:
83
146
  scheme = self._scheme
84
- return f"{scheme}://{self._host}{self._root_path}api/v1/{endpoint}"
147
+ components = (scheme, self._host, self._root_path, '', '')
148
+ base_url = urllib.parse.urlunsplit(components)
149
+ if not base_url.endswith('/'):
150
+ base_url += '/'
151
+ return urllib.parse.urljoin(base_url, f'api/v1/{endpoint}')
85
152
 
86
153
  def _get(self, endpoint, params=None):
87
154
  url = self._get_url(endpoint)
@@ -14,6 +14,8 @@
14
14
 
15
15
  from unittest import mock
16
16
 
17
+ import ssl
18
+
17
19
  import requests
18
20
 
19
21
  import testtools
@@ -83,6 +85,62 @@ class PrometheusAPIClientTestBase(testtools.TestCase):
83
85
 
84
86
 
85
87
  class PrometheusAPIClientTest(PrometheusAPIClientTestBase):
88
+ def _ssl_context(self, c):
89
+ adapter = c._session.get_adapter("https://localhost:9090/")
90
+ self.assertIsInstance(adapter, client._PrometheusTLSAdapter)
91
+ return adapter.poolmanager.connection_pool_kw['ssl_context']
92
+
93
+ def test_set_min_tls_version(self):
94
+ c = client.PrometheusAPIClient("localhost:9090")
95
+ c.set_min_tls_version("1.2")
96
+ ctx = self._ssl_context(c)
97
+ self.assertEqual(ssl.TLSVersion.TLSv1_2, ctx.minimum_version)
98
+ # verify is False by default, so the context must not demand certs
99
+ self.assertEqual(ssl.CERT_NONE, ctx.verify_mode)
100
+
101
+ def test_set_min_tls_version_with_ca_cert(self):
102
+ c = client.PrometheusAPIClient("localhost:9090")
103
+ c.set_ca_cert(True)
104
+ c.set_min_tls_version("1.3")
105
+ ctx = self._ssl_context(c)
106
+ self.assertEqual(ssl.TLSVersion.TLSv1_3, ctx.minimum_version)
107
+ self.assertEqual(ssl.CERT_REQUIRED, ctx.verify_mode)
108
+ self.assertTrue(ctx.check_hostname)
109
+
110
+ def test_set_min_tls_version_invalid(self):
111
+ c = client.PrometheusAPIClient("localhost:9090")
112
+ self.assertRaises(ValueError, c.set_min_tls_version, "TLSv1_2")
113
+ self.assertRaises(ValueError, c.set_min_tls_version, "1.1")
114
+
115
+ def test_set_max_tls_version(self):
116
+ c = client.PrometheusAPIClient("localhost:9090")
117
+ c.set_max_tls_version("1.2")
118
+ ctx = self._ssl_context(c)
119
+ self.assertEqual(ssl.TLSVersion.TLSv1_2, ctx.maximum_version)
120
+ self.assertEqual(ssl.CERT_NONE, ctx.verify_mode)
121
+
122
+ def test_set_max_tls_version_with_ca_cert(self):
123
+ c = client.PrometheusAPIClient("localhost:9090")
124
+ c.set_ca_cert(True)
125
+ c.set_max_tls_version("1.3")
126
+ ctx = self._ssl_context(c)
127
+ self.assertEqual(ssl.TLSVersion.TLSv1_3, ctx.maximum_version)
128
+ self.assertEqual(ssl.CERT_REQUIRED, ctx.verify_mode)
129
+ self.assertTrue(ctx.check_hostname)
130
+
131
+ def test_set_min_and_max_tls_version(self):
132
+ c = client.PrometheusAPIClient("localhost:9090")
133
+ c.set_min_tls_version("1.2")
134
+ c.set_max_tls_version("1.3")
135
+ ctx = self._ssl_context(c)
136
+ self.assertEqual(ssl.TLSVersion.TLSv1_2, ctx.minimum_version)
137
+ self.assertEqual(ssl.TLSVersion.TLSv1_3, ctx.maximum_version)
138
+
139
+ def test_set_max_tls_version_invalid(self):
140
+ c = client.PrometheusAPIClient("localhost:9090")
141
+ self.assertRaises(ValueError, c.set_max_tls_version, "TLSv1_2")
142
+ self.assertRaises(ValueError, c.set_max_tls_version, "1.1")
143
+
86
144
  def test_init_scheme_default(self):
87
145
  c = client.PrometheusAPIClient("localhost:9090")
88
146
  self.assertIsNone(c._scheme)
@@ -57,7 +57,7 @@ class GetPrometheusClientTest(testtools.TestCase):
57
57
  mock.patch.object(prometheus_client.PrometheusAPIClient,
58
58
  "__init__", return_value=None) as m:
59
59
  metric_utils.get_prometheus_client()
60
- m.assert_called_with("somehost:1234", None, "")
60
+ m.assert_called_with("somehost:1234", None, None)
61
61
 
62
62
  def test_get_prometheus_client_env_override(self):
63
63
  with mock.patch.dict(os.environ,
@@ -67,7 +67,7 @@ class GetPrometheusClientTest(testtools.TestCase):
67
67
  mock.patch.object(prometheus_client.PrometheusAPIClient,
68
68
  "__init__", return_value=None) as m:
69
69
  metric_utils.get_prometheus_client()
70
- m.assert_called_with("env_override:1234", None, "")
70
+ m.assert_called_with("env_override:1234", None, None)
71
71
 
72
72
  def test_get_prometheus_client_no_config_file(self):
73
73
  patched_env = {'PROMETHEUS_HOST': 'env_override',
@@ -78,7 +78,7 @@ class GetPrometheusClientTest(testtools.TestCase):
78
78
  mock.patch.object(prometheus_client.PrometheusAPIClient,
79
79
  "__init__", return_value=None) as m:
80
80
  metric_utils.get_prometheus_client()
81
- m.assert_called_with("env_override:env_port", None, "")
81
+ m.assert_called_with("env_override:env_port", None, None)
82
82
 
83
83
  def test_get_prometheus_client_prefix_in_env_variable(self):
84
84
  patched_env = {'PROMETHEUS_HOST': 'env_override',
@@ -148,7 +148,7 @@ class GetPrometheusClientTest(testtools.TestCase):
148
148
  mock.patch.object(prometheus_client.PrometheusAPIClient,
149
149
  "__init__", return_value=None) as m:
150
150
  metric_utils.get_prometheus_client()
151
- m.assert_called_with("[2607:5300:201:2000::654]:1234", None, "")
151
+ m.assert_called_with("[2607:5300:201:2000::654]:1234", None, None)
152
152
 
153
153
  def test_get_prometheus_client_from_conf_file_ipv6(self):
154
154
  config_data = '''
@@ -163,7 +163,7 @@ class GetPrometheusClientTest(testtools.TestCase):
163
163
  "__init__", return_value=None) as init_m:
164
164
  metric_utils.get_prometheus_client()
165
165
  init_m.assert_called_with(
166
- "[2607:5300:201:2000::654]:80", None, ""
166
+ "[2607:5300:201:2000::654]:80", None, None
167
167
  )
168
168
 
169
169
  def test_get_prometheus_client_from_keystone_ipv6(self):
@@ -70,32 +70,30 @@ def get_prom_client_from_keystone(session, adapter_options=None):
70
70
 
71
71
 
72
72
  def get_prom_client_from_file_or_env():
73
- host = port = ca_cert = None
74
- root_path = ''
75
- conf_file = get_config_file()
76
- if conf_file is not None:
77
- conf = yaml.safe_load(conf_file)
78
- if 'host' in conf:
79
- host = conf['host']
80
- if 'port' in conf:
81
- port = conf['port']
82
- if 'ca_cert' in conf:
83
- ca_cert = conf['ca_cert']
84
- if 'root_path' in conf:
85
- root_path = conf['root_path']
86
- conf_file.close()
87
- if 'PROMETHEUS_HOST' in os.environ:
88
- host = os.environ['PROMETHEUS_HOST']
89
- if 'PROMETHEUS_PORT' in os.environ:
90
- port = os.environ['PROMETHEUS_PORT']
91
- if 'PROMETHEUS_CA_CERT' in os.environ:
92
- ca_cert = os.environ['PROMETHEUS_CA_CERT']
93
- if 'PROMETHEUS_ROOT_PATH' in os.environ:
94
- root_path = os.environ['PROMETHEUS_ROOT_PATH']
95
- if host is None or port is None:
96
- raise ConfigurationError("Can't find prometheus host and "
97
- "port configuration in config file or "
98
- "environment variables.")
73
+ host = ca_cert = root_path = None
74
+ port = 9090
75
+ try:
76
+ conf_file = get_config_file()
77
+ if conf_file is not None:
78
+ conf = yaml.safe_load(conf_file)
79
+ host = conf.get('host', host)
80
+ port = conf.get('port', port)
81
+ ca_cert = conf.get('ca_cert', ca_cert)
82
+ root_path = conf.get('root_path', root_path)
83
+ finally:
84
+ if conf_file is not None:
85
+ conf_file.close()
86
+
87
+ host = os.environ.get('PROMETHEUS_HOST', host)
88
+ port = os.environ.get('PROMETHEUS_PORT', port)
89
+ ca_cert = os.environ.get('PROMETHEUS_CA_CERT', ca_cert)
90
+ root_path = os.environ.get('PROMETHEUS_ROOT_PATH', root_path)
91
+
92
+ if host is None:
93
+ raise ConfigurationError(
94
+ "Can't find prometheus host configuration in config file or "
95
+ "environment variables.")
96
+
99
97
  escaped_host = netutils.escape_ipv6(host)
100
98
  client = PrometheusAPIClient(
101
99
  f"{escaped_host}:{port}", None, root_path
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-observabilityclient
3
- Version: 1.4.0
3
+ Version: 1.5.0
4
4
  Summary: OpenStack Observability Client
5
5
  Author-email: OpenStack <openstack-discuss@lists.openstack.org>
6
6
  License: Apache-2.0
@@ -17,6 +17,7 @@ Classifier: Programming Language :: Python :: 3.11
17
17
  Classifier: Programming Language :: Python :: 3.12
18
18
  Classifier: Programming Language :: Python :: 3.13
19
19
  Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3.15
20
21
  Classifier: Programming Language :: Python :: 3 :: Only
21
22
  Requires-Python: >=3.11
22
23
  Description-Content-Type: text/markdown; charset=UTF-8
@@ -48,6 +49,7 @@ Install your OpenStack environment and patch your ``openstack`` client
48
49
  application using python.
49
50
 
50
51
  .. code:: console
52
+
51
53
  git clone https://opendev.org/openstack/python-observabilityclient.git
52
54
  cd python-observabilityclient
53
55
  sudo pip install .
@@ -61,6 +63,7 @@ Use ``openstack metric query somequery`` to query for metrics in prometheus.
61
63
  To use the python api do the following:
62
64
 
63
65
  .. code:: python
66
+
64
67
  from observabilityclient import client
65
68
 
66
69
  c = client.Client(
@@ -2,7 +2,7 @@ observabilityclient/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSu
2
2
  observabilityclient/client.py,sha256=cfRb816p6Ips9t2cdWvmSJ1uGrtTEHXQnctoExrLA5A,828
3
3
  observabilityclient/i18n.py,sha256=PFo6BaOfyGQD5q7L3FunYJ8d4mwbRszG8wOrJIjki_4,790
4
4
  observabilityclient/plugin.py,sha256=fxUDNvo_2UrG_tM-IsgBNWAKCrWwvixhqbWt0QktH4A,2262
5
- observabilityclient/prometheus_client.py,sha256=bxHGTbdteD7h0JBV7IekTU02bUXFbR_P_R9pXweO-ZE,7548
5
+ observabilityclient/prometheus_client.py,sha256=TdItnmBmTP9qy_pjEwsZ66nMXzKgThgpeFIxkX80mdc,9940
6
6
  observabilityclient/rbac.py,sha256=b71bi0Ls6lUBL3RE1az5ih98DiPMoqF43SPgQkosSqE,7807
7
7
  observabilityclient/tests/functional/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
8
  observabilityclient/tests/functional/base.py,sha256=FZT3C50z199-7SwgeGEMzxHLnbPqqB4GcHWbdobDLb8,6493
@@ -10,22 +10,22 @@ observabilityclient/tests/functional/test_cli.py,sha256=jwhgt8w0gq1CdDoaDKLV8SB_
10
10
  observabilityclient/tests/functional/test_python_api.py,sha256=5TLFboJ7B__UZ9zfc6bVSxPTzV9KnnrwluTqLwnTZLs,3308
11
11
  observabilityclient/tests/unit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
12
  observabilityclient/tests/unit/test_cli.py,sha256=Li3QNEp6mWC758aEVL0yC6JUXv2KKtYgDfWfGLPg4xo,6178
13
- observabilityclient/tests/unit/test_prometheus_client.py,sha256=u2te9c8CE5bR6FCI9pYi7jtPsqBiPa2HVshXUQMeYy0,20105
13
+ observabilityclient/tests/unit/test_prometheus_client.py,sha256=Fo3nfxwZymIoYOTMPSUo2c-7GYnm1kIn-KKKr8tWntQ,22643
14
14
  observabilityclient/tests/unit/test_python_api.py,sha256=cgpBwRR9KsCzfKC8OhE8Gm4OCirEobYnXDlK6e_4io4,4719
15
15
  observabilityclient/tests/unit/test_rbac.py,sha256=88mAxgOiTnKDrOGqb3Kt1SiqyeC4voYmDvvkWT1kVhw,8992
16
- observabilityclient/tests/unit/test_utils.py,sha256=xyjMjJIK5ofx9Urx-R39y-q1BPof_y-k-ocXcMOKen4,12529
16
+ observabilityclient/tests/unit/test_utils.py,sha256=J1V3QPcDf81qZ8RAlz_p1gAjRfC5pR_KqwMhMAb-wg0,12539
17
17
  observabilityclient/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
- observabilityclient/utils/metric_utils.py,sha256=Gp7Ai4WzROEDF0txEEPBmMEmuzTy1njU4HJ7TxZt5Vo,5709
18
+ observabilityclient/utils/metric_utils.py,sha256=0tXdbNBsY1hM7oU85YBqG1BkN0_t0-TIOq4ODBiFNNY,5513
19
19
  observabilityclient/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
20
  observabilityclient/v1/base.py,sha256=UfrHeow54fkJ1tWCNhKieKCPrSg1HiCLxJ_QpUOBb0w,2905
21
21
  observabilityclient/v1/cli.py,sha256=ln7GsnbW95n90oFGw4zLiwHDjY0YHBxkRBzID-j6ZmA,4028
22
22
  observabilityclient/v1/client.py,sha256=AFJkyvBEPvYAKIH-55BGiac8Z73Iasg3Q56NPEk11hc,1747
23
23
  observabilityclient/v1/python_api.py,sha256=GA5R5BezVbdT-Mnl9Nmg3kAlUuFl5sLrENlRQHXz_Vs,3886
24
- python_observabilityclient-1.4.0.dist-info/licenses/AUTHORS,sha256=TZPAY_mWGQ7oo86HOdjZU566EU_vInwz1QWmymMAFw8,678
25
- python_observabilityclient-1.4.0.dist-info/licenses/LICENSE,sha256=qyh9xnj_IPtYWzClm5mZxCWRKTr2eUP_iLcU28DIvCw,11343
26
- python_observabilityclient-1.4.0.dist-info/METADATA,sha256=kkB8dx5in8lhrYxx1nevQRjj7Q1lCz5SuogkfNsVI7E,3145
27
- python_observabilityclient-1.4.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
28
- python_observabilityclient-1.4.0.dist-info/entry_points.txt,sha256=15rmai80pMRfBKZrk6yPNrRkAs2h63bwlcbQKq9fax4,424
29
- python_observabilityclient-1.4.0.dist-info/pbr.json,sha256=SpW49bfnvklqlyuRqz3Lv-iLvqR87m6UZCJ9-Q-Bo9U,46
30
- python_observabilityclient-1.4.0.dist-info/top_level.txt,sha256=Lf7Fwm3hfK-X1JNRy19rVlrMUOyQShBBPwsCU3pz6yw,20
31
- python_observabilityclient-1.4.0.dist-info/RECORD,,
24
+ python_observabilityclient-1.5.0.dist-info/licenses/AUTHORS,sha256=0Ik9nTv4r5GnmW-vgQDuYmfsybCco2MS14GSDnCAHHc,713
25
+ python_observabilityclient-1.5.0.dist-info/licenses/LICENSE,sha256=qyh9xnj_IPtYWzClm5mZxCWRKTr2eUP_iLcU28DIvCw,11343
26
+ python_observabilityclient-1.5.0.dist-info/METADATA,sha256=vlRNd4FsEGY3JdB8l9MUrWwe4f8UGqkIc35c3LtJFZ4,3198
27
+ python_observabilityclient-1.5.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
28
+ python_observabilityclient-1.5.0.dist-info/entry_points.txt,sha256=15rmai80pMRfBKZrk6yPNrRkAs2h63bwlcbQKq9fax4,424
29
+ python_observabilityclient-1.5.0.dist-info/pbr.json,sha256=2tjKz1d-CcEMITZhsvxffmrrLWhc40aFP1O6obb2syI,46
30
+ python_observabilityclient-1.5.0.dist-info/top_level.txt,sha256=Lf7Fwm3hfK-X1JNRy19rVlrMUOyQShBBPwsCU3pz6yw,20
31
+ python_observabilityclient-1.5.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,6 +1,7 @@
1
1
  Alfredo Moralejo <amoralej@redhat.com>
2
2
  Chris Sibbitt <csibbitt@redhat.com>
3
3
  Cyril Roelandt <cyril@redhat.com>
4
+ Daniel Pawlik <dpawlik@redhat.com>
4
5
  Emma Foley <efoley@redhat.com>
5
6
  Erno Kuvaja <jokke@usr.fi>
6
7
  Ghanshyam Mann <gmann@ghanshyammann.com>
@@ -0,0 +1 @@
1
+ {"git_version": "8ba76b1", "is_release": true}
@@ -1 +0,0 @@
1
- {"git_version": "3c745ef", "is_release": true}