python-observabilityclient 0.1.0__py3-none-any.whl → 0.2.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.
Files changed (23) hide show
  1. observabilityclient/i18n.py +21 -0
  2. observabilityclient/prometheus_client.py +12 -5
  3. observabilityclient/tests/functional/__init__.py +0 -0
  4. observabilityclient/tests/functional/base.py +188 -0
  5. observabilityclient/tests/functional/test_cli.py +161 -0
  6. observabilityclient/tests/functional/test_python_api.py +94 -0
  7. observabilityclient/tests/unit/test_cli.py +42 -18
  8. observabilityclient/tests/unit/test_rbac.py +1 -2
  9. observabilityclient/tests/unit/test_utils.py +72 -1
  10. observabilityclient/utils/metric_utils.py +16 -11
  11. observabilityclient/v1/base.py +2 -1
  12. observabilityclient/v1/cli.py +9 -10
  13. observabilityclient/v1/rbac.py +1 -1
  14. {python_observabilityclient-0.1.0.dist-info → python_observabilityclient-0.2.0.dist-info}/AUTHORS +2 -0
  15. {python_observabilityclient-0.1.0.dist-info → python_observabilityclient-0.2.0.dist-info}/METADATA +4 -4
  16. python_observabilityclient-0.2.0.dist-info/RECORD +31 -0
  17. python_observabilityclient-0.2.0.dist-info/pbr.json +1 -0
  18. python_observabilityclient-0.1.0.dist-info/RECORD +0 -26
  19. python_observabilityclient-0.1.0.dist-info/pbr.json +0 -1
  20. {python_observabilityclient-0.1.0.dist-info → python_observabilityclient-0.2.0.dist-info}/LICENSE +0 -0
  21. {python_observabilityclient-0.1.0.dist-info → python_observabilityclient-0.2.0.dist-info}/WHEEL +0 -0
  22. {python_observabilityclient-0.1.0.dist-info → python_observabilityclient-0.2.0.dist-info}/entry_points.txt +0 -0
  23. {python_observabilityclient-0.1.0.dist-info → python_observabilityclient-0.2.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,21 @@
1
+ # Copyright 2023 OpenStack Foundation
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+ # not use this file except in compliance with the License. You may obtain
5
+ # a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+ # License for the specific language governing permissions and limitations
13
+ # under the License.
14
+ #
15
+
16
+ import oslo_i18n
17
+
18
+ _translators = oslo_i18n.TranslatorFactory(domain='observabilityclient')
19
+
20
+ # The primary translation function using the well-known name "_"
21
+ _ = _translators.primary
@@ -15,6 +15,7 @@
15
15
  import logging
16
16
 
17
17
  import requests
18
+ import simplejson
18
19
 
19
20
 
20
21
  LOG = logging.getLogger(__name__)
@@ -27,9 +28,15 @@ class PrometheusAPIClientError(Exception):
27
28
  def __str__(self) -> str:
28
29
  if self.resp.status_code != requests.codes.ok:
29
30
  if self.resp.status_code != 204:
30
- decoded = self.resp.json()
31
- if 'error' in decoded:
32
- return f'[{self.resp.status_code}] {decoded["error"]}'
31
+ try:
32
+ decoded = self.resp.json()
33
+ if 'error' in decoded:
34
+ return f'[{self.resp.status_code}] {decoded["error"]}'
35
+ except simplejson.errors.JSONDecodeError:
36
+ # If an https endpoint is accessed as http,
37
+ # we get 400 status with plain text instead of
38
+ # json and decoding it raises exception.
39
+ return f'[{self.resp.status_code}] {self.resp.text}'
33
40
  return f'[{self.resp.status_code}] {self.resp.reason}'
34
41
  else:
35
42
  decoded = self.resp.json()
@@ -47,14 +54,14 @@ class PrometheusAPIClientError(Exception):
47
54
  return f'[{decoded.status}]'
48
55
 
49
56
 
50
- class PrometheusMetric:
57
+ class PrometheusMetric(object):
51
58
  def __init__(self, input):
52
59
  self.timestamp = input['value'][0]
53
60
  self.labels = input['metric']
54
61
  self.value = input['value'][1]
55
62
 
56
63
 
57
- class PrometheusAPIClient:
64
+ class PrometheusAPIClient(object):
58
65
  def __init__(self, host):
59
66
  self._host = host
60
67
  self._session = requests.Session()
File without changes
@@ -0,0 +1,188 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+
13
+ # base.py file taken and modified from the openstackclient functional tests
14
+
15
+ import json
16
+ import logging
17
+ import os
18
+ import shlex
19
+ import subprocess
20
+
21
+ from observabilityclient import client
22
+
23
+ from keystoneauth1 import loading
24
+ from keystoneauth1 import session
25
+ import os_client_config
26
+ from tempest.lib.cli import output_parser
27
+ from tempest.lib import exceptions
28
+ import testtools
29
+
30
+ ADMIN_CLOUD = os.environ.get('OS_ADMIN_CLOUD', 'devstack-admin')
31
+ LOG = logging.getLogger(__name__)
32
+
33
+
34
+ class PythonAPITestCase(testtools.TestCase):
35
+ def _getKeystoneSession(self):
36
+ conf = os_client_config.OpenStackConfig()
37
+ creds = conf.get_one_cloud(cloud=ADMIN_CLOUD).get_auth_args()
38
+ ks_creds = dict(
39
+ auth_url=creds["auth_url"],
40
+ username=creds["username"],
41
+ password=creds["password"],
42
+ project_name=creds["project_name"],
43
+ user_domain_id=creds["user_domain_id"],
44
+ project_domain_id=creds["project_domain_id"])
45
+ loader = loading.get_plugin_loader("password")
46
+ auth = loader.load_from_options(**ks_creds)
47
+ return session.Session(auth=auth)
48
+
49
+ def setUp(self):
50
+ super(PythonAPITestCase, self).setUp()
51
+ self.client = client.Client(
52
+ 1,
53
+ self._getKeystoneSession()
54
+ )
55
+
56
+
57
+ def execute(cmd, fail_ok=False, merge_stderr=False):
58
+ """Execute specified command for the given action."""
59
+ LOG.debug('Executing: %s', cmd)
60
+ cmdlist = shlex.split(cmd)
61
+ stdout = subprocess.PIPE
62
+ stderr = subprocess.STDOUT if merge_stderr else subprocess.PIPE
63
+
64
+ proc = subprocess.Popen(cmdlist, stdout=stdout, stderr=stderr)
65
+
66
+ result_out, result_err = proc.communicate()
67
+ result_out = result_out.decode('utf-8')
68
+ LOG.debug('stdout: %s', result_out)
69
+ LOG.debug('stderr: %s', result_err)
70
+
71
+ if not fail_ok and proc.returncode != 0:
72
+ raise exceptions.CommandFailed(
73
+ proc.returncode,
74
+ cmd,
75
+ result_out,
76
+ result_err,
77
+ )
78
+
79
+ return result_out
80
+
81
+
82
+ class CliTestCase(testtools.TestCase):
83
+ @classmethod
84
+ def openstack(
85
+ cls,
86
+ cmd,
87
+ *,
88
+ cloud=ADMIN_CLOUD,
89
+ fail_ok=False,
90
+ parse_output=False,
91
+ ):
92
+ """Execute observabilityclient command for the given action.
93
+
94
+ :param cmd: A string representation of the command to execute.
95
+ :param cloud: The cloud to execute against. This can be a string, empty
96
+ string, or None. A string results in '--os-auth-type $cloud', an
97
+ empty string results in the '--os-auth-type' option being
98
+ omitted, and None resuts in '--os-auth-type none' for legacy
99
+ reasons.
100
+ :param fail_ok: If failure is permitted. If False (default), a command
101
+ failure will result in `~tempest.lib.exceptions.CommandFailed`
102
+ being raised.
103
+ :param parse_output: If true, pass the '-f json' parameter and decode
104
+ the output.
105
+ :returns: The output from the command.
106
+ :raises: `~tempest.lib.exceptions.CommandFailed` if the command failed
107
+ and ``fail_ok`` was ``False``.
108
+ """
109
+ auth_args = []
110
+ if cloud is None:
111
+ # Execute command with no auth
112
+ auth_args.append('--os-auth-type none')
113
+ elif cloud != '':
114
+ # Execute command with an explicit cloud specified
115
+ auth_args.append(f'--os-cloud {cloud}')
116
+
117
+ format_args = []
118
+ if parse_output:
119
+ format_args.append('-f json')
120
+
121
+ output = execute(
122
+ ' '.join(['openstack'] + auth_args + [cmd] + format_args),
123
+ fail_ok=fail_ok,
124
+ )
125
+
126
+ if parse_output:
127
+ return json.loads(output)
128
+ else:
129
+ return output
130
+
131
+ @classmethod
132
+ def assertOutput(cls, expected, actual):
133
+ if expected != actual:
134
+ raise Exception(expected + ' != ' + actual)
135
+
136
+ @classmethod
137
+ def assertInOutput(cls, expected, actual):
138
+ if expected not in actual:
139
+ raise Exception(expected + ' not in ' + actual)
140
+
141
+ @classmethod
142
+ def assertNotInOutput(cls, expected, actual):
143
+ if expected in actual:
144
+ raise Exception(expected + ' in ' + actual)
145
+
146
+ @classmethod
147
+ def assertsOutputNotNone(cls, observed):
148
+ if observed is None:
149
+ raise Exception('No output observed')
150
+
151
+ def assert_table_structure(self, items, field_names):
152
+ """Verify that all items have keys listed in field_names."""
153
+ for item in items:
154
+ for field in field_names:
155
+ self.assertIn(field, item)
156
+
157
+ def assert_show_fields(self, show_output, field_names):
158
+ """Verify that all items have keys listed in field_names."""
159
+ # field_names = ['name', 'description']
160
+ # show_output = [{'name': 'fc2b98d8faed4126b9e371eda045ade2'},
161
+ # {'description': 'description-821397086'}]
162
+ # this next line creates a flattened list of all 'keys' (like 'name',
163
+ # and 'description' out of the output
164
+ all_headers = [item for sublist in show_output for item in sublist]
165
+ for field_name in field_names:
166
+ self.assertIn(field_name, all_headers)
167
+
168
+ def parse_show_as_object(self, raw_output):
169
+ """Return a dict with values parsed from cli output."""
170
+ items = self.parse_show(raw_output)
171
+ o = {}
172
+ for item in items:
173
+ o.update(item)
174
+ return o
175
+
176
+ def parse_show(self, raw_output):
177
+ """Return list of dicts with item values parsed from cli output."""
178
+ items = []
179
+ table_ = output_parser.table(raw_output)
180
+ for row in table_['values']:
181
+ item = {}
182
+ item[row[0]] = row[1]
183
+ items.append(item)
184
+ return items
185
+
186
+ def parse_listing(self, raw_output):
187
+ """Return list of dicts with basic item parsed from cli output."""
188
+ return output_parser.listing(raw_output)
@@ -0,0 +1,161 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+
13
+ from observabilityclient.tests.functional import base
14
+ import time
15
+
16
+
17
+ class CliTestFunctionalRBACDisabled(base.CliTestCase):
18
+ """Functional tests for cli commands with disabled RBAC."""
19
+
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__"]
40
+ )
41
+ self.assertEqual(
42
+ "1",
43
+ metric["value"]
44
+ )
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"]
59
+ )
60
+
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
+ 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"]
93
+ )
94
+
95
+ 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"]
108
+ )
109
+
110
+
111
+ class CliTestFunctionalAdminCommands(base.CliTestCase):
112
+ """Functional tests for cli admin commands."""
113
+
114
+ def test_delete(self):
115
+ test_start_time = int(time.time())
116
+ query_before = self.openstack(
117
+ f'metric query prometheus_ready@{test_start_time} --disable-rbac',
118
+ parse_output=True,
119
+ )
120
+
121
+ values = [item.get("__name__") for item in query_before]
122
+ # Check, that the metric is present before the deletion
123
+ self.assertIn(
124
+ "prometheus_ready",
125
+ values
126
+ )
127
+
128
+ self.openstack(
129
+ 'metric delete prometheus_ready --disable-rbac',
130
+ parse_output=False,
131
+ )
132
+
133
+ query_after = self.openstack(
134
+ f'metric query prometheus_ready@{test_start_time} --disable-rbac',
135
+ parse_output=True,
136
+ )
137
+ values = [item.get("__name__") for item in query_after]
138
+ # Check, that the metric is not present after the deletion
139
+ self.assertNotIn(
140
+ "prometheus_ready",
141
+ values
142
+ )
143
+
144
+ def test_clean_tombstones(self):
145
+ # NOTE(jwysogla) There is not much to check here
146
+ # except for the fact, that the command doesn't
147
+ # raise an exception. Prometheus doesn't send any
148
+ # data back and we don't have a reliable way to query
149
+ # prometheus that this command did something.
150
+ self.openstack('metric clean-tombstones')
151
+
152
+ def test_snapshot(self):
153
+ cmd_output = self.openstack(
154
+ 'metric snapshot',
155
+ parse_output=True,
156
+ )
157
+ for name in cmd_output:
158
+ self.assertInOutput(
159
+ time.strftime('%Y%m%d'),
160
+ name.get("Snapshot file name")
161
+ )
@@ -0,0 +1,94 @@
1
+ # Copyright 2023 Red Hat, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+ # not use this file except in compliance with the License. You may obtain
5
+ # a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+ # License for the specific language governing permissions and limitations
13
+ # under the License.
14
+
15
+ from observabilityclient.tests.functional import base
16
+
17
+ import time
18
+
19
+
20
+ class PythonAPITestFunctionalRBACDisabled(base.PythonAPITestCase):
21
+ def test_list(self):
22
+ ret = self.client.query.list(disable_rbac=True)
23
+
24
+ self.assertIn("up", ret)
25
+
26
+ def test_show(self):
27
+ ret = self.client.query.show("up", disable_rbac=True)
28
+
29
+ for metric in ret:
30
+ self.assertEqual("up", metric.labels["__name__"])
31
+ self.assertEqual("1", metric.value)
32
+
33
+ def test_query(self):
34
+ ret = self.client.query.query("up", disable_rbac=True)
35
+
36
+ for metric in ret:
37
+ self.assertEqual("up", metric.labels["__name__"])
38
+ self.assertEqual("1", metric.value)
39
+
40
+
41
+ class PythonAPITestFunctionalRBACEnabled(base.PythonAPITestCase):
42
+ def test_list(self):
43
+ ret = self.client.query.list(disable_rbac=False)
44
+
45
+ self.assertIn("ceilometer_image_size", ret)
46
+ self.assertNotIn("up", ret)
47
+
48
+ def test_show(self):
49
+ ret = self.client.query.show("ceilometer_image_size",
50
+ disable_rbac=False)
51
+
52
+ for metric in ret:
53
+ self.assertEqual("ceilometer_image_size",
54
+ metric.labels["__name__"])
55
+ self.assertEqual("sg-core",
56
+ metric.labels["job"])
57
+
58
+ def test_query(self):
59
+ ret = self.client.query.query("ceilometer_image_size",
60
+ disable_rbac=False)
61
+
62
+ for metric in ret:
63
+ self.assertEqual("ceilometer_image_size",
64
+ metric.labels["__name__"])
65
+ self.assertEqual("sg-core", metric.labels["job"])
66
+
67
+
68
+ class PythonAPITestFunctionalAdminCommands(base.PythonAPITestCase):
69
+ def test_delete(self):
70
+ now = time.time()
71
+ metric_name = "prometheus_build_info"
72
+ query = f"{metric_name}@{now}"
73
+
74
+ query_before = self.client.query.query(query, disable_rbac=True)
75
+
76
+ for metric in query_before:
77
+ self.assertEqual(metric_name, metric.labels["__name__"])
78
+
79
+ self.client.query.delete(metric_name)
80
+
81
+ query_after = self.client.query.query(query, disable_rbac=True)
82
+ self.assertEqual([], query_after)
83
+
84
+ def test_clean_tombstones(self):
85
+ # NOTE(jwysogla) There is not much to check here
86
+ # except for the fact, that the command doesn't
87
+ # raise an exception. Prometheus doesn't send any
88
+ # data back and we don't have a reliable way to query
89
+ # prometheus that this command did something.
90
+ self.client.query.clean_tombstones()
91
+
92
+ def test_snapshot(self):
93
+ ret = self.client.query.snapshot()
94
+ self.assertIn(time.strftime("%Y%m%d"), ret)
@@ -28,30 +28,31 @@ class CliTest(testtools.TestCase):
28
28
  self.client.query = mock.Mock()
