python-observabilityclient 0.5.0__py3-none-any.whl → 1.1.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.
@@ -18,10 +18,24 @@ from observabilityclient.utils.metric_utils import format_labels
18
18
 
19
19
 
20
20
  class PromQLRbac(object):
21
- def __init__(self, prom_api_client, project_id):
21
+ def __init__(self, prom_api_client, project_id, project_label='project'):
22
22
  self.client = prom_api_client
23
+
24
+ # NOTE(jwysogla): Since Prometheus 3, metric and label names can
25
+ # utilize all unicode characters. But the syntax is a little different
26
+ # and some parts of the queries need to be quoted or escaped. The
27
+ # rest of this module doesn't support that right now, so use a
28
+ # Prometheus 2 regex and raise an exception when it doesn't match.
29
+ # See https://prometheus.io/docs/concepts/data_model/
30
+ label_name_regex = "[a-zA-Z_][a-zA-Z0-9_]*"
31
+ if not re.fullmatch(label_name_regex, project_label):
32
+ raise ValueError(
33
+ f"Project label {project_label} doesn't match the "
34
+ f"label name regex: {label_name_regex}"
35
+ )
36
+
23
37
  self.labels = {
24
- "project": project_id
38
+ project_label: project_id
25
39
  }
26
40
 
27
41
  def _find_label_value_end(self, query, start, quote_char):
@@ -83,14 +97,27 @@ class PromQLRbac(object):
83
97
  f"{labels_str}"
84
98
  f"{query[location:]}")
85
99
 
86
- def modify_query(self, query):
100
+ def modify_query(self, query, metric_names=None):
87
101
  """Add rbac labels to a query.
88
102
 
89
103
  :param query: The query to modify
90
104
  :type query: str
105
+
106
+ :param metric_names: List of metric names currently stored in
107
+ prometheus. For correct function of the query
108
+ modification, it's important for the list to be
109
+ accurate and to include all metrics across all
110
+ tenants. This parameter can be unspecified or
111
+ None, in which case the list will be retrieved
112
+ from Prometheus by sending an API request to it.
113
+ It's advised to provide the metric list when
114
+ doing a query modification in a loop for
115
+ performance purposes.
116
+ :type metric_names: list
91
117
  """
92
- # We need to get all metric names, no matter the rbac
93
- metric_names = self.client.label_values("__name__")
118
+
119
+ if metric_names is None:
120
+ metric_names = self.client.label_values("__name__")
94
121
 
95
122
  # We need to detect the locations of metric names
96
123
  # inside the query
@@ -111,7 +138,7 @@ class PromQLRbac(object):
111
138
  name_end_locations = [0]
112
139
  for name_end_location in name_end_locations:
113
140
  if (name_end_location < len(query) and
114
- query[name_end_location] == "{"):
141
+ query[name_end_location] == "{"):
115
142
  # There is already a label section
