Browse Source

python-pankoclient is no longer maintained.

The contents of this repository are still available in the Git source
code management system. To see the contents of this repository before it
reached its end of life, please check out the previous commit with
"git checkout HEAD^1".

For any further questions, please email
openstack-discuss@lists.openstack.org or join #openstack-telemetry on OFTC.

Change-Id: I10a6f35f14b5883f62e4675216dee7a11f749443
changes/92/791692/3
Matthias Runge 1 year ago
parent
commit
4acf636975
  1. 6
      .coveragerc
  2. 7
      .testr.conf
  3. 5
      .zuul.yaml
  4. 17
      CONTRIBUTING.rst
  5. 4
      HACKING.rst
  6. 176
      LICENSE
  7. 6
      MANIFEST.in
  8. 31
      README.rst
  9. 1
      bindep.txt
  10. 2
      doc/requirements.txt
  11. 27
      doc/source/api.rst
  12. 122
      doc/source/conf.py
  13. 4
      doc/source/contributing.rst
  14. 46
      doc/source/index.rst
  15. 8
      doc/source/installation.rst
  16. 42
      doc/source/osc_integrated_commands.rst
  17. 21
      pankoclient/__init__.py
  18. 42
      pankoclient/client.py
  19. 0
      pankoclient/common/__init__.py
  20. 374
      pankoclient/common/base.py
  21. 21
      pankoclient/common/i18n.py
  22. 193
      pankoclient/exceptions.py
  23. 65
      pankoclient/osc.py
  24. 170
      pankoclient/shell.py
  25. 0
      pankoclient/tests/__init__.py
  26. 0
      pankoclient/tests/functional/__init__.py
  27. 20
      pankoclient/tests/functional/base.py
  28. 0
      pankoclient/tests/unit/__init__.py
  29. 34
      pankoclient/tests/unit/base.py
  30. 0
      pankoclient/tests/unit/common/__init__.py
  31. 277
      pankoclient/tests/unit/common/test_base.py
  32. 148
      pankoclient/tests/unit/fakes.py
  33. 73
      pankoclient/tests/unit/test_osc_plugin.py
  34. 0
      pankoclient/tests/unit/v2/__init__.py
  35. 75
      pankoclient/tests/unit/v2/test_events.py
  36. 34
      pankoclient/utils.py
  37. 0
      pankoclient/v2/__init__.py
  38. 27
      pankoclient/v2/capabilities.py
  39. 27
      pankoclient/v2/capabilities_cli.py
  40. 40
      pankoclient/v2/client.py
  41. 89
      pankoclient/v2/events.py
  42. 153
      pankoclient/v2/events_cli.py
  43. 0
      releasenotes/notes/.placeholder
  44. 6
      releasenotes/notes/drop-py-2-7-08bf464fcf679d24.yaml
  45. 0
      releasenotes/source/_static/.placeholder
  46. 0
      releasenotes/source/_templates/.placeholder
  47. 283
      releasenotes/source/conf.py
  48. 15
      releasenotes/source/index.rst
  49. 6
      releasenotes/source/pike.rst
  50. 6
      releasenotes/source/queens.rst
  51. 6
      releasenotes/source/stein.rst
  52. 6
      releasenotes/source/train.rst
  53. 5
      releasenotes/source/unreleased.rst
  54. 6
      releasenotes/source/ussuri.rst
  55. 6
      releasenotes/source/victoria.rst
  56. 6
      releasenotes/source/wallaby.rst
  57. 13
      requirements.txt
  58. 55
      setup.cfg
  59. 20
      setup.py
  60. 47
      tox.ini

6
.coveragerc

@ -1,6 +0,0 @@
[run]
branch = True
source = pankoclient
[report]
ignore_errors = True

7
.testr.conf

@ -1,7 +0,0 @@
[DEFAULT]
test_command=OS_STDOUT_CAPTURE=${OS_STDOUT_CAPTURE:-1} \
OS_STDERR_CAPTURE=${OS_STDERR_CAPTURE:-1} \
OS_TEST_TIMEOUT=${OS_TEST_TIMEOUT:-60} \
${PYTHON:-python} -m subunit.run discover -t ./ . $LISTOPT $IDOPTION
test_id_option=--load-list $IDFILE
test_list_option=--list

