python-observabilityclient 0.4.0__py3-none-any.whl → 0.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.
@@ -53,10 +53,18 @@ class PrometheusMetric(object):
53
53
 
54
54
 
55
55
  class PrometheusAPIClient(object):
56
- def __init__(self, host):
56
+ def __init__(self, host, session=None, root_path=""):
57
57
  self._host = host
58
- self._session = requests.Session()
58
+ if not self._host.endswith('/'):
59
+ self._host += '/'
60
+ if session is None:
61
+ self._session = requests.Session()
62
+ else:
63
+ self._session = session
59
64
  self._session.verify = False
65
+ self._root_path = root_path
66
+ if root_path != "" and not self._root_path.endswith('/'):
67
+ self._root_path += '/'
60
68
 
61
69
  def set_ca_cert(self, ca_cert):
62
70
  self._session.verify = ca_cert
@@ -68,11 +76,15 @@ class PrometheusAPIClient(object):
68
76
  def set_basic_auth(self, auth_user, auth_password):
69
77
  self._session.auth = (auth_user, auth_password)
70
78
 
79
+ def _get_url(self, endpoint):
80
+ scheme = 'https' if self._session.verify else 'http'
81
+ return f"{scheme}://{self._host}{self._root_path}api/v1/{endpoint}"
82
+
71
83
  def _get(self, endpoint, params=None):
72
- url = (f"{'https' if self._session.verify else 'http'}://"
73
- f"{self._host}/api/v1/{endpoint}")
84
+ url = self._get_url(endpoint)
74
85
  resp = self._session.get(url, params=params,
75
- headers={'Accept': 'application/json'})
86
+ headers={'Accept': 'application/json',
87
+ 'Accept-Encoding': 'identity'})
76
88
  if resp.status_code != requests.codes.ok:
77
89
  raise PrometheusAPIClientError(resp)
78
90
  decoded = resp.json()
@@ -82,8 +94,7 @@ class PrometheusAPIClient(object):
82
94
  return decoded
83
95
 
84
96
  def _post(self, endpoint, params=None):
85
- url = (f"{'https' if self._session.verify else 'http'}://"
86
- f"{self._host}/api/v1/{endpoint}")
97
+ url = self._get_url(endpoint)
87
98
  resp = self._session.post(url, params=params,
88
99
  headers={'Accept': 'application/json'})
89
100
  if resp.status_code != requests.codes.ok:
@@ -14,32 +14,15 @@
14
14
 
15
15
  import re
16
16
 
17
- from keystoneauth1.exceptions.auth_plugins import MissingAuthPlugin
18
-
19
17
  from observabilityclient.utils.metric_utils import format_labels
20
18
 
21
19
 
22
- class ObservabilityRbacError(Exception):
23
- pass
24
-
25
-
26
- class Rbac(object):
27
- def __init__(self, client, session, disable_rbac=False):
28
- self.client = client
29
- self.session = session
30
- self.disable_rbac = disable_rbac
31
- try:
32
- self.project_id = self.session.get_project_id()
33
- self.default_labels = {
34
- "project": self.project_id
35
- }
36
- self.rbac_init_successful = True
37
- except MissingAuthPlugin:
38
- self.project_id = None
39
- self.default_labels = {
40
- "project": "no-project"
41
- }
42
- self.rbac_init_successful = False
20
+ class PromQLRbac(object):
21
+ def __init__(self, prom_api_client, project_id):
22
+ self.client = prom_api_client
23
+ self.labels = {
24
+ "project": project_id
25
+ }
43
26
 
44
27
  def _find_label_value_end(self, query, start, quote_char):
45
28
  end = start
@@ -71,6 +54,10 @@ class Rbac(object):
71
54
  return end
72
55
 
73
56
  def _find_label_section_end(self, query, start):
57
+ if query[start:].startswith('{}'):
58
+ # We have an empty label section, without any
59
+ # label pair
60
+ return start + 1
74
61
  nearest_curly_brace_pos = None
75
62
  while nearest_curly_brace_pos != -1:
76
63
  pair_end = self._find_label_pair_end(query, start)
@@ -84,23 +71,26 @@ class Rbac(object):
84
71
  # and the "=" or "~" is a part of the next section.
85
72
  return nearest_curly_brace_pos
86
73
  start = pair_end
74
+ # TODO(tkajinam): We should probably raise an exception here because
75
+ # this indicates illegal format without closing } .
87
76
  return -1
88
77
 
89
- def enrich_query(self, query, disable_rbac=False):
90
- """Add rbac labels to queries.
78
+ def _insert_labels(self, query, location, comma=False, braces=False):
79
+ comma_str = ", " if comma else ""
80
+ formatted_labels = format_labels(self.labels)
81
+ labels_str = f"{{{formatted_labels}}}" if braces else formatted_labels
82
+ return (f"{query[:location]}{comma_str}"
83
+ f"{labels_str}"
84
+ f"{query[location:]}")
85
+
86
+ def modify_query(self, query):
87
+ """Add rbac labels to a query.
91
88
 