116
143
  labels_end = self._find_label_section_end(
117
144
  query,
@@ -22,7 +22,7 @@ from observabilityclient import client
22
22
 
23
23
  from keystoneauth1 import loading
24
24
  from keystoneauth1 import session
25
- import os_client_config
25
+ from openstack import config as occ
26
26
  from tempest.lib.cli import output_parser
27
27
  from tempest.lib import exceptions
28
28
  import testtools
@@ -33,8 +33,8 @@ LOG = logging.getLogger(__name__)
33
33
 
34
34
  class PythonAPITestCase(testtools.TestCase):
35
35
  def _getKeystoneSession(self):
36
- conf = os_client_config.OpenStackConfig()
37
- creds = conf.get_one_cloud(cloud=ADMIN_CLOUD).get_auth_args()
36
+ conf = occ.OpenStackConfig()
37
+ creds = conf.get_one(cloud=ADMIN_CLOUD).get_auth_args()
38
38
  ks_creds = dict(
39
39
  auth_url=creds["auth_url"],
40
40
  username=creds["username"],
@@ -14,98 +14,56 @@ from observabilityclient.tests.functional import base
14
14
  import time
15
15
 
16
16
 
17
- class CliTestFunctionalRBACDisabled(base.CliTestCase):
18
- """Functional tests for cli commands with disabled RBAC."""
17
+ class CliTestFunctionalRBACNOOP(base.CliTestCase):
18
+ """Functional tests for cli commands testing RBAC option."""
19
19
 
20
20
  def test_list(self):
21
- cmd_output = self.openstack(
22
- 'metric list --disable-rbac',
23
- parse_output=True,
24
- )
25
- name_list = [item.get('metric_name') for item in cmd_output]
26
- self.assertIn(
27
- 'up',
28
- name_list
29
- )
30
-
31
- def test_show(self):
32
- cmd_output = self.openstack(
33
- 'metric show up --disable-rbac',
34
- parse_output=True,
35
- )
36
- for metric in cmd_output:
37
- self.assertEqual(
38
- "up",
39
- metric["__name__"]
21
+ for cmdstr in ('metric list', 'metric list --disable-rbac'):
22
+ cmd_output = self.openstack(
23
+ cmdstr,
24
+ parse_output=True,
40
25
  )
41
- self.assertEqual(
42
- "1",
43
- metric["value"]
26
+ name_list = [item.get('metric_name') for item in cmd_output]
27
+ self.assertIn(
28
+ 'ceilometer_image_size',
29
+ name_list
44
30
  )
45
-
46
- def test_query(self):
47
- cmd_output = self.openstack(
48
- 'metric query up --disable-rbac',
49
- parse_output=True,
50
- )
51
- for metric in cmd_output:
52
- self.assertEqual(
53
- "up",
54
- metric["__name__"]
55
- )
56
- self.assertEqual(
57
- "1",
58
- metric["value"]
31
+ self.assertIn(
32
+ 'up',
33
+ name_list
59
34
  )
60
35
 
61
-
62
- class CliTestFunctionalRBACEnabled(base.CliTestCase):
63
- """Functional tests for cli commands with enabled RBAC."""
64
-
65
- def test_list(self):
66
- cmd_output = self.openstack(
67
- 'metric list',
68
- parse_output=True,
69
- )
70
- name_list = [item.get('metric_name') for item in cmd_output]
71
- self.assertIn(
72
- 'ceilometer_image_size',
73
- name_list
74
- )
75
- self.assertNotIn(
76
- 'up',
77
- name_list
78
- )
79
-
80
36
  def test_show(self):
81
- cmd_output = self.openstack(
82
- 'metric show ceilometer_image_size',
83
- parse_output=True,
84
- )
85
- for metric in cmd_output:
86
- self.assertEqual(
87
- "ceilometer_image_size",
88
- metric["__name__"]
89
- )
90
- self.assertEqual(
91
- "sg-core",
92
- metric["job"]
37
+ for cmdstr in ('metric show up', 'metric show up --disable-rbac'):
38
+ cmd_output = self.openstack(
39
+ cmdstr,
40
+ parse_output=True,
93
41
  )
42
+ for metric in cmd_output:
43
+ self.assertEqual(
44
+ "up",
45
+ metric["__name__"]
46
+ )
47
+ self.assertEqual(
48
+ "1",
49
+ metric["value"]
50
+ )
94
51
 
95
52
  def test_query(self):
96
- cmd_output = self.openstack(
97
- 'metric query ceilometer_image_size',
98
- parse_output=True,
99
- )
100
- for metric in cmd_output:
101
- self.assertEqual(
102
- "ceilometer_image_size",
103
- metric["__name__"]
104
- )
105
- self.assertEqual(
106
- "sg-core",
107
- metric["job"]
53
+ for cmdstr in ('metric query up', 'metric query up --disable-rbac'):
54
+ cmd_output = self.openstack(
55
+ cmdstr,
56
+ parse_output=True,
108
57
  )
58
+ for metric in cmd_output:
59
+ self.assertEqual(
60
+ "up",
61
+ metric["__name__"]
62
+ )
63
+ self.assertEqual(
64
+ "1",
65
+ metric["value"]
66
+ )
109
67
 
110
68
 
111
69
  class CliTestFunctionalAdminCommands(base.CliTestCase):
@@ -52,7 +52,7 @@ class PythonAPITestFunctionalRBACEnabled(base.PythonAPITestCase):
52
52
  for metric in ret:
53
53
  self.assertEqual("ceilometer_image_size",
54
54
  metric.labels["__name__"])
55
- self.assertEqual("sg-core",
55
+ self.assertEqual("custom",
56
56
  metric.labels["job"])
57
57
 
58
58
  def test_query(self):
@@ -62,7 +62,7 @@ class PythonAPITestFunctionalRBACEnabled(base.PythonAPITestCase):
62
62
  for metric in ret:
63
63
  self.assertEqual("ceilometer_image_size",
64
64
  metric.labels["__name__"])
65
- self.assertEqual("sg-core", metric.labels["job"])
65
+ self.assertEqual("custom", metric.labels["job"])
66
66
 
67
67
 
68
68
  class PythonAPITestFunctionalAdminCommands(base.PythonAPITestCase):
@@ -43,8 +43,9 @@ class CliTest(testtools.TestCase):
43
43
  return_value=self.client), \
44
44
  mock.patch.object(self.client.query, 'list',
45
45
  return_value=metric_names) as m:
46
+ # NOTE: disable-rbac option is NOOP, RBAC is disabled by default
46
47
  ret1 = cli_list.take_action(test_parsed_args_enabled)
47
- m.assert_called_with(disable_rbac=False)
48
+ m.assert_called_with(disable_rbac=True)
48
49
 
49
50
  ret2 = cli_list.take_action(test_parsed_args_disabled)
50
51
  m.assert_called_with(disable_rbac=True)
@@ -75,9 +76,9 @@ class CliTest(testtools.TestCase):
75
76
  return_value=self.client), \
76
77
  mock.patch.object(self.client.query, 'show',
77
78
  return_value=prom_metric) as m:
78
-
79
+ # NOTE: disable-rbac option is NOOP, RBAC is disabled by default
79
80
  ret1 = cli_show.take_action(test_parsed_args_enabled)
80
- m.assert_called_with('metric_name', disable_rbac=False)
81
+ m.assert_called_with('metric_name', disable_rbac=True)
81
82
 
82
83
  ret2 = cli_show.take_action(test_parsed_args_disabled)
83
84
  m.assert_called_with('metric_name', disable_rbac=True)
@@ -113,8 +114,9 @@ class CliTest(testtools.TestCase):
113
114
  mock.patch.object(self.client.query, 'query',
114
115
  return_value=prom_metric) as m:
115
116
 
117
+ # NOTE: disable-rbac option is NOOP, RBAC is disabled by default
116
118
  ret1 = cli_query.take_action(test_parsed_args_enabled)
117
- m.assert_called_with(query, disable_rbac=False)
119
+ m.assert_called_with(query, disable_rbac=True)
118
120
 
119
121
  ret2 = cli_query.take_action(test_parsed_args_disabled)
120
122
  m.assert_called_with(query, disable_rbac=True)
@@ -40,33 +40,16 @@ class QueryManagerTest(testtools.TestCase):
40
40
  self.client.query = self.manager
41
41
 
42
42
  def test_list(self):
43
- returned_by_prom_rbac = {
44
- 'data': [
45
- {
46
- '__name__': 'metric1',
47
- 'label1': 'foo'
48
- },
49
- {
50
- '__name__': 'test42',
51
- 'anotherlabel': 'bar'
52
- },
53
- {
54
- '__name__': 'abc2',
55
- }
56
- ]
57
- }
58
- returned_by_prom_no_rbac = {'data': ['metric1', 'test42', 'abc2']}
43
+ returned_data = {'data': ['metric1', 'test42', 'abc2']}
59
44
  expected = ['abc2', 'metric1', 'test42']
60
45
 
61
46
  with mock.patch.object(prometheus_client.PrometheusAPIClient, '_get',
62
- return_value=returned_by_prom_rbac):
47
+ return_value=returned_data):
63
48
  ret1 = self.manager.list()
64
- self.assertEqual(expected, ret1)
49
+ self.assertEqual(expected, ret1)
65
50
 
66
- with mock.patch.object(prometheus_client.PrometheusAPIClient, '_get',
67
- return_value=returned_by_prom_no_rbac):
68
51
  ret2 = self.manager.list(disable_rbac=True)
69
- self.assertEqual(expected, ret2)
52
+ self.assertEqual(expected, ret2)
70
53
 
71
54
  def test_show(self):
72
55
  query = 'some_metric'
@@ -90,7 +73,7 @@ class QueryManagerTest(testtools.TestCase):
90
73
  with mock.patch.object(prometheus_client.PrometheusAPIClient, '_get',
91
74
  return_value=returned_by_prom):
92
75
  ret1 = self.manager.show(query)
93
- self.rbac.append_rbac_labels.assert_called_with(query)
76
+ self.rbac.append_rbac_labels.assert_not_called()
94
77
 
95
78
  self.assertThat(ret1, expected_matcher)
96
79
  self.assertThat(ret2, expected_matcher)
@@ -118,7 +101,7 @@ class QueryManagerTest(testtools.TestCase):
118
101
  self.rbac.modify_query.assert_not_called()
119
102
 
120
103
  ret2 = self.manager.query(query)
121
- self.rbac.modify_query.assert_called_with(query)
104
+ self.rbac.modify_query.assert_not_called()
122
105
 
123
106
  self.assertThat(ret1, expected_matcher)
124
107
  self.assertThat(ret2, expected_matcher)
@@ -27,15 +27,17 @@ class PromQLRbacTest(testtools.TestCase):
27
27
  self.rbac.labels = {
28
28
  "project": "project123"
29
29
  }
30
- self.rbac.client.label_values = lambda label: [
31
- 'test_query',
32
- 'cpu_temp_celsius',
33
- 'http_requests',
34
- 'test:query:with:colon:',
35
- 'test_query_with_digit1',
36
- 'method_code:http_errors:rate5m',
37
- 'method:http_requests:rate5m'
38
- ]
30
+ self.rbac.client.label_values = mock.MagicMock(
31
+ return_value=[
32
+ 'test_query',
33
+ 'cpu_temp_celsius',
34
+ 'http_requests',
35
+ 'test:query:with:colon:',
36
+ 'test_query_with_digit1',
37
+ 'method_code:http_errors:rate5m',
38
+ 'method:http_requests:rate5m'
39
+ ]
40
+ )
39
41
  self.test_cases = [
40
42
  (
41
43
  "test_query",
@@ -167,6 +169,12 @@ class PromQLRbacTest(testtools.TestCase):
167
169
  f"{{project='{self.project_id}'}}"
168
170
  f"[10m])))"
169
171
  )
172
+ ), (
173
+ "test_query{project='some_id'}",
174
+
175
+ (f"test_query{{project='some_id', "
176
+ f"project='{self.project_id}'}}"
177
+ )
170
178
  )
171
179
  ]
172
180
 
@@ -186,3 +194,64 @@ class PromQLRbacTest(testtools.TestCase):
186
194
  expected = f"{query}{{project='{self.project_id}'}}"
187
195
  ret = self.rbac.append_rbac_labels(query)
188
196
  self.assertEqual(expected, ret)
197
+
198
+ def test_setting_different_project_label_name(self):
199
+ query = 'test_query'
200
+ project_label = 'different_name'
201
+ project_value = 'some_project'
202
+
203
+ rbac_instance = rbac.PromQLRbac(
204
+ mock.Mock(), project_value, project_label=project_label
205
+ )
206
+ rbac_instance.client.label_values = lambda label: [
207
+ query,
208
+ ]
209
+
210
+ expected = f"{query}{{{project_label}='{project_value}'}}"
211
+
212
+ ret = rbac_instance.modify_query(query)
213
+
214
+ self.assertEqual(expected, ret)
215
+
216
+ def test_setting_illegal_project_label_name(self):
217
+ # Try setting a label name with a white space character inside
218
+ project_label = 'different name'
219
+ project_value = 'some_project'
220
+
221
+ args = (mock.Mock(), project_value)
222
+ kwargs = {'project_label': project_label}
223
+
224
+ self.assertRaises(ValueError, rbac.PromQLRbac, *args, **kwargs)
225
+
226
+ # Try setting an empty label name
227
+ project_label = ''
228
+
229
+ kwargs = {'project_label': project_label}
230
+
231
+ self.assertRaises(ValueError, rbac.PromQLRbac, *args, **kwargs)
232
+
233
+ def test_specifying_metric_names(self):
234
+ query = "test_query"
235
+ metric_names = [
236
+ "metric_name1",
237
+ "foo",
238
+ "bar",
239
+ "test_query"
240
+ ]
241
+
242
+ expected = "test_query{project='project123'}"
243
+
244
+ ret = self.rbac.modify_query(query, metric_names)
245
+
246
+ self.assertEqual(expected, ret)
247
+ self.rbac.client.label_values.assert_not_called()
248
+
249
+ def test_not_specifying_metric_names(self):
250
+ query = "test_query"
251
+
252
+ expected = "test_query{project='project123'}"
253
+
254
+ ret = self.rbac.modify_query(query)
255
+
256
+ self.assertEqual(expected, ret)
257
+ self.rbac.client.label_values.assert_called_once()
@@ -15,6 +15,8 @@
15
15
  import os
16
16
  from unittest import mock
17
17
 
18
+ from keystoneauth1 import adapter
19
+ from keystoneauth1 import session
18
20
  import testtools
19
21
 
20
22
  from observabilityclient import prometheus_client
@@ -99,6 +101,87 @@ class GetPrometheusClientTest(testtools.TestCase):
99
101
  self.assertRaises(metric_utils.ConfigurationError,
100
102
  metric_utils.get_prometheus_client)
101
103
 
104
+ def test_get_prometheus_client_from_keystone_http(self):
105
+ prom_endpoint = "http://localhost:1234/prometheus"
106
+ keystone_session = session.Session()
107
+ with mock.patch.dict(os.environ, {}), \
108
+ mock.patch.object(metric_utils, 'get_config_file',
109
+ return_value=None), \
110
+ mock.patch.object(adapter.Adapter, 'get_endpoint',
111
+ return_value=prom_endpoint), \
112
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
113
+ "__init__", return_value=None) as init_m, \
114
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
115
+ "set_ca_cert") as ca_m:
116
+ metric_utils.get_prometheus_client(keystone_session)
117
+ init_m.assert_called_with(
118
+ "localhost:1234", keystone_session, "prometheus"
119
+ )
120
+ ca_m.assert_not_called()
121
+
122
+ def test_get_prometheus_client_from_keystone_https(self):
123
+ prom_endpoint = "https://localhost:1234/prometheus"
124
+ keystone_session = session.Session()
125
+ with mock.patch.dict(os.environ, {}), \
126
+ mock.patch.object(metric_utils, 'get_config_file',
127
+ return_value=None), \
128
+ mock.patch.object(adapter.Adapter, 'get_endpoint',
129
+ return_value=prom_endpoint), \
130
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
131
+ "__init__", return_value=None) as init_m, \
132
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
133
+ "set_ca_cert") as ca_m:
134
+ metric_utils.get_prometheus_client(keystone_session)
135
+ init_m.assert_called_with(
136
+ "localhost:1234", keystone_session, "prometheus"
137
+ )
138
+ ca_m.assert_called_with(True)
139
+
140
+ def test_get_prometheus_client_from_env_vars_ipv6(self):
141
+ patched_env = {'PROMETHEUS_HOST': '2607:5300:201:2000::654',
142
+ 'PROMETHEUS_PORT': '1234'}
143
+ with mock.patch.dict(os.environ, patched_env), \
144
+ mock.patch.object(metric_utils, 'get_config_file',
145
+ return_value=None), \
146
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
147
+ "__init__", return_value=None) as m:
148
+ metric_utils.get_prometheus_client()
149
+ m.assert_called_with("[2607:5300:201:2000::654]:1234", None, "")
150
+
151
+ def test_get_prometheus_client_from_conf_file_ipv6(self):
152
+ config_data = '''
153
+ host: "2607:5300:201:2000::654"
154
+ port: "80"
155
+ '''
156
+ config_file = mock.mock_open(read_data=config_data)("name", 'r')
157
+ with mock.patch.dict(os.environ, {}), \
158
+ mock.patch.object(metric_utils, 'get_config_file',
159
+ return_value=config_file), \
160
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
161
+ "__init__", return_value=None) as init_m:
162
+ metric_utils.get_prometheus_client()
163
+ init_m.assert_called_with(
164
+ "[2607:5300:201:2000::654]:80", None, ""
165
+ )
166
+
167
+ def test_get_prometheus_client_from_keystone_ipv6(self):
168
+ prom_endpoint = "http://[2607:5300:201:2000::654]:80/prometheus"
169
+ keystone_session = session.Session()
170
+ with mock.patch.dict(os.environ, {}), \
171
+ mock.patch.object(metric_utils, 'get_config_file',
172
+ return_value=None), \
173
+ mock.patch.object(adapter.Adapter, 'get_endpoint',
174
+ return_value=prom_endpoint), \
175
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
176
+ "__init__", return_value=None) as init_m, \
177
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
178
+ "set_ca_cert") as ca_m:
179
+ metric_utils.get_prometheus_client(keystone_session)
180
+ init_m.assert_called_with(
181
+ "[2607:5300:201:2000::654]:80", keystone_session, "prometheus"
182
+ )
183
+ ca_m.assert_not_called()
184
+
102
185
 