29
29
 
30
30
  def test_list(self):
31
- args_enabled = {'disable_rbac': False}
32
- args_disabled = {'disable_rbac': True}
33
-
34
31
  metric_names = ['name1', 'name2', 'name3']
35
32
  expected = (['metric_name'], [['name1'], ['name2'], ['name3']])
36
33
  cli_list = cli.List(mock.Mock(), mock.Mock())
37
34
 
35
+ parser = cli_list.get_parser("metric list")
36
+ test_parsed_args_enabled = parser.parse_args([
37
+ ])
38
+ test_parsed_args_disabled = parser.parse_args([
39
+ "--disable-rbac"
40
+ ])
41
+
38
42
  with mock.patch.object(metric_utils, 'get_client',
39
43
  return_value=self.client), \
40
44
  mock.patch.object(self.client.query, 'list',
41
45
  return_value=metric_names) as m:
42
- ret1 = cli_list.take_action(args_enabled)
46
+ ret1 = cli_list.take_action(test_parsed_args_enabled)
43
47
  m.assert_called_with(disable_rbac=False)
44
48
 
45
- ret2 = cli_list.take_action(args_disabled)
49
+ ret2 = cli_list.take_action(test_parsed_args_disabled)
46
50
  m.assert_called_with(disable_rbac=True)