92
- :param query: The query to enrich
89
+ :param query: The query to modify
93
90
  :type query: str
94
- :param disable_rbac: Disables rbac injection if set to True
95
- :type disable_rbac: boolean
96
91
  """
97
- # TODO(jwysogla): This should be properly tested
98
- if disable_rbac:
99
- return query
100
- labels = self.default_labels
101
-
102
92
  # We need to get all metric names, no matter the rbac
103
- metric_names = self.client.query.list(disable_rbac=False)
93
+ metric_names = self.client.label_values("__name__")
104
94
 
105
95
  # We need to detect the locations of metric names
106
96
  # inside the query
@@ -117,35 +107,51 @@ class Rbac(object):
117
107
  name_end_locations.append(potential_name.end())
118
108
 
119
109
  name_end_locations = sorted(name_end_locations, reverse=True)
110
+ if len(name_end_locations) == 0:
111
+ name_end_locations = [0]
120
112
  for name_end_location in name_end_locations:
121
113
  if (name_end_location < len(query) and
122
114
  query[name_end_location] == "{"):
123
- # There already are some labels
124
- labels_end = self._find_label_section_end(query,
125
- name_end_location)
126
- query = (f"{query[:labels_end]}, "
127
- f"{format_labels(labels)}"
128
- f"{query[labels_end:]}")
115
+ # There is already a label section
116
+ labels_end = self._find_label_section_end(
117
+ query,
118
+ name_end_location
119
+ )
120
+ if labels_end == name_end_location + 1:
121
+ query = self._insert_labels(
122
+ query,
123
+ labels_end,
124
+ comma=False,
125
+ braces=False
126
+ )
127
+ else:
128
+ query = self._insert_labels(
129
+ query,
130
+ labels_end,
131
+ comma=True,
132
+ braces=False
133
+ )
129
134
  else:
130
- query = (f"{query[:name_end_location]}"
131
- f"{{{format_labels(labels)}}}"
132
- f"{query[name_end_location:]}")
135
+ query = self._insert_labels(
136
+ query,
137
+ name_end_location,
138
+ comma=False,
139
+ braces=True
140
+ )
133
141
  return query
134
142
 
135
- def append_rbac(self, query, disable_rbac=False):
143
+ def append_rbac_labels(self, query):
136
144
  """Append rbac labels to queries.
137
145
 
138
- It's a simplified and faster version of enrich_query(). This just
146
+ It's a simplified and faster version of modify_query(). This just
139
147
  appends the labels at the end of the query string. For proper handling
140
148
  of complex queries, where metric names might occure elsewhere than
141
- just at the end, please use the enrich_query() function.
149
+ just at the end, please use the modify_query() function.
142
150
 
143
151
  :param query: The query to append to
144
152
  :type query: str