103
186
  class FormatLabelsTest(testtools.TestCase):
104
187
  def setUp(self):
@@ -14,7 +14,11 @@
14
14
 
15
15
  import logging
16
16
  import os
17
+ from urllib import parse
17
18
 
19
+ from keystoneauth1 import adapter
20
+ from keystoneauth1.exceptions import catalog as keystone_exception
21
+ from oslo_utils import netutils
18
22
  import yaml
19
23
 
20
24
  from observabilityclient.prometheus_client import PrometheusAPIClient
@@ -45,11 +49,33 @@ def get_config_file():
45
49
  return None
46
50
 
47
51
 
48
- def get_prometheus_client(session=None):
49
- host = None
50
- port = None
51
- ca_cert = None
52
- root_path = ""
52
+ def get_prom_client_from_keystone(session, adapter_options=None):
53
+ if adapter_options is None:
54
+ adapter_options = {}
55
+ endpoint = adapter.Adapter(
56
+ session=session, **adapter_options
57
+ ).get_endpoint()
58
+ parsed_url = parse.urlparse(endpoint)
59
+
60
+ escaped_host = netutils.escape_ipv6(parsed_url.hostname)
61
+ root_path = parsed_url.path.strip('/')
62
+ tls = parsed_url.scheme == "https"
63
+
64
+ if parsed_url.port is not None:
65
+ url = f'{escaped_host}:{parsed_url.port}'
66
+ else:
67
+ url = escaped_host
68
+
69
+ client = PrometheusAPIClient(url, session, root_path)
70
+
71
+ if tls:
72
+ client.set_ca_cert(True)
73
+ return client
74
+
75
+
76
+ def get_prom_client_from_file_or_env():
77
+ host = port = ca_cert = None
78
+ root_path = ''
53
79
  conf_file = get_config_file()