5
.zuul.yaml

@ -1,5 +0,0 @@
- project:
templates:
- openstack-python3-xena-jobs
- publish-openstack-docs-pti
- openstackclient-plugin-jobs

17
CONTRIBUTING.rst

@ -1,17 +0,0 @@
If you would like to contribute to the development of OpenStack, you must
follow the steps in this page:
http://docs.openstack.org/infra/manual/developers.html
If you already have a good understanding of how the system works and your
OpenStack accounts are set up, you can skip to the development workflow
section of this documentation to learn how changes to OpenStack should be
submitted for review via the Gerrit tool:
http://docs.openstack.org/infra/manual/developers.html#development-workflow
Pull requests submitted through GitHub will be ignored.
Bugs should be filed on Launchpad, not GitHub:
https://bugs.launchpad.net/python-pankoclient

4
HACKING.rst

@ -1,4 +0,0 @@
python-pankoclient Style Commandments
=====================================
Read the OpenStack Style Commandments https://docs.openstack.org/hacking/latest/

176
LICENSE

@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

6
MANIFEST.in

@ -1,6 +0,0 @@
include AUTHORS
include ChangeLog
exclude .gitignore
exclude .gitreview
global-exclude *.pyc

31
README.rst

@ -1,26 +1,7 @@
==========================================
Python bindings to the OpenStack Panko API
==========================================
The contents of this repository are still available in the Git source
code management system. To see the contents of this repository before it
reached its end of life, please check out the previous commit with
"git checkout HEAD^1".
.. image:: https://img.shields.io/pypi/v/pankoclient.svg
:target: https://pypi.org/project/pankoclient/
:alt: Latest Version
This is a client library for Panko built on the Panko API. It provides a
Python API (the ``pankoclient`` module) and a OSC (the openstackclient CLI)
command-line tool (``openstack event``).
* Free software: Apache license
* `PyPi`_ - package installation
* `Online Documentation`_
* `Launchpad project`_ - release management
* `Blueprints`_ - feature specifications
* `Bugs`_ - issue tracking
* `Source`_
.. _PyPi: https://pypi.org/project/pankoclient
.. _Online Documentation: https://docs.openstack.org/python-pankoclient/latest/
.. _Launchpad project: https://launchpad.net/python-pankoclient
.. _Blueprints: https://blueprints.launchpad.net/python-pankoclient
.. _Bugs: https://bugs.launchpad.net/python-pankoclient
.. _Source: https://opendev.org/openstack/python-pankoclient
For any further questions, please email
openstack-discuss@lists.openstack.org or join #openstack-telemetry on OFTC.

1
bindep.txt

@ -1 +0,0 @@
python37 [platform:rpm py37]

2
doc/requirements.txt

@ -1,2 +0,0 @@
sphinx>=2.0.0,!=2.1.0 # BSD
openstackdocstheme>=2.2.1 # Apache-2.0

27
doc/source/api.rst

@ -1,27 +0,0 @@
The :mod:`pankoclient` Python API
=================================
.. module:: pankoclient
:synopsis: A client for the Panko API.
.. currentmodule:: pankoclient
Usage
-----
To use pankoclient in a project::
>>> from pankoclient.v2 import client
>>> panko = client.Client(...)
>>> panko.event.list()
Reference
---------
For more information, see the reference:
.. toctree::
:maxdepth: 2
ref/v2/index

122
doc/source/conf.py