145
- :param disable_rbac: Disables rbac injection if set to True
146
- :type disable_rbac: boolean
147
153
  """
148
- labels = self.default_labels
149
- if disable_rbac:
150
- return query
151
- return f"{query}{{{format_labels(labels)}}}"
154
+ if any(c in query for c in "{}"):
155
+ return self.modify_query(query)
156
+ else:
157
+ return f"{query}{{{format_labels(self.labels)}}}"
@@ -85,7 +85,8 @@ class PrometheusAPIClientTestBase(testtools.TestCase):
85
85
  class PrometheusAPIClientTest(PrometheusAPIClientTestBase):
86
86
  def test_get(self):
87
87
  url = "test"
88
- expected_url = "http://localhost:9090/api/v1/test"
88
+ root_path = "root_path"
89
+ expected_url = f"http://localhost:9090/{root_path}/api/v1/{url}"
89
90
 
90
91
  params = {"query": "ceilometer_image_size{publisher='localhost'}"}
91
92
  expected_params = params
@@ -93,12 +94,14 @@ class PrometheusAPIClientTest(PrometheusAPIClientTestBase):
93
94
  return_value = self.GoodResponse()
94
95
  with mock.patch.object(requests.Session, 'get',
95
96
  return_value=return_value) as m:
96
- c = client.PrometheusAPIClient("localhost:9090")
97
+ c = client.PrometheusAPIClient("localhost:9090",
98
+ root_path=root_path)
97
99
  c._get(url, params)
98
100
 
99
101
  m.assert_called_with(expected_url,
100
102
  params=expected_params,
101
- headers={'Accept': 'application/json'})
103
+ headers={'Accept': 'application/json',
104
+ 'Accept-Encoding': 'identity'})
102
105
 
103
106
  def test_get_error(self):
104
107
  url = "test"
@@ -120,7 +123,7 @@ class PrometheusAPIClientTest(PrometheusAPIClientTestBase):
120
123
 
121
124
  def test_post(self):
122
125
  url = "test"
123
- expected_url = "http://localhost:9090/api/v1/test"
126
+ expected_url = f"http://localhost:9090/api/v1/{url}"
124
127
 
125
128
  params = {"query": "ceilometer_image_size{publisher='localhost'}"}
126
129
  expected_params = params
@@ -17,11 +17,11 @@ from unittest import mock
17
17
  import testtools
18
18
 
19
19
  from observabilityclient import prometheus_client
20
+ from observabilityclient import rbac
20
21
  from observabilityclient.tests.unit.test_prometheus_client import (
21
22
  MetricListMatcher
22
23
  )
23
24
  from observabilityclient.v1 import python_api
24
- from observabilityclient.v1 import rbac
25
25
 
26
26
 
27
27
  class QueryManagerTest(testtools.TestCase):
@@ -31,9 +31,8 @@ class QueryManagerTest(testtools.TestCase):
31
31
  prom_client = prometheus_client.PrometheusAPIClient("somehost")
32
32
  self.client.prometheus_client = prom_client
33
33
 
34
- self.rbac = mock.Mock(wraps=rbac.Rbac(self.client, mock.Mock()))
35
- self.rbac.default_labels = {'project': 'project_id'}
36
- self.rbac.rbac_init_succesful = True
34
+ self.rbac = mock.Mock(wraps=rbac.PromQLRbac(prom_client, mock.Mock()))
35
+ self.rbac.labels = {'project': 'project_id'}
37
36
 
38
37
  self.manager = python_api.QueryManager(self.client)
39
38
 
@@ -41,15 +40,32 @@ class QueryManagerTest(testtools.TestCase):
41
40
  self.client.query = self.manager
42
41
 
43
42
  def test_list(self):
44
- returned_by_prom = {'data': ['metric1', 'test42', 'abc2']}
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']}
45
59
  expected = ['abc2', 'metric1', 'test42']
46
60
 
47
61
  with mock.patch.object(prometheus_client.PrometheusAPIClient, '_get',
48
- return_value=returned_by_prom):
62
+ return_value=returned_by_prom_rbac):
49
63
  ret1 = self.manager.list()
50
- ret2 = self.manager.list(disable_rbac=True)
51
-
52
64
  self.assertEqual(expected, ret1)
65
+
66
+ with mock.patch.object(prometheus_client.PrometheusAPIClient, '_get',
67
+ return_value=returned_by_prom_no_rbac):
68
+ ret2 = self.manager.list(disable_rbac=True)
53
69
  self.assertEqual(expected, ret2)
54
70
 
55
71
  def test_show(self):
@@ -65,21 +81,23 @@ class QueryManagerTest(testtools.TestCase):
65
81
  }
66
82
  expected = [prometheus_client.PrometheusMetric(returned_by_prom)]
67
83
  expected_matcher = MetricListMatcher(expected)
84
+
68
85
  with mock.patch.object(prometheus_client.PrometheusAPIClient, '_get',
69
86
  return_value=returned_by_prom):
70
- ret1 = self.manager.show(query)
71
- self.rbac.append_rbac.assert_called_with(query,
72
- disable_rbac=False)
73
-
74
87
  ret2 = self.manager.show(query, disable_rbac=True)
75
- self.rbac.append_rbac.assert_called_with(query,
76
- disable_rbac=True)
88
+ self.rbac.append_rbac_labels.assert_not_called()
89
+
90
+ with mock.patch.object(prometheus_client.PrometheusAPIClient, '_get',
91
+ return_value=returned_by_prom):
92
+ ret1 = self.manager.show(query)
93
+ self.rbac.append_rbac_labels.assert_called_with(query)
77
94
 
78
95
  self.assertThat(ret1, expected_matcher)
79
96
  self.assertThat(ret2, expected_matcher)
80
97
 
81
98
  def test_query(self):
82
- query = 'some_metric'
99
+ queried_metric_name = 'some_metric'
100
+ query = queried_metric_name
83
101
  returned_by_prom = {
84
102
  'data': {
85
103
  'resultType': 'non-vector'
@@ -92,14 +110,15 @@ class QueryManagerTest(testtools.TestCase):
92
110
  expected = [prometheus_client.PrometheusMetric(returned_by_prom)]
93
111
  expected_matcher = MetricListMatcher(expected)
94
112
  with mock.patch.object(prometheus_client.PrometheusAPIClient, '_get',
95
- return_value=returned_by_prom):
96
- ret1 = self.manager.query(query)
97
- self.rbac.enrich_query.assert_called_with(query,
98
- disable_rbac=False)
113
+ return_value=returned_by_prom), \
114
+ mock.patch.object(python_api.QueryManager, 'list',
115
+ return_value=queried_metric_name):
116
+
117
+ ret1 = self.manager.query(query, disable_rbac=True)
118
+ self.rbac.modify_query.assert_not_called()
99
119
 
100
- ret2 = self.manager.query(query, disable_rbac=True)
101
- self.rbac.enrich_query.assert_called_with(query,
102
- disable_rbac=True)
120
+ ret2 = self.manager.query(query)
121
+ self.rbac.modify_query.assert_called_with(query)
103
122
 
104
123
  self.assertThat(ret1, expected_matcher)
105
124
  self.assertThat(ret2, expected_matcher)
@@ -14,62 +14,67 @@
14
14
 
15
15
  from unittest import mock
16
16
 
17
- from keystoneauth1.exceptions.auth_plugins import MissingAuthPlugin
18
- from keystoneauth1 import session
19
17
  import testtools
20
18
 
21
- from observabilityclient.v1 import rbac
19
+ from observabilityclient import rbac
22
20
 
23
21
 
24
- class RbacTest(testtools.TestCase):
22
+ class PromQLRbacTest(testtools.TestCase):
25
23
  def setUp(self):
26
- super(RbacTest, self).setUp()
27
- self.rbac = rbac.Rbac(mock.Mock(), mock.Mock())
28
- self.rbac.project_id = "secret_id"
29
- self.rbac.default_labels = {
30
- "project": self.rbac.project_id
24
+ super(PromQLRbacTest, self).setUp()
25
+ self.project_id = "project123"
26
+ self.rbac = rbac.PromQLRbac(mock.Mock(), mock.Mock())
27
+ self.rbac.labels = {
28
+ "project": "project123"
31
29
  }
32
-
33
- def test_constructor(self):
34
- with mock.patch.object(session.Session, 'get_project_id',
35
- return_value="123"):
36
- r = rbac.Rbac("client", session.Session(), False)
37
- self.assertEqual(r.project_id, "123")
38
- self.assertEqual(r.default_labels, {
39
- "project": "123"
40
- })
41
-
42
- def test_constructor_error(self):
43
- with mock.patch.object(session.Session, 'get_project_id',
44
- side_effect=MissingAuthPlugin()):
45
- r = rbac.Rbac("client", session.Session(), False)
46
- self.assertIsNone(r.project_id)
47
-
48
- def test_enrich_query(self):
49
- test_cases = [
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
+ ]
39
+ self.test_cases = [
50
40
  (
51
41
  "test_query",
52
- f"test_query{{project='{self.rbac.project_id}'}}"
42
+ f"test_query{{project='{self.project_id}'}}"
53
43
  ), (
54
44
  "test_query{somelabel='value'}",
55
45
 
56
46
  (f"test_query{{somelabel='value', "
57
- f"project='{self.rbac.project_id}'}}")
47
+ f"project='{self.project_id}'}}")
58
48
  ), (
59
49
  "test_query{somelabel='value', label2='value2'}",
60
50
 
61
51
  (f"test_query{{somelabel='value', label2='value2', "
62
- f"project='{self.rbac.project_id}'}}")
52
+ f"project='{self.project_id}'}}")
53
+ ), (
54
+ "test_query{somelabel='unicode{}{ \t/-_#~$&%\\'}",
55
+
56
+ (f"test_query{{somelabel='unicode{{}}{{ \t/-_#~$&%\\', "
57
+ f"project='{self.project_id}'}}")
63
58
  ), (
64
- "test_query{somelabel='unicode{}{'}",
59
+ "test_query{somelabel='s p a c e'}",
65
60
 
66
- (f"test_query{{somelabel='unicode{{}}{{', "
67
- f"project='{self.rbac.project_id}'}}")
61
+ (f"test_query{{somelabel='s p a c e', "
62
+ f"project='{self.project_id}'}}")
63
+ ), (
64
+ "test_query{somelabel='doublequotes\"'}",
65
+
66
+ (f"test_query{{somelabel='doublequotes\"', "
67
+ f"project='{self.project_id}'}}")
68
+ ), (
69
+ 'test_query{somelabel="singlequotes\'"}',
70
+
71
+ (f'test_query{{somelabel="singlequotes\'", '
72
+ f'project=\'{self.project_id}\'}}')
68
73
  ), (
69
74
  "test_query{doesnt_match_regex!~'regex'}",
70
75
 
71
76
  (f"test_query{{doesnt_match_regex!~'regex', "
72
- f"project='{self.rbac.project_id}'}}")
77
+ f"project='{self.project_id}'}}")
73
78
  ), (
74
79
  "delta(cpu_temp_celsius{host='zeus'}[2h]) - "
75
80
  "sum(http_requests) + "
@@ -77,69 +82,107 @@ class RbacTest(testtools.TestCase):
77
82
  "sum(http_requests{or_regex=~'smth1|something2|3'})",
78
83
 
79
84
  (f"delta(cpu_temp_celsius{{host='zeus', "
80
- f"project='{self.rbac.project_id}'}}[2h]) - "
85
+ f"project='{self.project_id}'}}[2h]) - "
81
86
  f"sum(http_requests"
82
- f"{{project='{self.rbac.project_id}'}}) + "
87
+ f"{{project='{self.project_id}'}}) + "
83
88
  f"sum(http_requests{{instance=~'.*', "
84
- f"project='{self.rbac.project_id}'}}) + "
89
+ f"project='{self.project_id}'}}) + "
85
90
  f"sum(http_requests{{or_regex=~'smth1|something2|3', "
86
- f"project='{self.rbac.project_id}'}})")
87
- )
88
- ]
91
+ f"project='{self.project_id}'}})")
92
+ ), (
93
+ "round(test_query{label='something'},5)",
89
94
 
90
- self.rbac.client.query.list = lambda disable_rbac: ['test_query',
91
- 'cpu_temp_celsius',
92
- 'http_requests']
95
+ (f"round(test_query{{label='something', "
96
+ f"project='{self.project_id}'}},5)")
97
+ ), (
98
+ "sum by (foo) (test_query{label_1='baz'})",
93
99
 
94
- for query, expected in test_cases:
95
- ret = self.rbac.enrich_query(query)
96
- self.assertEqual(ret, expected)
100
+ (f"sum by (foo) (test_query{{label_1='baz', "
101
+ f"project='{self.project_id}'}})")
102
+ ), (
103
+ "test_query{} + avg without (application, group) "
104
+ "(test:query:with:colon:{label='baz'})",
97
105
 
98
- def test_enrich_query_disable(self):
99
- test_cases = [
100
- (
101
- "test_query",
102
- "test_query"
106
+ (f"test_query{{project='{self.project_id}'}} + "
107
+ f"avg without (application, group) "
108
+ f"(test:query:with:colon:{{label='baz', "
109
+ f"project='{self.project_id}'}})")
103
110
  ), (
104
- "test_query{somelabel='value'}",
105
- "test_query{somelabel='value'}"
111
+ "test_query{label1='foo'} + on (label1,label2) "
112
+ "avg by (label3) (test_query_with_digit1{label='baz',"
113
+ "label1='foo',label2='bar'})",
114
+
115
+ (f"test_query{{label1='foo', "
116
+ f"project='{self.project_id}'}} "
117
+ f"+ on (label1,label2) avg by (label3) "
118
+ f"(test_query_with_digit1{{label='baz',"
119
+ f"label1='foo',label2='bar', "
120
+ f"project='{self.project_id}'}})")
106
121
  ), (
107
- "test_query{somelabel='value', label2='value2'}",
108
- "test_query{somelabel='value', label2='value2'}"
122
+ "{label='no-metric'}",
123
+
124
+ (f"{{label='no-metric', "
125
+ f"project='{self.project_id}'}}")
109
126
  ), (
110
- "test_query{somelabel='unicode{}{'}",
111
- "test_query{somelabel='unicode{}{'}"
127
+ "http_requests{environment=~"
128
+ "'staging|testing|development',method!='GET'}",
129
+
130
+ (f"http_requests{{environment=~"
131
+ f"'staging|testing|development',method!='GET', "
132
+ f"project='{self.project_id}'}}")
112
133
  ), (
113
- "test_query{doesnt_match_regex!~'regex'}",
114
- "test_query{doesnt_match_regex!~'regex'}",
134
+ "http_requests{replica!='rep-a',replica=~'rep.*'}",
135
+
136
+ (f"http_requests{{replica!='rep-a',replica=~'rep.*', "
137
+ f"project='{self.project_id}'}}")
115
138
  ), (
116
- "delta(cpu_temp_celsius{host='zeus'}[2h]) - "
117
- "sum(http_requests) + "
118
- "sum(http_requests{instance=~'.*'}) + "
119
- "sum(http_requests{or_regex=~'smth1|something2|3'})",
139
+ "{__name__=~'job:.*'}",
120
140
 
121
- "delta(cpu_temp_celsius{host='zeus'}[2h]) - "
122
- "sum(http_requests) + "
123
- "sum(http_requests{instance=~'.*'}) + "
124
- "sum(http_requests{or_regex=~'smth1|something2|3'})"
141
+ (f"{{__name__=~'job:.*', "
142
+ f"project='{self.project_id}'}}")
143
+ ), (
144
+ "http_requests offset 5m",
145
+
146
+ (f"http_requests"
147
+ f"{{project='{self.project_id}'}} "
148
+ f"offset 5m")
149
+ ), (
150
+ "rate(http_requests[5m] offset -1w)",
151
+
152
+ (f"rate(http_requests"
153
+ f"{{project='{self.project_id}'}}"
154
+ f"[5m] offset -1w)")
155
+ ), (
156
+ "http_requests @ 1609746000",
157
+
158
+ (f"http_requests"
159
+ f"{{project='{self.project_id}'}} "
160
+ f"@ 1609746000")
161
+ ), (
162
+ "histogram_quantile(0.9, sum by (le) "
163
+ "(rate(http_requests[10m])))",
164
+
165
+ (f"histogram_quantile(0.9, sum by (le) "
166
+ f"(rate(http_requests"
167
+ f"{{project='{self.project_id}'}}"
168
+ f"[10m])))"
169
+ )
125
170
  )
126
171
  ]
127
172
 
128
- self.rbac.client.query.list = lambda disable_rbac: ['test_query',
129
- 'cpu_temp_celsius',
130
- 'http_requests']
131
- for query, expected in test_cases:
132
- ret = self.rbac.enrich_query(query, disable_rbac=True)
133
- self.assertEqual(ret, query)
173
+ def test_constructor(self):
174
+ r = rbac.PromQLRbac("client", "123")
175
+ self.assertEqual(r.labels, {
176
+ "project": "123"
177
+ })
134
178
 
135
- def test_append_rbac(self):
136
- query = "test_query"
137
- expected = f"{query}{{project='{self.rbac.project_id}'}}"
138
- ret = self.rbac.append_rbac(query)
139
- self.assertEqual(ret, expected)
179
+ def test_modify_query(self):
180
+ for query, expected in self.test_cases:
181
+ ret = self.rbac.modify_query(query)
182
+ self.assertEqual(expected, ret)
140
183
 
141
- def test_append_rbac_disable(self):
184
+ def test_append_rbac_labels(self):
142
185
  query = "test_query"
143
- expected = query
144
- ret = self.rbac.append_rbac(query, disable_rbac=True)
145
- self.assertEqual(ret, expected)
186
+ expected = f"{query}{{project='{self.project_id}'}}"
187
+ ret = self.rbac.append_rbac_labels(query)
188
+ self.assertEqual(expected, ret)
@@ -55,19 +55,20 @@ class GetPrometheusClientTest(testtools.TestCase):
55
55
  mock.patch.object(prometheus_client.PrometheusAPIClient,
56
56
  "__init__", return_value=None) as m:
57
57
  metric_utils.get_prometheus_client()
58
- m.assert_called_with("somehost:1234")
58
+ m.assert_called_with("somehost:1234", None, "")
59
59
 
60
- def test_get_prometheus_client_env_overide(self):
61
- with mock.patch.dict(os.environ, {'PROMETHEUS_HOST': 'env_overide'}), \
60
+ def test_get_prometheus_client_env_override(self):
61
+ with mock.patch.dict(os.environ,
62
+ {'PROMETHEUS_HOST': 'env_override'}), \
62
63
  mock.patch.object(metric_utils, 'get_config_file',
63
64
  return_value=self.config_file), \
64
65
  mock.patch.object(prometheus_client.PrometheusAPIClient,
65
66
  "__init__", return_value=None) as m:
66
67
  metric_utils.get_prometheus_client()
67
- m.assert_called_with("env_overide:1234")
68
+ m.assert_called_with("env_override:1234", None, "")
68
69
 
69
70
  def test_get_prometheus_client_no_config_file(self):
70
- patched_env = {'PROMETHEUS_HOST': 'env_overide',
71
+ patched_env = {'PROMETHEUS_HOST': 'env_override',
71
72
  'PROMETHEUS_PORT': 'env_port'}
72
73
  with mock.patch.dict(os.environ, patched_env), \
73
74
  mock.patch.object(metric_utils, 'get_config_file',
@@ -75,7 +76,19 @@ class GetPrometheusClientTest(testtools.TestCase):
75
76
  mock.patch.object(prometheus_client.PrometheusAPIClient,
76
77
  "__init__", return_value=None) as m:
77
78
  metric_utils.get_prometheus_client()
78
- m.assert_called_with("env_overide:env_port")
79
+ m.assert_called_with("env_override:env_port", None, "")
80
+
81
+ def test_get_prometheus_client_prefix_in_env_variable(self):
82
+ patched_env = {'PROMETHEUS_HOST': 'env_override',
83
+ 'PROMETHEUS_PORT': 'env_port',
84
+ 'PROMETHEUS_ROOT_PATH': 'root_path_env'}
85
+ with mock.patch.dict(os.environ, patched_env), \
86
+ mock.patch.object(metric_utils, 'get_config_file',
87
+ return_value=None), \
88
+ mock.patch.object(prometheus_client.PrometheusAPIClient,
89
+ "__init__", return_value=None) as m:
90
+ metric_utils.get_prometheus_client()
91
+ m.assert_called_with("env_override:env_port", None, "root_path_env")
79
92
 
80
93
  def test_get_prometheus_client_missing_configuration(self):
81
94
  with mock.patch.dict(os.environ, {}), \
@@ -20,8 +20,11 @@ import yaml
20
20
  from observabilityclient.prometheus_client import PrometheusAPIClient
21
21
 
22
22
 
23
- DEFAULT_CONFIG_LOCATIONS = [os.environ["HOME"] + "/.config/openstack/",
24
- "/etc/openstack/"]
23
+ DEFAULT_CONFIG_LOCATIONS = (
24
+ [os.path.join(os.environ["HOME"], ".config/openstack/"), "/etc/openstack/"]
25
+ if "HOME" in os.environ
26
+ else ["/etc/openstack/"]
27
+ )
25
28
  CONFIG_FILE_NAME = "prometheus.yaml"
26
29
  LOG = logging.getLogger(__name__)
27
30
 
@@ -42,10 +45,11 @@ def get_config_file():
42
45
  return None
43
46
 
44
47
 
45
- def get_prometheus_client():
48
+ def get_prometheus_client(session=None):
46
49
  host = None
47
50
  port = None
48
51
  ca_cert = None
52
+ root_path = ""
49
53
  conf_file = get_config_file()
50
54
  if conf_file is not None:
51
55
  conf = yaml.safe_load(conf_file)
@@ -55,6 +59,8 @@ def get_prometheus_client():
55
59
  port = conf['port']
56
60
  if 'ca_cert' in conf:
57
61
  ca_cert = conf['ca_cert']
62
+ if 'root_path' in conf:
63
+ root_path = conf['root_path']
58
64
  conf_file.close()
59
65
 
60
66
  # NOTE(jwysogla): We allow to overide the prometheus.yaml by
@@ -65,10 +71,12 @@ def get_prometheus_client():
65
71
  port = os.environ['PROMETHEUS_PORT']
66
72
  if 'PROMETHEUS_CA_CERT' in os.environ:
67
73
  ca_cert = os.environ['PROMETHEUS_CA_CERT']
74
+ if 'PROMETHEUS_ROOT_PATH' in os.environ:
75
+ root_path = os.environ['PROMETHEUS_ROOT_PATH']
68
76
  if host is None or port is None:
69
77
  raise ConfigurationError("Can't find prometheus host and "
70
78
  "port configuration.")
71
- client = PrometheusAPIClient(f"{host}:{port}")
79
+ client = PrometheusAPIClient(f"{host}:{port}", session, root_path)
72
80
  if ca_cert is not None:
73
81
  client.set_ca_cert(ca_cert)
74
82
  return client
@@ -14,9 +14,9 @@
14
14
 
15
15
  import keystoneauth1.session
16
16
 
17
+ from observabilityclient import rbac
17
18
  from observabilityclient.utils.metric_utils import get_prometheus_client
18
19
  from observabilityclient.v1 import python_api
19
- from observabilityclient.v1 import rbac
20
20
 
21
21
 
22
22
  class Client(object):
@@ -38,6 +38,9 @@ class Client(object):
38
38
 
39
39
  self.session = session
40
40
 
41
- self.prometheus_client = get_prometheus_client()
41
+ self.prometheus_client = get_prometheus_client(session)
42
42
  self.query = python_api.QueryManager(self)
43
- self.rbac = rbac.Rbac(self, self.session, disable_rbac)
43
+ self.rbac = rbac.PromQLRbac(
44
+ self.prometheus_client,
45
+ self.session.get_project_id()
46
+ )
@@ -23,11 +23,11 @@ class QueryManager(base.Manager):
23
23
  :param disable_rbac: Disables rbac injection if set to True
24
24
  :type disable_rbac: boolean
25
25
  """