54
80
  if conf_file is not None:
55
81
  conf = yaml.safe_load(conf_file)
@@ -62,9 +88,6 @@ def get_prometheus_client(session=None):
62
88
  if 'root_path' in conf:
63
89
  root_path = conf['root_path']
64
90
  conf_file.close()
65
-
66
- # NOTE(jwysogla): We allow to overide the prometheus.yaml by
67
- # the environment variables
68
91
  if 'PROMETHEUS_HOST' in os.environ:
69
92
  host = os.environ['PROMETHEUS_HOST']
70
93
  if 'PROMETHEUS_PORT' in os.environ:
@@ -75,13 +98,48 @@ def get_prometheus_client(session=None):
75
98
  root_path = os.environ['PROMETHEUS_ROOT_PATH']
76
99
  if host is None or port is None:
77
100
  raise ConfigurationError("Can't find prometheus host and "
78
- "port configuration.")
79
- client = PrometheusAPIClient(f"{host}:{port}", session, root_path)
101
+ "port configuration in config file or "
102
+ "environment variables.")
103
+ escaped_host = netutils.escape_ipv6(host)
104
+ client = PrometheusAPIClient(
105
+ f"{escaped_host}:{port}", None, root_path
106
+ )
80
107
  if ca_cert is not None:
81
108
  client.set_ca_cert(ca_cert)