@ -1,122 +0,0 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(BASE_DIR, "..", ".."))
sys.path.insert(0, ROOT)
sys.path.insert(0, BASE_DIR)
def gen_ref(ver, title, names):
refdir = os.path.join(BASE_DIR, "ref")
pkg = "pankoclient"
if ver:
pkg = "%s.%s" % (pkg, ver)
refdir = os.path.join(refdir, ver)
if not os.path.exists(refdir):
os.makedirs(refdir)
idxpath = os.path.join(refdir, "index.rst")
with open(idxpath, "w") as idx:
idx.write(("%(title)s\n"
"%(signs)s\n"
"\n"
".. toctree::\n"
" :maxdepth: 1\n"
"\n") % {"title": title, "signs": "=" * len(title)})
for name in names:
idx.write(" %s\n" % name)
rstpath = os.path.join(refdir, "%s.rst" % name)
with open(rstpath, "w") as rst:
rst.write(("%(title)s\n"
"%(signs)s\n"
"\n"
".. automodule:: %(pkg)s.%(name)s\n"
" :members:\n"
" :undoc-members:\n"
" :show-inheritance:\n"
" :noindex:\n")
% {"title": " ".join([n.capitalize()
for n in name.split("_")]),
"signs": "=" * len(name),
"pkg": pkg, "name": name})
gen_ref("v2", "Version 2 API", ["client"])
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'openstackdocstheme',
'sphinx.ext.autodoc',
#'sphinx.ext.intersphinx',
]
# autodoc generation is a bit aggressive and a nuisance when doing heavy
# text edit cycles.
# execute "export SPHINX_DEBUG=1" in your terminal to disable
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pankoclient'
copyright = u'2015, OpenStack Foundation'
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'native'
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme_path = ["."]
# html_theme = '_theme'
# html_static_path = ['static']
html_theme = 'openstackdocs'
# openstackdocstheme options
openstackdocs_repo_name = 'openstack/python-pankoclient'
openstackdocs_bug_project = 'python-pankoclient'
openstackdocs_bug_tag = ''
# Output file base name for HTML help builder.
htmlhelp_basename = '%sdoc' % project
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index',
'%s.tex' % project,
u'%s Documentation' % project,
u'OpenStack Foundation', 'manual'),
]
# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {'http://docs.python.org/': None}

4
doc/source/contributing.rst

@ -1,4 +0,0 @@
============
Contributing
============
.. include:: ../../CONTRIBUTING.rst

46
doc/source/index.rst