26
- if disable_rbac or self.client.rbac.disable_rbac:
26
+ if disable_rbac:
27
27
  metric_names = self.prom.label_values("__name__")
28
28
  return sorted(metric_names)
29
29
  else:
30
- match = f"{{{format_labels(self.client.rbac.default_labels)}}}"
30
+ match = f"{{{format_labels(self.client.rbac.labels)}}}"
31
31
  metrics = self.prom.series(match)
32
32
  if metrics == []:
33
33
  return []
@@ -40,9 +40,12 @@ class QueryManager(base.Manager):
40
40
  :param disable_rbac: Disables rbac injection if set to True
41
41
  :type disable_rbac: boolean
42
42
  """
43
- enriched = self.client.rbac.append_rbac(name,
44
- disable_rbac=disable_rbac)
45
- last_metric_query = f"last_over_time({enriched}[5m])"
43
+ query = ""
44
+ if disable_rbac:
45
+ query = name
46
+ else:
47
+ query = self.client.rbac.append_rbac_labels(name)
48
+ last_metric_query = f"last_over_time({query}[5m])"
46
49
  return self.prom.query(last_metric_query)
47
50
 
48
51
  def query(self, query, disable_rbac=False):
@@ -63,7 +66,8 @@ class QueryManager(base.Manager):
63
66
  :param disable_rbac: Disables rbac injection if set to True
64
67
  :type disable_rbac: boolean
65
68
  """