47
51
 
48
52
  self.assertEqual(ret1, expected)
49
53
  self.assertEqual(ret2, expected)
50
54
 
51
55
  def test_show(self):
52
- args_enabled = {'name': 'metric_name', 'disable_rbac': False}
53
- args_disabled = {'name': 'metric_name', 'disable_rbac': True}
54
-
55
56
  metric = {
56
57
  'value': [123456, 12],
57
58
  'metric': {'label1': 'value1'}
@@ -61,15 +62,24 @@ class CliTest(testtools.TestCase):
61
62
 
62
63
  cli_show = cli.Show(mock.Mock(), mock.Mock())
63
64
 
65
+ parser = cli_show.get_parser("metric show")
66
+ test_parsed_args_enabled = parser.parse_args([
67
+ "metric_name"
68
+ ])
69
+ test_parsed_args_disabled = parser.parse_args([
70
+ "metric_name",
71
+ "--disable-rbac"
72
+ ])
73
+
64
74
  with mock.patch.object(metric_utils, 'get_client',
65
75
  return_value=self.client), \
66
76
  mock.patch.object(self.client.query, 'show',
67
77
  return_value=prom_metric) as m:
68
78
 
69
- ret1 = cli_show.take_action(args_enabled)
79
+ ret1 = cli_show.take_action(test_parsed_args_enabled)
70
80
  m.assert_called_with('metric_name', disable_rbac=False)
71
81
 
72
- ret2 = cli_show.take_action(args_disabled)
82
+ ret2 = cli_show.take_action(test_parsed_args_disabled)
73
83
  m.assert_called_with('metric_name', disable_rbac=True)
74
84
 
75
85
  self.assertEqual(ret1, expected)
@@ -78,8 +88,6 @@ class CliTest(testtools.TestCase):
78
88
  def test_query(self):
79
89
  query = ("some_query{label!~'not_this_value'} - "
80
90
  "sum(second_metric{label='this'})")
81
- args_enabled = {'query': query, 'disable_rbac': False}
82
- args_disabled = {'query': query, 'disable_rbac': True}
83
91
 
84
92
  metric = {
85
93
  'value': [123456, 12],
@@ -91,32 +99,48 @@ class CliTest(testtools.TestCase):
91
99
 
92
100
  cli_query = cli.Query(mock.Mock(), mock.Mock())
93
101
 
102
+ parser = cli_query.get_parser("metric query")
103
+ test_parsed_args_enabled = parser.parse_args([
104
+ query
105
+ ])
106
+ test_parsed_args_disabled = parser.parse_args([
107
+ query,
108
+ "--disable-rbac"
109
+ ])
110
+
94
111
  with mock.patch.object(metric_utils, 'get_client',
95
112
  return_value=self.client), \
96
113
  mock.patch.object(self.client.query, 'query',
97
114
  return_value=prom_metric) as m:
98
115
 
99
- ret1 = cli_query.take_action(args_enabled)
116
+ ret1 = cli_query.take_action(test_parsed_args_enabled)
100
117
  m.assert_called_with(query, disable_rbac=False)
101
118
 
102
- ret2 = cli_query.take_action(args_disabled)
119
+ ret2 = cli_query.take_action(test_parsed_args_disabled)
103
120
  m.assert_called_with(query, disable_rbac=True)
104
121
 
105
122
  self.assertEqual(ret1, expected)
106
123
  self.assertEqual(ret2, expected)
107
124
 
108
125
  def test_delete(self):
109
- matches = "some_label_name"
110
- args = {'matches': matches, 'start': 0, 'end': 10}
126
+ match1 = "some_label_name"
127
+ match2 = "some_label_name2"
111
128
 
112
129
  cli_delete = cli.Delete(mock.Mock(), mock.Mock())
113
130
 
131
+ parser = cli_delete.get_parser("metric delete")
132
+ test_parsed_args = parser.parse_args([
133
+ match1, match2,
134
+ "--start", "0",
135
+ "--end", "10"
136
+ ])
137
+
114
138
  with mock.patch.object(metric_utils, 'get_client',
115
139
  return_value=self.client), \
116
140
  mock.patch.object(self.client.query, 'delete') as m:
117
141
 
118
- cli_delete.take_action(args)
119
- m.assert_called_with(matches, 0, 10)
142
+ cli_delete.take_action(test_parsed_args)
143
+ m.assert_called_with([[match1, match2]], "0", "10")
120
144
 
121
145
  def test_clean_combstones(self):
122
146
  cli_clean_tombstones = cli.CleanTombstones(mock.Mock(), mock.Mock())
@@ -16,7 +16,6 @@ from unittest import mock
16
16
 
17
17
  from keystoneauth1.exceptions.auth_plugins import MissingAuthPlugin
18
18
  from keystoneauth1 import session
19
-
20
19
  import testtools
21
20
 
22
21
  from observabilityclient.v1 import rbac
@@ -44,7 +43,7 @@ class RbacTest(testtools.TestCase):
44
43
  with mock.patch.object(session.Session, 'get_project_id',
45
44
  side_effect=MissingAuthPlugin()):
46
45
  r = rbac.Rbac("client", session.Session(), False)
47
- self.assertEqual(r.project_id, None)
46
+ self.assertIsNone(r.project_id)
48
47
 
49
48
  def test_enrich_query(self):
50
49
  test_cases = [
@@ -40,7 +40,7 @@ class GetConfigFileTest(testtools.TestCase):
40
40
  with mock.patch.object(os.path, 'exists', return_value=False) as m:
41
41
  ret = metric_utils.get_config_file()
42
42
  m.call_args_list == expected
43
- self.assertEqual(ret, None)
43
+ self.assertIsNone(ret)
44
44
 
45
45
 
46
46
  class GetPrometheusClientTest(testtools.TestCase):
@@ -70,6 +70,8 @@ class GetPrometheusClientTest(testtools.TestCase):
70
70
  patched_env = {'PROMETHEUS_HOST': 'env_overide',
71
71
  'PROMETHEUS_PORT': 'env_port'}
72
72
  with mock.patch.dict(os.environ, patched_env), \
73
+ mock.patch.object(metric_utils, 'get_config_file',
74
+ return_value=None), \
73
75
  mock.patch.object(prometheus_client.PrometheusAPIClient,
74
76
  "__init__", return_value=None) as m:
75
77
  metric_utils.get_prometheus_client()
@@ -77,6 +79,8 @@ class GetPrometheusClientTest(testtools.TestCase):
77
79
 
78
80
  def test_get_prometheus_client_missing_configuration(self):
79
81
  with mock.patch.dict(os.environ, {}), \
82
+ mock.patch.object(metric_utils, 'get_config_file',
83
+ return_value=None), \
80
84
  mock.patch.object(prometheus_client.PrometheusAPIClient,
81
85
  "__init__", return_value=None):
82
86
  self.assertRaises(metric_utils.ConfigurationError,
@@ -124,3 +128,70 @@ class Metrics2ColsTest(testtools.TestCase):
124
128
 
125
129
  ret = metric_utils.metrics2cols(input_metrics)
126
130
  self.assertEqual(expected, ret)
131
+
132
+ def test_metrics2cols_column_ordering(self):
133
+ metric = {
134
+ 'value': [
135
+ 1234567,
136
+ 5
137
+ ],
138
+ 'metric': {
139
+ 'a_label1': 'value1',
140
+ 'b_label2': 'value2',
141
+ }
142
+ }
143
+ input_metrics = [prometheus_client.PrometheusMetric(metric)]
144
+ expected = (['a_label1', 'b_label2', 'value'],
145
+ [['value1', 'value2', 5]])
146
+
147
+ ret = metric_utils.metrics2cols(input_metrics)
148
+ self.assertEqual(expected, ret)
149
+
150
+ metric = {
151
+ 'value': [
152
+ 1234567,
153
+ 5
154
+ ],
155
+ 'metric': {
156
+ 'b_label1': 'value1',
157
+ 'a_label2': 'value2',
158
+ }
159
+ }
160
+ input_metrics = [prometheus_client.PrometheusMetric(metric)]
161
+ expected = (['a_label2', 'b_label1', 'value'],
162
+ [['value2', 'value1', 5]])
163
+
164
+ ret = metric_utils.metrics2cols(input_metrics)
165
+ self.assertEqual(expected, ret)
166
+
167
+ metric1 = {
168
+ 'value': [
169
+ 1234567,
170
+ 5
171
+ ],
172
+ 'metric': {
173
+ 'b_label1': 'value1',
174
+ 'a_label2': 'value2',
175
+ }
176
+ }
177
+ metric2 = {
178
+ 'value': [
179
+ 1234567,
180
+ 5
181
+ ],
182
+ 'metric': {
183
+ 'b_label1': 'value1',
184
+ 'a_label2': 'value2',
185
+ 'd_label3': 'value3',
186
+ 'c_label4': 'value4',
187
+ }
188
+ }
189
+ input_metrics = [prometheus_client.PrometheusMetric(metric1),
190
+ prometheus_client.PrometheusMetric(metric2)]
191
+ expected = (['a_label2', 'b_label1', 'c_label4', 'd_label3', 'value'],
192
+ [['value2', 'value1', '', '', 5],
193
+ ['value2', 'value1', 'value4', 'value3', 5]]
194
+ )
195
+
196
+ ret = metric_utils.metrics2cols(input_metrics)
197
+ self.assertEqual(expected, ret)
@@ -45,6 +45,7 @@ def get_config_file():
45
45
  def get_prometheus_client():
46
46
  host = None
47
47
  port = None
48
+ ca_cert = None
48
49
  conf_file = get_config_file()
49
50
  if conf_file is not None:
50
51
  conf = yaml.safe_load(conf_file)
@@ -52,6 +53,8 @@ def get_prometheus_client():
52
53
  host = conf['host']
53
54
  if 'port' in conf:
54
55
  port = conf['port']
56
+ if 'ca_cert' in conf:
57
+ ca_cert = conf['ca_cert']
55
58
  conf_file.close()
56
59
 
57
60
  # NOTE(jwysogla): We allow to overide the prometheus.yaml by
@@ -60,10 +63,15 @@ def get_prometheus_client():
60
63
  host = os.environ['PROMETHEUS_HOST']
61
64
  if 'PROMETHEUS_PORT' in os.environ:
62
65
  port = os.environ['PROMETHEUS_PORT']
66
+ if 'PROMETHEUS_CA_CERT' in os.environ:
67
+ ca_cert = os.environ['PROMETHEUS_CA_CERT']
63
68
  if host is None or port is None:
64
69
  raise ConfigurationError("Can't find prometheus host and "
65
70
  "port configuration.")
66
- return PrometheusAPIClient(f"{host}:{port}")
71
+ client = PrometheusAPIClient(f"{host}:{port}")
72
+ if ca_cert is not None:
73
+ client.set_ca_cert(ca_cert)
74
+ return client
67
75
 
68
76
 
69
77
  def get_client(obj):
@@ -90,18 +98,15 @@ def format_labels(d: dict) -> str:
90
98
 
91
99
 
92
100
  def metrics2cols(m):
93
- cols = []
101
+ # get all label keys
102
+ cols = list(set().union(*(d.labels.keys() for d in m)))
103
+ cols.sort()
104
+ cols.append("value")
94
105
  fields = []
95
- first = True
96
106
  for metric in m:
97
- row = []
107
+ row = [""] * len(cols)
98
108
  for key, value in metric.labels.items():
99
- if first:
100
- cols.append(key)
101
- row.append(value)
102
- if first:
103
- cols.append("value")
104
- row.append(metric.value)
109
+ row[cols.index(key)] = value
110
+ row[cols.index("value")] = metric.value
105
111
  fields.append(row)
106
- first = False
107
112
  return cols, fields
@@ -14,7 +14,8 @@
14
14
  #
15
15
 
16
16
  from osc_lib.command import command
17
- from osc_lib.i18n import _
17
+
18
+ from observabilityclient.i18n import _
18
19
 
19
20
 
20
21
  class ObservabilityBaseCommand(command.Command):
@@ -14,8 +14,7 @@
14
14
 
15
15
  from cliff import lister
16
16
 
17
- from osc_lib.i18n import _
18
-
17
+ from observabilityclient.i18n import _
19
18
  from observabilityclient.utils import metric_utils
20
19
  from observabilityclient.v1 import base
21
20
 
@@ -25,7 +24,7 @@ class List(base.ObservabilityBaseCommand, lister.Lister):
25
24
 
26
25
  def take_action(self, parsed_args):
27
26
  client = metric_utils.get_client(self)
28
- metrics = client.query.list(disable_rbac=parsed_args['disable_rbac'])
27
+ metrics = client.query.list(disable_rbac=parsed_args.disable_rbac)
29
28
  return ["metric_name"], [[m] for m in metrics]
30
29
 
31
30
 
@@ -41,8 +40,8 @@ class Show(base.ObservabilityBaseCommand, lister.Lister):
41
40
 
42
41
  def take_action(self, parsed_args):
43
42
  client = metric_utils.get_client(self)
44
- metric = client.query.show(parsed_args['name'],
45
- disable_rbac=parsed_args['disable_rbac'])
43
+ metric = client.query.show(parsed_args.name,
44
+ disable_rbac=parsed_args.disable_rbac)
46
45
  ret = metric_utils.metrics2cols(metric)
47
46
  return ret
48
47
 
@@ -59,8 +58,8 @@ class Query(base.ObservabilityBaseCommand, lister.Lister):
59
58
 
60
59
  def take_action(self, parsed_args):
61
60
  client = metric_utils.get_client(self)
62
- metric = client.query.query(parsed_args['query'],
63
- disable_rbac=parsed_args['disable_rbac'])
61
+ metric = client.query.query(parsed_args.query,
62
+ disable_rbac=parsed_args.disable_rbac)
64
63
  ret = metric_utils.metrics2cols(metric)
65
64
  return ret
66
65
 
@@ -89,9 +88,9 @@ class Delete(base.ObservabilityBaseCommand):
89
88
 
90
89
  def take_action(self, parsed_args):
91
90
  client = metric_utils.get_client(self)
92
- return client.query.delete(parsed_args['matches'],
93
- parsed_args['start'],
94
- parsed_args['end'])
91
+ return client.query.delete(parsed_args.matches,
92
+ parsed_args.start,
93
+ parsed_args.end)
95
94
 
96
95
 
97
96
  class CleanTombstones(base.ObservabilityBaseCommand):
@@ -23,7 +23,7 @@ class ObservabilityRbacError(Exception):
23
23
  pass
24
24
 
25
25
 
26
- class Rbac():
26
+ class Rbac(object):
27
27
  def __init__(self, client, session, disable_rbac=False):
28
28
  self.client = client
29
29
  self.session = session
@@ -1,5 +1,6 @@
1
1
  Chris Sibbitt <csibbitt@redhat.com>
2
2
  Erno Kuvaja <jokke@usr.fi>
3
+ Ghanshyam Mann <gmann@ghanshyammann.com>
3
4
  Jaromir Wysoglad <jwysogla@redhat.com>
4
5
  Jaromír Wysoglad <jwysogla@redhat.com>
5
6
  Leif Madsen <leif@leifmadsen.com>
@@ -7,3 +8,4 @@ Leif Madsen <lmadsen@redhat.com>
7
8
  Marihan Girgis mgirgisf@redhat.com
8
9
  Martin Magr <mmagr@redhat.com>
9
10
  Martin Mágr <mmagr@redhat.com>
11
+ Takashi Kajinami <kajinamit@oss.nttdata.com>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-observabilityclient
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: OpenStack Observability Client
5
5
  Home-page: https://infrawatch.github.io/documentation/
6
6
  Author: OpenStack
@@ -18,11 +18,11 @@ Classifier: Programming Language :: Python
18
18
  Classifier: Programming Language :: Python :: Implementation :: CPython
19
19
  Classifier: Programming Language :: Python :: 3 :: Only
20
20
  Classifier: Programming Language :: Python :: 3
21
- Classifier: Programming Language :: Python :: 3.6
22
- Classifier: Programming Language :: Python :: 3.7
23
21
  Classifier: Programming Language :: Python :: 3.8
24
22
  Classifier: Programming Language :: Python :: 3.9
25
- Requires-Python: >=3.6
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Requires-Python: >=3.8
26
26
  Description-Content-Type: text/markdown; charset=UTF-8
27
27
  Requires-Dist: cliff (>=1.14.0)
28
28
  Requires-Dist: keystoneauth1 (>=1.0.0)
@@ -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=iVylMmgSDwBXuuGQjkixwrcfsHiS5NqEYrMB57R2pyQ,7467
6
+ observabilityclient/tests/functional/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ observabilityclient/tests/functional/base.py,sha256=SXbPiksFH7aER-zZjIWxz5nwCqq5f1MYWth1tlFLwcs,6523
8
+ observabilityclient/tests/functional/test_cli.py,sha256=QqU8BCGUnh4IlwnGr6hdDHjHp7TIM0jasDjReyZpz-Y,4856
9
+ observabilityclient/tests/functional/test_python_api.py,sha256=NJBqBTEW_POoxI8CvMlNhWhDNAU3sQVKjRdXM2NboeU,3310
10
+ observabilityclient/tests/unit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ 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
16
+ observabilityclient/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ observabilityclient/utils/metric_utils.py,sha256=K_G23krVIENNSPNsj2w9AkmCk2MDum9K3DkWNQl3Bro,3425
18
+ observabilityclient/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ observabilityclient/v1/base.py,sha256=g7r0GrtbUR6BDWPPvTRL1pF0hZbcq1evYQTeXqlI7X8,2556
20
+ 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.2.0.dist-info/AUTHORS,sha256=BVS3DtpzGMTE2D4RpV_lVctcBfQHGK5G1yWrNcrI1hI,393
25
+ python_observabilityclient-0.2.0.dist-info/LICENSE,sha256=qyh9xnj_IPtYWzClm5mZxCWRKTr2eUP_iLcU28DIvCw,11343
26
+ python_observabilityclient-0.2.0.dist-info/METADATA,sha256=R4cRUoo7LAdA-Cp09cE_jK8yQx6EhAZnaPSjAMoOu4g,3440
27
+ python_observabilityclient-0.2.0.dist-info/WHEEL,sha256=g4nMs7d-Xl9-xC9XovUrsDHGXt-FT0E17Yqo92DEfvY,92
28
+ python_observabilityclient-0.2.0.dist-info/entry_points.txt,sha256=KVIgt6aQmLXBvbWakAMnBATcmYAd4U99I6UOyYpWD2c,425
29
+ python_observabilityclient-0.2.0.dist-info/pbr.json,sha256=WS-7Hx84xzfqmQFMjGB5pTZKhFjhExgXQNhl-drJCAg,46
30
+ python_observabilityclient-0.2.0.dist-info/top_level.txt,sha256=Lf7Fwm3hfK-X1JNRy19rVlrMUOyQShBBPwsCU3pz6yw,20
31
+ python_observabilityclient-0.2.0.dist-info/RECORD,,
@@ -0,0 +1 @@
1
+ {"git_version": "0dea42c", "is_release": true}
@@ -1,26 +0,0 @@
1
- observabilityclient/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- observabilityclient/client.py,sha256=cfRb816p6Ips9t2cdWvmSJ1uGrtTEHXQnctoExrLA5A,828
3
- observabilityclient/plugin.py,sha256=hyxENjNO6NLrH6G4muyAeEEtFTBa9d5OozjwpzNpJVA,2262
4
- observabilityclient/prometheus_client.py,sha256=LhbmoaHUnZ9wM7Pxhkf-dBHdSRr78WENy6ibdGtMBr4,7077
5
- observabilityclient/tests/unit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- observabilityclient/tests/unit/test_cli.py,sha256=KGLNrGMxY3rmg2wlihYXszIvGvLrEgbyj59QnRO_XBw,5317
7
- observabilityclient/tests/unit/test_prometheus_client.py,sha256=oPD5AALoyR0haQ8u0RYEasFSicKjT1RW9g_sFYCtLNM,18801
8
- observabilityclient/tests/unit/test_python_api.py,sha256=xOKCdLH52AF9Vf7tu4ja-O6zsC-FEH7Y-DJQ7x8jzy4,4760
9
- observabilityclient/tests/unit/test_rbac.py,sha256=p8HG1Se_nIwHoUXhYA6dZ1xvZOd_0GvAFKse_5dRzrQ,5698
10
- observabilityclient/tests/unit/test_utils.py,sha256=6YrTC2uYB5p9yQmgzNAShXLtRn34dHhe7VbnLP53TB0,5129
11
- observabilityclient/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
- observabilityclient/utils/metric_utils.py,sha256=JnA_GoV8iJpzUaT-XkkEGcZ_R3UvjF5wrj6cNwqdOwQ,3153
13
- observabilityclient/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
- observabilityclient/v1/base.py,sha256=kUcpJ57acbXeRPHp56aPecmfKhrZsUrZqIB7lTjKLLk,2543
15
- observabilityclient/v1/cli.py,sha256=2MBBKjOdsUFiOzg0oj5MoqpSsQ1jYewjKZebPeMHka8,4041
16
- observabilityclient/v1/client.py,sha256=q5bH-N9uCWi9boVVYhLv6M7NYLxMnmgGBupg2uqvgRo,1643
17
- observabilityclient/v1/python_api.py,sha256=nTsaasNBMVNrGW5CNSf7-o2oOKsea_u38GEbs2-8Gkw,3916
18
- observabilityclient/v1/rbac.py,sha256=TDeOnHq7cIY1wCiPQxvwuHgCZHO8r8X8dfA45QfGWTQ,6109
19
- python_observabilityclient-0.1.0.dist-info/AUTHORS,sha256=xBZ3WdDIJLV_3ThE0nOL_W3ABB3k2hClEc97nXNNBzY,307
20
- python_observabilityclient-0.1.0.dist-info/LICENSE,sha256=qyh9xnj_IPtYWzClm5mZxCWRKTr2eUP_iLcU28DIvCw,11343
21
- python_observabilityclient-0.1.0.dist-info/METADATA,sha256=KkfjvXsKjyiOgHZYWdMoLVZJAidBUyUKAvaefGoRmn8,3438
22
- python_observabilityclient-0.1.0.dist-info/WHEEL,sha256=g4nMs7d-Xl9-xC9XovUrsDHGXt-FT0E17Yqo92DEfvY,92
23
- python_observabilityclient-0.1.0.dist-info/entry_points.txt,sha256=KVIgt6aQmLXBvbWakAMnBATcmYAd4U99I6UOyYpWD2c,425
24
- python_observabilityclient-0.1.0.dist-info/pbr.json,sha256=eV2_8cuiUXuq_4YBE_f6B_kkHT58VyzSj_5FXE7VoQw,46
25
- python_observabilityclient-0.1.0.dist-info/top_level.txt,sha256=Lf7Fwm3hfK-X1JNRy19rVlrMUOyQShBBPwsCU3pz6yw,20
26
- python_observabilityclient-0.1.0.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- {"git_version": "2668773", "is_release": true}