82
109
  return client
83
110
 
84
111
 
112
+ def get_prometheus_client(session=None, adapter_options=None):
113
+ if adapter_options is None:
114
+ adapter_options = {}
115
+
116
+ keystone_error = None
117
+ if session is not None:
118
+ try:
119
+ return get_prom_client_from_keystone(session, adapter_options)
120
+ except keystone_exception.EndpointNotFound as e:
121
+ # NOTE(jwysogla): Fallback to get the endpoint configuration from
122
+ # the config file and env vars. If that doesn't work, the error
123
+ # message is raised as ConfigurationError later.
124
+ keystone_error = e
125
+ LOG.debug("Aetos endpoint discovery from Keystone failed: %s", e)
126
+
127
+ # NOTE(jwysogla): Always fallback to the original method of discovery
128
+ # through config file and env variables for backwards compatibility.
129
+ try:
130
+ return get_prom_client_from_file_or_env()
131
+ except ConfigurationError as e:
132
+ if keystone_error is not None:
133
+ raise ConfigurationError(
134
+ f"Failed to configure Prometheus client. "
135
+ f"Aetos discovery from keystone failed: '{keystone_error}'. "
136
+ f"Prometheus configuration from config file and environment "
137
+ f"variables failed: '{e}'"
138
+ )
139
+ else:
140
+ raise e
141
+
142
+
85
143
  def get_client(obj):