66
- query = self.client.rbac.enrich_query(query, disable_rbac=disable_rbac)
69
+ if not disable_rbac:
70
+ query = self.client.rbac.modify_query(query)
67
71
  return self.prom.query(query)
68
72
 
69
73
  def delete(self, matches, start=None, end=None):
@@ -9,4 +9,6 @@ Leif Madsen <lmadsen@redhat.com>
9
9
  Marihan Girgis mgirgisf@redhat.com
10
10
  Martin Magr <mmagr@redhat.com>
11
11
  Martin Mágr <mmagr@redhat.com>
12
+ OpenStack Release Bot <infra-root@openstack.org>
12
13
  Takashi Kajinami <kajinamit@oss.nttdata.com>
14
+ Victoria Martinez de la Cruz <victoria@redhat.com>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-observabilityclient
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: OpenStack Observability Client
5
5
  Home-page: https://infrawatch.github.io/documentation/
6
6
  Author: OpenStack
@@ -2,30 +2,30 @@ 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=hyxENjNO6NLrH6G4muyAeEEtFTBa9d5OozjwpzNpJVA,2262
5
- observabilityclient/prometheus_client.py,sha256=NcZAJRZzcuNFVJGdROwZBdwzpaV98_Ywcw29QBf7g18,7052
5
+ observabilityclient/prometheus_client.py,sha256=yn0cOj08CUYLNydyh3sc1vTPGwplxZeMiyNN4l52aoY,7457
6
+ observabilityclient/rbac.py,sha256=Rw2jyEl-xGb2U6wi7mDjJxTR9kGpIt8xOKOUOFvjq1Q,6327
6
7
  observabilityclient/tests/functional/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