@ -1,46 +0,0 @@
.. pankoclient documentation master file, created by
sphinx-quickstart on Tue Jul 9 22:26:36 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Python bindings to the Panko API
================================
This is a client for Panko API. There's :doc:`a Python API
<api>` (the :mod:`pankoclient` module), and a set of event related commands
which are integrated with the OSC CLI tool. Each implements the entire Panko
API.
.. warning::
This is a new client to interact with Panko API. There may be differences
in functionality, syntax, and command line output when compared with the
event functionality provided by ceilometerclient.
.. seealso::
You may want to read the `Panko Developer Guide`__ -- the overview, at
least -- to get an idea of the concepts. By understanding the concepts
this library should make more sense.
__ https://docs.openstack.org/panko/latest/
Contents:
.. toctree::
:maxdepth: 2
installation
osc_integrated_commands
api
contributing
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

8
doc/source/installation.rst

@ -1,8 +0,0 @@
============
Installation
============
At the command line::
$ pip install pankoclient

42
doc/source/osc_integrated_commands.rst

@ -1,42 +0,0 @@
The OSC CLI plugins
===================
This program provides a set of event related commands which are performed by
OSC `openstack program`_. The `OpenStackClient`_ project provide a plugin
mechanism which supports loading other external projects' commands from
clients library entry points.
The event related commands begin with `openstack event` in `openstack`
command tool.
To configure the environment variables, see `openstack program`_.
.. _OpenStackClient: https://docs.openstack.org/python-openstackclient/latest/
.. _openstack program: https://docs.openstack.org/python-openstackclient/latest/cli/man/openstack.html
Examples
--------
List the capabilities of event interfaces::
openstack event capabilities list
List the events::
openstack event list
Show an event::
openstack event show <MESSAGE_ID>
List event types::
openstack event type list
List trait values of a specified event type and a trait name::
openstack event traits list <EVENT_TYPE> <TRAIT_NAME>
List traits definitions for a specified event type::
openstack event trait description <EVENT_TYPE>

21
pankoclient/__init__.py

@ -1,21 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright 2017 Huawei, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'pankoclient').version_string()

42
pankoclient/client.py

@ -1,42 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneauth1 import adapter
from oslo_utils import importutils
from osprofiler import web
from pankoclient import exceptions
def Client(version, *args, **kwargs):
module = 'pankoclient.v%s.client' % version
module = importutils.import_module(module)
client_class = getattr(module, 'Client')
return client_class(*args, **kwargs)
class SessionClient(adapter.Adapter):
def request(self, url, method, **kwargs):
kwargs.setdefault('headers', kwargs.get('headers', {}))
# NOTE(sileht): The standard call raises errors from
# keystoneauth, where we need to raise the pankoclient errors.
raise_exc = kwargs.pop('raise_exc', True)
kwargs['headers'].update(web.get_trace_id_headers())
resp = super(SessionClient, self).request(url,
method,
raise_exc=False,
**kwargs)
if raise_exc and resp.status_code >= 400:
raise exceptions.from_response(resp, url, method)
return resp, resp.json()

0
pankoclient/common/__init__.py

374
pankoclient/common/base.py

@ -1,374 +0,0 @@
# Copyright 2017 Huawei, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""
Base utilities to build API operation managers and objects on top of.
"""
import abc
import copy
from requests import Response
import six
from pankoclient import exceptions
def getid(obj):
"""Get obj's uuid or object itself if no uuid
Abstracts the common pattern of allowing both an object or
an object's ID (UUID) as a parameter when dealing with relationships.
"""
try:
return obj.uuid
except AttributeError:
return obj
class Manager(object):
"""Interacts with type of API
Managers interact with a particular type of API (instances, types, etc.)
and provide CRUD operations for them.
"""
resource_class = None
def __init__(self, api):
self.api = api
def _list(self, url, response_key=None, obj_class=None,
data=None, headers=None):
if headers is None:
headers = {}
resp, body = self.api.get(url, headers=headers)
if obj_class is None:
obj_class = self.resource_class
if response_key:
if response_key not in body:
body[response_key] = []
data = body[response_key]
else:
data = body
if all([isinstance(res, six.string_types) for res in data]):
items = data
else:
items = [obj_class(self, res, loaded=True) for res in data if res]
return ListWithMeta(items, resp)
def _delete(self, url, headers=None):
if headers is None:
headers = {}
resp, body = self.api.delete(url, headers=headers)
return self.convert_into_with_meta(body, resp)
def _update(self, url, data, response_key=None, return_raw=False,
headers=None):
if headers is None:
headers = {}
resp, body = self.api.patch(url, data=data, headers=headers)
if return_raw:
if response_key:
body = body[response_key]
return self.convert_into_with_meta(body, resp)
# PATCH requests may not return a body
if body:
if response_key:
return self.resource_class(self, body[response_key], resp=resp)
return self.resource_class(self, body, resp=resp)
else:
return StrWithMeta(body, resp)
def _update_all(self, url, data, response_key=None, return_raw=False,
headers=None):
if headers is None:
headers = {}
resp, body = self.api.put(url, data=data, headers=headers)
if return_raw:
if response_key:
body = body[response_key]
return self.convert_into_with_meta(body, resp)
# PUT requests may not return a body
if body:
if response_key:
return self.resource_class(self, body[response_key], resp=resp)
return self.resource_class(self, body, resp=resp)
else:
return StrWithMeta(body, resp)
def _create(self, url, data=None, response_key=None, return_raw=False,
headers=None):
if headers is None:
headers = {}
if data:
resp, body = self.api.post(url, data=data, headers=headers)
else:
resp, body = self.api.post(url, headers=headers)
if return_raw:
if response_key:
body = body[response_key]
return self.convert_into_with_meta(body, resp)
if response_key:
return self.resource_class(self, body[response_key], resp=resp)
return self.resource_class(self, body, resp=resp)
def _get(self, url, response_key=None, return_raw=False, headers=None):
if headers is None:
headers = {}
resp, body = self.api.get(url, headers=headers)
if return_raw:
if response_key:
body = body[response_key]
return self.convert_into_with_meta(body, resp)
if response_key:
return self.resource_class(self, body[response_key], loaded=True,
resp=resp)
return self.resource_class(self, body, loaded=True, resp=resp)
def convert_into_with_meta(self, item, resp):
if isinstance(item, six.string_types):
if six.PY2 and isinstance(item, six.text_type):
return UnicodeWithMeta(item, resp)
else:
return StrWithMeta(item, resp)
elif isinstance(item, six.binary_type):
return BytesWithMeta(item, resp)
elif isinstance(item, list):
return ListWithMeta(item, resp)
elif isinstance(item, tuple):
return TupleWithMeta(item, resp)
elif item is None:
return TupleWithMeta((), resp)
else:
return DictWithMeta(item, resp)
@six.add_metaclass(abc.ABCMeta)
class ManagerWithFind(Manager):
"""Manager with additional `find()`/`findall()` methods."""
@abc.abstractmethod
def list(self):
pass
def find(self, **kwargs):
"""Find a single item with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side.
"""
matches = self.findall(**kwargs)
num = len(matches)
if num == 0:
msg = "No %s matching %s." % (self.resource_class.__name__, kwargs)
raise exceptions.NotFound(msg)
elif num > 1:
raise exceptions.NoUniqueMatch
else:
return self.get(matches[0].uuid)
def findall(self, **kwargs):
"""Find all items with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side.
"""
found = []
searches = kwargs.items()
for obj in self.list():
try:
if all(getattr(obj, attr) == value
for (attr, value) in searches):
found.append(obj)
except AttributeError:
continue
return found
class RequestIdMixin(object):
"""Wrapper class to expose x-openstack-request-id to the caller."""
def request_ids_setup(self):
self.x_openstack_request_ids = []
@property
def request_ids(self):
return self.x_openstack_request_ids
def append_request_ids(self, resp):
"""Add request_ids as an attribute to the object
:param resp: Response object or list of Response objects
"""
if isinstance(resp, list):
# Add list of request_ids if response is of type list.
for resp_obj in resp:
self._append_request_id(resp_obj)
elif resp is not None:
# Add request_ids if response contains single object.
self._append_request_id(resp)
def _append_request_id(self, resp):
if isinstance(resp, Response):
# Extract 'X-Openstack-Request-Id' from headers if
# response is a Response object.
request_id = (resp.headers.get('Openstack-Request-Id') or
resp.headers.get('x-openstack-request-id') or
resp.headers.get('x-compute-request-id'))
else:
# If resp is of type string or None.
request_id = resp
if request_id not in self.x_openstack_request_ids:
self.x_openstack_request_ids.append(request_id)
class Resource(RequestIdMixin):
"""Represents an instance of an object
A resource represents a particular instance of an object (instance, type,
etc). This is pretty much just a bag for attributes.
:param manager: BaseManager object
:param info: dictionary representing resource attributes
:param loaded: prevent lazy-loading if set to True
:param resp: Response or list of Response objects
"""
def __init__(self, manager, info, loaded=False, resp=None):
self.manager = manager
self._info = info
self._add_details(info)
self._loaded = loaded
self.request_ids_setup()
self.append_request_ids(resp)
def _add_details(self, info):
for (k, v) in six.iteritems(info):
try:
setattr(self, k, v)
self._info[k] = v
except AttributeError:
# In this case we already defined the attribute on the class
pass
def __setstate__(self, d):
for k, v in d.items():
setattr(self, k, v)
def __getattr__(self, k):
if k not in self.__dict__:
# NOTE(RuiChen): disallow lazy-loading if already loaded once
if not self.is_loaded():
self.get()
return self.__getattr__(k)
raise AttributeError(k)
else:
return self.__dict__[k]
def __repr__(self):
reprkeys = sorted(k for k in self.__dict__.keys() if k[0] != '_' and
k not in ('manager', 'x_openstack_request_ids'))
info = ", ".join("%s=%s" % (k, getattr(self, k)) for k in reprkeys)
return "<%s %s>" % (self.__class__.__name__, info)
def get(self):
# set_loaded() first ... so if we have to bail, we know we tried.
self.set_loaded(True)
if not hasattr(self.manager, 'get'):
return
new = self.manager.get(self.uuid)
if new:
self._add_details(new._info)
# The 'request_ids' attribute has been added,
# so store the request id to it instead of _info
self.append_request_ids(new.request_ids)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self._info == other._info
def __ne__(self, other):
return not self.__eq__(other)
def is_loaded(self):
return self._loaded
def set_loaded(self, val):
self._loaded = val
def to_dict(self):
return copy.deepcopy(self._info)
class ListWithMeta(list, RequestIdMixin):
def __init__(self, values, resp):
super(ListWithMeta, self).__init__(values)
self.request_ids_setup()
self.append_request_ids(resp)
class DictWithMeta(dict, RequestIdMixin):
def __init__(self, values, resp):
super(DictWithMeta, self).__init__(values)
self.request_ids_setup()
self.append_request_ids(resp)
class TupleWithMeta(tuple, RequestIdMixin):
def __new__(cls, values, resp):
return super(TupleWithMeta, cls).__new__(cls, values)
def __init__(self, values, resp):
self.request_ids_setup()
self.append_request_ids(resp)
class StrWithMeta(str, RequestIdMixin):
def __new__(cls, value, resp):
return super(StrWithMeta, cls).__new__(cls, value)
def __init__(self, values, resp):
self.request_ids_setup()
self.append_request_ids(resp)
class BytesWithMeta(six.binary_type, RequestIdMixin):
def __new__(cls, value, resp):
return super(BytesWithMeta, cls).__new__(cls, value)
def __init__(self, values, resp):
self.request_ids_setup()
self.append_request_ids(resp)
if six.PY2:
class UnicodeWithMeta(six.text_type, RequestIdMixin):
def __new__(cls, value, resp):
return super(UnicodeWithMeta, cls).__new__(cls, value)
def __init__(self, values, resp):
self.request_ids_setup()
self.append_request_ids(resp)

21
pankoclient/common/i18n.py

@ -1,21 +0,0 @@
# Copyright 2017 Huawei, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='pankoclient')
# The primary translation function using the well-known name "_"
_ = _translators.primary

193
pankoclient/exceptions.py

@ -1,193 +0,0 @@
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ClientException(Exception):
"""The base exception class for all exceptions this library raises."""
message = 'Unknown Error'
http_status = 'N/A'
def __init__(self, message=None, request_id=None,
url=None, method=None):
self.message = message or self.__class__.message
self.request_id = request_id
self.url = url
self.method = method
# NOTE(jd) for backward compat
@property
def code(self):
return self.http_status
def __str__(self):
formatted_string = "%s (HTTP %s)" % (self.message, self.http_status)
if self.request_id:
formatted_string += " (Request-ID: %s)" % self.request_id
return formatted_string
class RetryAfterException(ClientException):
"""The base exception for ClientExceptions that use Retry-After header."""
def __init__(self, *args, **kwargs):
try:
self.retry_after = int(kwargs.pop('retry_after'))
except (KeyError, ValueError):
self.retry_after = 0
super(RetryAfterException, self).__init__(*args, **kwargs)
class MutipleMeaningException(object):
"""An mixin for exception that can be enhanced by reading the details"""
class CommandError(Exception):
pass
class BadRequest(ClientException):
"""HTTP 400 - Bad request: you sent some malformed data."""
http_status = 400
message = "Bad request"
class Unauthorized(ClientException):
"""HTTP 401 - Unauthorized: bad credentials."""
http_status = 401
message = "Unauthorized"
class Forbidden(ClientException):
"""HTTP 403 - Forbidden:
your credentials don't give you access to this resource.
"""
http_status = 403
message = "Forbidden"
class NotFound(ClientException):
"""HTTP 404 - Not found"""
http_status = 404
message = "Not found"
class MethodNotAllowed(ClientException):
"""HTTP 405 - Method Not Allowed"""
http_status = 405
message = "Method Not Allowed"
class NotAcceptable(ClientException):
"""HTTP 406 - Not Acceptable"""
http_status = 406
message = "Not Acceptable"
class Conflict(ClientException):
"""HTTP 409 - Conflict"""
http_status = 409
message = "Conflict"
class OverLimit(RetryAfterException):
"""HTTP 413 - Over limit:
you're over the API limits for this time period.
"""
http_status = 413
message = "Over limit"
class RateLimit(RetryAfterException):
"""HTTP 429 - Rate limit:
you've sent too many requests for this time period.
"""
http_status = 429
message = "Rate limit"
class NoUniqueMatch(Exception):
pass
class NotImplemented(ClientException):
"""HTTP 501 - Not Implemented:
the server does not support this operation.
"""
http_status = 501
message = "Not Implemented"
_error_classes = [BadRequest, Unauthorized, Forbidden, NotFound,
MethodNotAllowed, NotAcceptable, Conflict, OverLimit,
RateLimit, NotImplemented]
_error_classes_enhanced = {}
_code_map = dict(
(c.http_status, (c, _error_classes_enhanced.get(c, [])))
for c in _error_classes)
def from_response(response, url, method=None):
"""Return an instance of one of the ClientException on an requests response.
Usage::
resp = requests.request(...)
if resp.status_code != 200:
raise exception_from_response(resp)
"""
if response.status_code:
cls, enhanced_classes = _code_map.get(response.status_code,
(ClientException, []))
req_id = response.headers.get("x-openstack-request-id")
content_type = response.headers.get("Content-Type", "").split(";")[0]
kwargs = {
'method': method,
'url': url,
'request_id': req_id,
}
if "retry-after" in response.headers:
kwargs['retry_after'] = response.headers.get('retry-after')
if content_type == "application/json":
try:
body = response.json()
except ValueError:
pass
else:
error_message = body.get('error_message', {})
try:
desc = error_message.get('faultstring')
except AttributeError:
desc = error_message
for enhanced_cls in enhanced_classes:
if enhanced_cls.match.match(desc):
cls = enhanced_cls
break
kwargs['message'] = desc
elif content_type.startswith("text/"):
kwargs['message'] = response.text
if not kwargs.get('message'):
kwargs.pop('message', None)
exception = cls(**kwargs)
if isinstance(exception, ClientException) and response.status_code:
exception.http_status = response.status_code
return exception

65
pankoclient/osc.py

@ -1,65 +0,0 @@
# Copyright 2017 Huawei, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import logging
from osc_lib import utils
from pankoclient.common.i18n import _
LOG = logging.getLogger(__name__)
DEFAULT_EVENT_API_VERSION = '2'
API_VERSION_OPTION = 'os_event_api_version'
API_NAME = 'event'
API_VERSIONS = {
'2': 'pankoclient.v2.client.Client',
}
def make_client(instance):
"""Returns an event service client"""
panko_client = utils.get_client_class(
API_NAME,
instance._api_version[API_NAME],
API_VERSIONS)
LOG.debug('Instantiating event client: %s', panko_client)
endpoint = instance.get_endpoint_for_service_type(
API_NAME,
region_name=instance.region_name,
interface=instance.interface,
)
kwargs = {'session': instance.session,
'endpoint_override': endpoint}
client = panko_client(**kwargs)
return client
def build_option_parser(parser):
"""Hook to add global options"""
parser.add_argument(
'--os-event-api-version',
metavar='<event-api-version>',
default=utils.env(
'OS_EVENT_API_VERSION',
default=DEFAULT_EVENT_API_VERSION),
help=(_('Event API version, default=%s '
'(Env: OS_EVENT_API_VERSION)') %
DEFAULT_EVENT_API_VERSION)
)
return parser

170
pankoclient/shell.py

@ -1,170 +0,0 @@
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import os
import sys
import warnings
from cliff import app
from cliff import commandmanager
from keystoneauth1 import exceptions
from keystoneauth1 import loading
from pankoclient import __version__
from pankoclient import client
from pankoclient.v2 import capabilities_cli
from pankoclient.v2 import events_cli
class PankoCommandManager(commandmanager.CommandManager):
SHELL_COMMANDS = {
"event list": events_cli.EventList,
"event show": events_cli.EventShow,
"event type list": events_cli.EventTypeList,
"event trait list": events_cli.EventTraitList,
"event trait description": events_cli.EventTraitDescription,
"capabilities list": capabilities_cli.CliCapabilitiesList,
}
def load_commands(self, namespace):
for name, command_class in self.SHELL_COMMANDS.items():
self.add_command(name, command_class)
class PankoShell(app.App):
def __init__(self):
super(PankoShell, self).__init__(
description='Panko command line client',
version=__version__,
command_manager=PankoCommandManager(None),
deferred_help=True,
)
self._client = None
def build_option_parser(self, description, version):
"""Return an argparse option parser for this application.
Subclasses may override this method to extend
the parser with more global options.
:param description: full description of the application
:paramtype description: str
:param version: version number for the application
:paramtype version: str
"""
parser = super(PankoShell, self).build_option_parser(description,
version)
# Global arguments, one day this should go to keystoneauth1
parser.add_argument(
'--os-region-name',
metavar='<auth-region-name>',
dest='region_name',
default=os.environ.get('OS_REGION_NAME'),
help='Authentication region name (Env: OS_REGION_NAME)')
parser.add_argument(
'--os-interface',
metavar='<interface>',
dest='interface',
choices=['admin', 'public', 'internal'],
default=os.environ.get('OS_INTERFACE'),
help='Select an interface type.'
' Valid interface types: [admin, public, internal].'
' (Env: OS_INTERFACE)')
parser.add_argument(
'--panko-api-version',
default=os.environ.get('PANKO_API_VERSION', '2'),
help='Defaults to env[PANKO_API_VERSION] or 2.')
parser.add_argument(
'--panko-endpoint',
metavar='<endpoint>',
dest='endpoint',
default=os.environ.get('PANKO_ENDPOINT'),
help='Aodh endpoint (Env: PANKO_ENDPOINT)')
loading.register_session_argparse_arguments(parser=parser)
loading.register_auth_argparse_arguments(
parser=parser, argv=sys.argv, default="password")
return parser
@property
def client(self):
# NOTE(sileht): we lazy load the client to not
# load/connect auth stuffs
if self._client is None:
if hasattr(self.options, "endpoint"):
endpoint_override = self.options.endpoint
else:
endpoint_override = None
auth_plugin = loading.load_auth_from_argparse_arguments(
self.options)
session = loading.load_session_from_argparse_arguments(
self.options, auth=auth_plugin)
self._client = client.Client(self.options.panko_api_version,
session=session,
interface=self.options.interface,
region_name=self.options.region_name,
endpoint_override=endpoint_override)
return self._client
def clean_up(self, cmd, result, err):
if isinstance(err, exceptions.HttpError) and err.details:
print(err.details, file=sys.stderr)
def configure_logging(self):
if self.options.debug:
# --debug forces verbose_level 3
# Set this here so cliff.app.configure_logging() can work
self.options.verbose_level = 3
super(PankoShell, self).configure_logging()
root_logger = logging.getLogger('')
# Set logging to the requested level
if self.options.verbose_level == 0:
# --quiet
root_logger.setLevel(logging.ERROR)
warnings.simplefilter("ignore")
elif self.options.verbose_level == 1:
# This is the default case, no --debug, --verbose or --quiet
root_logger.setLevel(logging.WARNING)
warnings.simplefilter("ignore")
elif self.options.verbose_level == 2:
# One --verbose
root_logger.setLevel(logging.INFO)
warnings.simplefilter("once")
elif self.options.verbose_level >= 3:
# Two or more --verbose
root_logger.setLevel(logging.DEBUG)
# Hide some useless message
requests_log = logging.getLogger("requests")
cliff_log = logging.getLogger('cliff')
stevedore_log = logging.getLogger('stevedore')
iso8601_log = logging.getLogger("iso8601")
cliff_log.setLevel(logging.ERROR)
stevedore_log.setLevel(logging.ERROR)
iso8601_log.setLevel(logging.ERROR)
if self.options.debug:
requests_log.setLevel(logging.DEBUG)
else:
requests_log.setLevel(logging.ERROR)