86
144
  return obj.app.client_manager.observabilityclient
87
145
 
@@ -13,20 +13,39 @@
13
13
  # under the License.
14
14
  #
15
15
 
16
+ import argparse
17
+ import sys
18
+
16
19
  from osc_lib.command import command
17
20
 
18
21
  from observabilityclient.i18n import _
19
22
 
20
23
 
24
+ class DeprecatedNOOPAction(argparse.Action):
25
+ def __init__(self, *args, **kwargs):
26
+ kwargs['help'] = f"[DEPRECATED] {kwargs['help']}" \
27
+ if 'help' in kwargs else \
28
+ "[DEPRECATED]"
29
+ kwargs['required'] = False
30
+ kwargs['nargs'] = 0
31
+ super().__init__(*args, **kwargs)
32
+
33
+ def __call__(self, parser, namespace, values, option_string=None):
34
+ if option_string is not None:
35
+ print(f"Note: {option_string} is deprecated option, "
36
+ "has no effect and is a subject for removal "
37
+ "in future OpenStack release.", file=sys.stderr)
38
+
39
+
21
40
  class ObservabilityBaseCommand(command.Command):
22
41
  """Base class for metric commands."""
23
42
 
24
43
  def get_parser(self, prog_name):
25
44
  parser = super().get_parser(prog_name)
26
- # TODO(jwysogla): Should this be restricted somehow?
27
45
  parser.add_argument(
28
46
  '--disable-rbac',
29
- action='store_true',
47
+ action=DeprecatedNOOPAction,
48
+ default=True,
30
49
  help=_("Disable rbac injection")
31
50
  )
32
51
  return parser
@@ -28,7 +28,7 @@ class Client(object):
28
28
  session_options = session_options or {}
29
29
  adapter_options = adapter_options or {}
30
30
 
31
- adapter_options.setdefault('service_type', "metric")
31
+ adapter_options.setdefault('service_type', "metric-storage")
32
32
 
33
33
  if session is None:
34
34
  session = keystoneauth1.session.Session(**session_options)
@@ -38,7 +38,9 @@ class Client(object):
38
38
 
39
39
  self.session = session
40
40
 
41
- self.prometheus_client = get_prometheus_client(session)
41
+ self.prometheus_client = get_prometheus_client(
42
+ session, adapter_options
43
+ )
42
44
  self.query = python_api.QueryManager(self)