8
  observabilityclient/tests/functional/base.py,sha256=SXbPiksFH7aER-zZjIWxz5nwCqq5f1MYWth1tlFLwcs,6523
8
9
  observabilityclient/tests/functional/test_cli.py,sha256=QqU8BCGUnh4IlwnGr6hdDHjHp7TIM0jasDjReyZpz-Y,4856
9
10
  observabilityclient/tests/functional/test_python_api.py,sha256=NJBqBTEW_POoxI8CvMlNhWhDNAU3sQVKjRdXM2NboeU,3310
10
11
  observabilityclient/tests/unit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
12
  observabilityclient/tests/unit/test_cli.py,sha256=TMKjb0IXwbMkm6frvfTqClOa5ZGGWKywyheyTeWl3i8,5964
12
- observabilityclient/tests/unit/test_prometheus_client.py,sha256=oPD5AALoyR0haQ8u0RYEasFSicKjT1RW9g_sFYCtLNM,18801
13
- observabilityclient/tests/unit/test_python_api.py,sha256=xOKCdLH52AF9Vf7tu4ja-O6zsC-FEH7Y-DJQ7x8jzy4,4760
14
- observabilityclient/tests/unit/test_rbac.py,sha256=PxBlvSGqGVFBSjQB1MGcyuBX5qcv6peQKSL5R_Aid9c,5692
15
- observabilityclient/tests/unit/test_utils.py,sha256=-sYsiYTuvcb71SX2KewrxkPinMEGLzUi0wnfBHsOIOA,7387
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
16
17
  observabilityclient/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