43
45
  self.rbac = rbac.PromQLRbac(
44
46
  self.prometheus_client,
@@ -17,7 +17,7 @@ from observabilityclient.v1 import base
17
17
 
18
18
 
19
19
  class QueryManager(base.Manager):
20
- def list(self, disable_rbac=False):
20
+ def list(self, disable_rbac=True):
21
21
  """List metric names.
22
22
 
23
23
  :param disable_rbac: Disables rbac injection if set to True
@@ -34,7 +34,7 @@ class QueryManager(base.Manager):
34
34
  unique_metric_names = list(set([m['__name__'] for m in metrics]))
35
35
  return sorted(unique_metric_names)
36
36
 
37
- def show(self, name, disable_rbac=False):
37
+ def show(self, name, disable_rbac=True):
38
38
  """Show current values for metrics of a specified name.
39
39
 
40
40
  :param disable_rbac: Disables rbac injection if set to True
@@ -48,7 +48,7 @@ class QueryManager(base.Manager):
48
48
  last_metric_query = f"last_over_time({query}[5m])"
49
49
  return self.prom.query(last_metric_query)
50
50
 
51
- def query(self, query, disable_rbac=False):
51
+ def query(self, query, disable_rbac=True):
52
52
  """Send a query to prometheus.
53
53
 
54
54
  The query can be any PromQL query. Labels for enforcing
@@ -1,5 +1,6 @@
1
1
  Alfredo Moralejo <amoralej@redhat.com>
2
2
  Chris Sibbitt <csibbitt@redhat.com>
3
+ Cyril Roelandt <cyril@redhat.com>
3
4
  Erno Kuvaja <jokke@usr.fi>
4
5
  Ghanshyam Mann <gmann@ghanshyammann.com>
5
6
  Jaromir Wysoglad <jwysogla@redhat.com>
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-observabilityclient
3
- Version: 0.5.0
3
+ Version: 1.1.0
4
4
  Summary: OpenStack Observability Client
5
- Home-page: https://infrawatch.github.io/documentation/
5
+ Home-page: https://opendev.org/openstack/python-observabilityclient
6
6
  Author: OpenStack
7
7
  Author-email: openstack-discuss@lists.openstack.org
8
8
  License: Apache License, Version 2.0
@@ -17,11 +17,10 @@ Classifier: Programming Language :: Python
17
17
  Classifier: Programming Language :: Python :: Implementation :: CPython
18
18
  Classifier: Programming Language :: Python :: 3 :: Only
19
19
  Classifier: Programming Language :: Python :: 3
20
- Classifier: Programming Language :: Python :: 3.9
21
20
  Classifier: Programming Language :: Python :: 3.10
22
21
  Classifier: Programming Language :: Python :: 3.11
23
22
  Classifier: Programming Language :: Python :: 3.12
24
- Requires-Python: >=3.9
23
+ Requires-Python: >=3.10
25
24
  Description-Content-Type: text/markdown; charset=UTF-8
26
25
  License-File: LICENSE
27
26
  License-File: AUTHORS
@@ -45,7 +44,7 @@ Install your OpenStack environment and patch your `openstack` client application
45
44
  su - stack
46
45
 
47
46
  # clone and install observability client plugin
48
- git clone https://github.com/infrawatch/python-observabilityclient
47
+ git clone https://opendev.org/openstack/python-observabilityclient.git
49
48
  cd python-observabilityclient
50
49
  sudo python setup.py install --prefix=/usr
51
50
  ```
@@ -0,0 +1,31 @@
1
+ observabilityclient/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ observabilityclient/client.py,sha256=cfRb816p6Ips9t2cdWvmSJ1uGrtTEHXQnctoExrLA5A,828
3
+ observabilityclient/i18n.py,sha256=PFo6BaOfyGQD5q7L3FunYJ8d4mwbRszG8wOrJIjki_4,790
4
+ observabilityclient/plugin.py,sha256=hyxENjNO6NLrH6G4muyAeEEtFTBa9d5OozjwpzNpJVA,2262
5
+ observabilityclient/prometheus_client.py,sha256=yn0cOj08CUYLNydyh3sc1vTPGwplxZeMiyNN4l52aoY,7457
6
+ observabilityclient/rbac.py,sha256=EudKSx79doqV-2Ka2HraP2ImOOj1ctIno4-rMVI2jqY,7830
7
+ observabilityclient/tests/functional/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ observabilityclient/tests/functional/base.py,sha256=X2KZRKrHQlQf5uMeNERydlIPQYdhjd5LI_MlGfT0oTA,6516
9
+ observabilityclient/tests/functional/test_cli.py,sha256=jwhgt8w0gq1CdDoaDKLV8SB_hQRmgnbMw9rRIyfcZLo,3944
10
+ observabilityclient/tests/functional/test_python_api.py,sha256=5TLFboJ7B__UZ9zfc6bVSxPTzV9KnnrwluTqLwnTZLs,3308
11
+ observabilityclient/tests/unit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ observabilityclient/tests/unit/test_cli.py,sha256=N19Yo-PIdhlR4-tKQCKbtoetbknxZwl10zsEQSA1Leo,6191
13
+ observabilityclient/tests/unit/test_prometheus_client.py,sha256=iyAypBArQE2e7WGORwhelpoKdNAK1UD2SqZcs6p6ToQ,18982
14
+ observabilityclient/tests/unit/test_python_api.py,sha256=gMUcsvQISESY7p3NWsuoHk07I0phc74c-JC2vKRKfBI,4741
15
+ observabilityclient/tests/unit/test_rbac.py,sha256=sSIw8y8Xgdy6nJm0QW2ImZzyQOOQ24E5S_s7AtHcnQ8,9012
16
+ observabilityclient/tests/unit/test_utils.py,sha256=FbRR056Xr0RUlXYJVDJVAFF6eB9BmNNbCTpzA3sev7I,12445
17
+ observabilityclient/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ observabilityclient/utils/metric_utils.py,sha256=AISLI2s1Y7dnQq5aP0BbpczoZIO23hbD_QEpLkqn0Oc,5799
19
+ observabilityclient/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ observabilityclient/v1/base.py,sha256=keRgOIe7_yvE57fJRZ5O6s0GK6N4CqbGwhw24CmiAGE,2913
21
+ observabilityclient/v1/cli.py,sha256=ln7GsnbW95n90oFGw4zLiwHDjY0YHBxkRBzID-j6ZmA,4028
22
+ observabilityclient/v1/client.py,sha256=MPsHTAG3IL_8PD37fbHZnJ_sgCWJyMPO_upEXsiB5D0,1755
23
+ observabilityclient/v1/python_api.py,sha256=niW0NUWKK-Mdli72gWpP_tjGYEFr4RXc5J3giBkIkuA,3891
24
+ python_observabilityclient-1.1.0.dist-info/AUTHORS,sha256=kbZ0J1gr9UzwvCdQ444XzTLrcuzW1hbhHEqY28qN_f0,566
25
+ python_observabilityclient-1.1.0.dist-info/LICENSE,sha256=qyh9xnj_IPtYWzClm5mZxCWRKTr2eUP_iLcU28DIvCw,11343
26
+ python_observabilityclient-1.1.0.dist-info/METADATA,sha256=M2BJIU_tSAFAunMQf921xatnAtiOxOUiuGV6zFWTETE,2966
27
+ python_observabilityclient-1.1.0.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
28
+ python_observabilityclient-1.1.0.dist-info/entry_points.txt,sha256=15rmai80pMRfBKZrk6yPNrRkAs2h63bwlcbQKq9fax4,424
29
+ python_observabilityclient-1.1.0.dist-info/pbr.json,sha256=YkDXPaQjUHOO9g_MmNHUjIBb2HuDZNhQko7XV3thS-I,46
30
+ python_observabilityclient-1.1.0.dist-info/top_level.txt,sha256=Lf7Fwm3hfK-X1JNRy19rVlrMUOyQShBBPwsCU3pz6yw,20
31
+ python_observabilityclient-1.1.0.dist-info/RECORD,,
@@ -0,0 +1 @@
1
+ {"git_version": "2f31846", "is_release": true}
@@ -1,31 +0,0 @@
1
- observabilityclient/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- observabilityclient/client.py,sha256=cfRb816p6Ips9t2cdWvmSJ1uGrtTEHXQnctoExrLA5A,828
3
- observabilityclient/i18n.py,sha256=PFo6BaOfyGQD5q7L3FunYJ8d4mwbRszG8wOrJIjki_4,790
4
- observabilityclient/plugin.py,sha256=hyxENjNO6NLrH6G4muyAeEEtFTBa9d5OozjwpzNpJVA,2262
5
- observabilityclient/prometheus_client.py,sha256=yn0cOj08CUYLNydyh3sc1vTPGwplxZeMiyNN4l52aoY,7457
6
- observabilityclient/rbac.py,sha256=Rw2jyEl-xGb2U6wi7mDjJxTR9kGpIt8xOKOUOFvjq1Q,6327
7
- observabilityclient/tests/functional/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- observabilityclient/tests/functional/base.py,sha256=SXbPiksFH7aER-zZjIWxz5nwCqq5f1MYWth1tlFLwcs,6523
9
- observabilityclient/tests/functional/test_cli.py,sha256=QqU8BCGUnh4IlwnGr6hdDHjHp7TIM0jasDjReyZpz-Y,4856
10
- observabilityclient/tests/functional/test_python_api.py,sha256=NJBqBTEW_POoxI8CvMlNhWhDNAU3sQVKjRdXM2NboeU,3310
11
- observabilityclient/tests/unit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
- observabilityclient/tests/unit/test_cli.py,sha256=TMKjb0IXwbMkm6frvfTqClOa5ZGGWKywyheyTeWl3i8,5964
13
- observabilityclient/tests/unit/test_prometheus_client.py,sha256=iyAypBArQE2e7WGORwhelpoKdNAK1UD2SqZcs6p6ToQ,18982
14
- observabilityclient/tests/unit/test_python_api.py,sha256=16uvol7Ar9Ve0EPsW1MEs9_51KSeD36oMitPLAwA3Gk,5306
15
- observabilityclient/tests/unit/test_rbac.py,sha256=9kntOcGUwz9uzG2S4uZUozOl_BMw7I9b0W8FCoaNvm4,6961
16
- observabilityclient/tests/unit/test_utils.py,sha256=zqb8lgpIkQHU0i_qhEKw-c9dafXY6Tksmeu4uLo_exc,8143
17
- observabilityclient/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
- observabilityclient/utils/metric_utils.py,sha256=dOn0LC4HFCM2xLJl6ifYHGlAJXI42QRhi_ggBHF5Si0,3699
19
- observabilityclient/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
- observabilityclient/v1/base.py,sha256=2AMQU8WKbERvfoiRdOPIlogzH1ds_Son4Gr7fjGdGQ4,2260
21
- observabilityclient/v1/cli.py,sha256=ln7GsnbW95n90oFGw4zLiwHDjY0YHBxkRBzID-j6ZmA,4028
22
- observabilityclient/v1/client.py,sha256=SCvdmLcshiE2IMMl9ibxAJnMe94yjF_P94TzuD8sobs,1708
23
- observabilityclient/v1/python_api.py,sha256=ajlX0pHq7I_mfaNVs2BjFtV1cKj4HN94JCKK5INVscI,3894
24
- python_observabilityclient-0.5.0.dist-info/AUTHORS,sha256=uF42zVMEuwXhMW7eHDIzCpnu-RfapejbBNapd1-nRmc,532
25
- python_observabilityclient-0.5.0.dist-info/LICENSE,sha256=qyh9xnj_IPtYWzClm5mZxCWRKTr2eUP_iLcU28DIvCw,11343
26
- python_observabilityclient-0.5.0.dist-info/METADATA,sha256=1-Xb5LtCDmn6pxpCiodm9xhBk9fRaVfnswjyTDmALyo,2998
27
- python_observabilityclient-0.5.0.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
28
- python_observabilityclient-0.5.0.dist-info/entry_points.txt,sha256=15rmai80pMRfBKZrk6yPNrRkAs2h63bwlcbQKq9fax4,424
29
- python_observabilityclient-0.5.0.dist-info/pbr.json,sha256=wBkgi0o8n7AI9evsfhcx81qkg1yJPIj8UA-zXcpA3Ig,46
30
- python_observabilityclient-0.5.0.dist-info/top_level.txt,sha256=Lf7Fwm3hfK-X1JNRy19rVlrMUOyQShBBPwsCU3pz6yw,20
31
- python_observabilityclient-0.5.0.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- {"git_version": "ab8ce8f", "is_release": true}