- observabilityclient/utils/metric_utils.py,sha256=K_G23krVIENNSPNsj2w9AkmCk2MDum9K3DkWNQl3Bro,3425
18
+ observabilityclient/utils/metric_utils.py,sha256=dOn0LC4HFCM2xLJl6ifYHGlAJXI42QRhi_ggBHF5Si0,3699
18
19
  observabilityclient/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
20
  observabilityclient/v1/base.py,sha256=2AMQU8WKbERvfoiRdOPIlogzH1ds_Son4Gr7fjGdGQ4,2260
20
21
  observabilityclient/v1/cli.py,sha256=ln7GsnbW95n90oFGw4zLiwHDjY0YHBxkRBzID-j6ZmA,4028
21
- observabilityclient/v1/client.py,sha256=q5bH-N9uCWi9boVVYhLv6M7NYLxMnmgGBupg2uqvgRo,1643
22
- observabilityclient/v1/python_api.py,sha256=nTsaasNBMVNrGW5CNSf7-o2oOKsea_u38GEbs2-8Gkw,3916
23
- observabilityclient/v1/rbac.py,sha256=cnscaSzcbY7AEcLHcjpXBeHHZ12k5-hYmVwXsMTBSjQ,6115
24
- python_observabilityclient-0.4.0.dist-info/AUTHORS,sha256=zWBYZ8rVSwsa_gRSTSrH1_WEtElkJl2LO7nWANcVao0,432
25
- python_observabilityclient-0.4.0.dist-info/LICENSE,sha256=qyh9xnj_IPtYWzClm5mZxCWRKTr2eUP_iLcU28DIvCw,11343
26
- python_observabilityclient-0.4.0.dist-info/METADATA,sha256=qqBvE_I-2DBK1SWhWWo01QBvXzbISkpmeVT304ANO5M,2998
27
- python_observabilityclient-0.4.0.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
28
- python_observabilityclient-0.4.0.dist-info/entry_points.txt,sha256=15rmai80pMRfBKZrk6yPNrRkAs2h63bwlcbQKq9fax4,424
29
- python_observabilityclient-0.4.0.dist-info/pbr.json,sha256=pdbs7sVnVCndbMaEPpoTrrs2jQhgqgrBFuTvBUaC--o,46
30
- python_observabilityclient-0.4.0.dist-info/top_level.txt,sha256=Lf7Fwm3hfK-X1JNRy19rVlrMUOyQShBBPwsCU3pz6yw,20
31
- python_observabilityclient-0.4.0.dist-info/RECORD,,
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,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.3.0)
2
+ Generator: setuptools (75.3.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -0,0 +1 @@
1
+ {"git_version": "ab8ce8f", "is_release": true}
@@ -1 +0,0 @@
1
- {"git_version": "df6c253", "is_release": true}