Retire python-monascaclient repository

This repository is being retired as part of the Monasca project
retirement. The project content has been replaced with a retirement
notice.

Needed-By: I3cb522ce8f51424b64e93c1efaf0dfd1781cd5ac
Change-Id: Icbcce52b26ee4db120286b11ef1746c304baa2d7
Signed-off-by: Goutham Pacha Ravi <gouthampravi@gmail.com>
This commit is contained in:
Goutham Pacha Ravi
2025-08-11 22:15:14 -07:00
parent 860840dd20
commit bef42432f5
68 changed files with 7 additions and 5010 deletions

View File

@@ -1,3 +0,0 @@
[DEFAULT]
test_path=${OS_TEST_PATH:-./monascaclient/tests}
top_dir=./

View File

@@ -1,56 +0,0 @@
- project:
templates:
- openstack-cover-jobs
- openstack-python3-zed-jobs
- publish-openstack-docs-pti
- check-requirements
- release-notes-jobs-python3
check:
jobs:
- build-monasca-docker-image
post:
jobs:
- publish-monasca-client-docker-image
periodic:
jobs:
- publish-monasca-client-docker-image
release:
jobs:
- publish-monasca-client-docker-image
- job:
name: publish-monasca-client-docker-image
parent: build-monasca-docker-image
post-run: playbooks/docker-publish.yml
required-projects:
- openstack/monasca-common
vars:
publisher: true
secrets:
- doker_hub_login_client
- secret:
name: doker_hub_login_client
data:
user: !encrypted/pkcs1-oaep
- QdHgQ9lGfeOypCKTX9funuwbHCVRhUGfyswosl9whSskzy1EhztLSPpP5PPHg/ZM0Ag8o
VAHT6La7oroTDeWYcDJmN8Zc5mslQlcskwoq9TN/VWEhY36+OF3k938Zr78URwOT5Hqm4
ch+itjmydrQOrqcCwJ3ROrrJ2XpIMainz567U1HYuUari9B3zOUTW3xJfqbJ8UJIn/Irj
qEHn4Rn/RT3fOBcLwZfWJOcuwes8dsQykXNufLxXy2UGpdcHlE6lAAnRBgN/EPBxtqpAB
j+TO3s3yJLCIXDPIV+nST8z6EbvYc+woM4O1PN0AQ/tfyulFGvDTJNIdKenUBD99rBBJS
RCBZ0hhVgqDE4y4fcHh6STde0UHUQgwdX9lbdC2MGZah0bjUWG67QMwdtiiBwktbz3nza
a7yjd6/6di3zstDDGRLvZ5+vJ0cE/4eeWUmXcq2c0dtggaFDXYhOIoM1xfHKNvMN6QjM1
kETvG2aw/PyNYIJkNic19Qk7UbOrgKduZUA6K17xQ5lqIJn/JfRVQyvoi0pLMCsa1NSe+
wlpg9acJ46l0licRJ8o+QA02cFcrl9gBY5x0WwO3N/+LOxc40L+hHJi2vzduQO0ikCYa4
Lerew8vrpf2EZ3JV5JEuIQ0/q5V5ZXhCeJQ6JBdLusYF3LzHRkX+7DCt3UMgaU=
password: !encrypted/pkcs1-oaep
- uZOFnKJzCV26Ea3KtPmK0WaTCV6YqLgS0Y5BolGq4MahKftVXxDbWRtVMQWnwx8mMugmh
A8mtchoyvrIvH5gjU7SmvVYAyH5KJGdKnb/9jbYTJ/Zq9f2CFd10hlomIUIlbDixAIMmV
rbcexomEY5b15lF9F4I3ovwPEsqu0YcGMW7ABPdZaZx5JGDgYXXGWpy3CFvVV/MIzLbV+
wgByN7RsBNEFY44/xLTBkjN4RHOWTo1hFLeblI2pRJ40fzPw6fuUpeG1oPV/l4h9cjTgq
KMr4RuxxvCI3D0nWmq8SrIJ446erEldolJtpKRLqn1GTcGgyQbUgiXA0Nd44sFAcmwTBz
vK4rgD9Akhz/bsV6P8P5x25YoU6oS8Vws4mKu+iw3TWn0e+467oFvw+PD4e3+JbSSofyh
6gVRsXK+Ls7YMNdnoAe8XXh76IBfC639olAgFU7ewtcsOLAiVrqIIynWmprBJZ2apEBxs
jRNQpBgkTtUaaBcb3uGY3Fcip7PDcjcApYoaLHAUi2P2+o5gatsmySLb64g4O3rddn7Wf
8uSWv123X4zvXIk3V7FmCeSXgamVuZKpRHbFIeq9S+13ze1HBce6s36egoiGTfCMq5wLr
XwRwytGr8JoI4c8YIQXffYxJhhbgA9Qn+FalsrJIQNR03GnA2oUKKNsZExwcPs=

View File

@@ -1,19 +0,0 @@
The source repository for this project can be found at:
https://opendev.org/openstack/python-monascaclient
Pull requests submitted through GitHub are not monitored.
To start contributing to OpenStack, follow the steps in the contribution guide
to set up and use Gerrit:
https://docs.openstack.org/contributors/code-and-documentation/quick-start.html
Bugs should be filed on Storyboard:
https://storyboard.openstack.org/#!/project/880
For more specific information about contributing to this repository, see the
Monasca contributor guide:
https://docs.openstack.org/monasca-api/latest/contributor/contributing.html

View File

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

View File

@@ -1,32 +1,9 @@
========================
Team and repository tags
========================
This project is no longer maintained.
.. image:: https://governance.openstack.org/tc/badges/python-monascaclient.svg
:target: https://governance.openstack.org/tc/reference/tags/index.html
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".
.. Change things from this point on
Python bindings to the Monasca API
==================================
.. image:: https://img.shields.io/pypi/v/python-monascaclient.svg
:target: https://pypi.python.org/pypi/python-monascaclient/
:alt: Latest Version
This is a client library for Monasca built to interface with the Monasca API.
It provides a Python API (the ``monascaclient`` module) and a command-line tool
(``monasca``).
* License: Apache License, Version 2.0
* `PyPi`_ - package installation
* `Online Documentation`_
* `Bugs`_ - issue tracking (we use *bug* tag to differentiate from new features)
* `Source`_
* `Release Notes`_
.. _PyPi: https://pypi.python.org/pypi/python-monascaclient
.. _Online Documentation: https://docs.openstack.org/python-monascaclient/latest/
.. _Bugs: https://storyboard.openstack.org/#!/project/880
.. _Source: https://opendev.org/openstack/python-monascaclient
.. _Release Notes: https://docs.openstack.org/releasenotes/python-monascaclient
For any further questions, please email openstack-discuss@lists.openstack.org
or join #openstack-dev on OFTC.

View File

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

View File

@@ -1,361 +0,0 @@
=========
Using CLI
=========
monasca CLI
-----------
.. toctree::
:maxdepth: 2
monasca CLI guide <monasca>
monasca CLI formatting <monasca-formatting>
monasca CLI debugging <monasca-debug>
Usage
-----
You'll find complete documentation on the shell by running
``monasca help``::
usage: monasca [--version] [-v | -q] [--log-file LOG_FILE] [-h] [--debug]
[--os-cloud <cloud-config-name>]
[--os-region-name <auth-region-name>]
[--os-cacert <ca-bundle-file>] [--os-cert <certificate-file>]
[--os-key <key-file>] [--verify | --insecure]
[--os-default-domain <auth-domain>]
[--os-interface <interface>] [--timing] [--os-beta-command]
[--os-auth-type <auth-type>] [--os-code <auth-code>]
[--os-protocol <auth-protocol>]
[--os-project-name <auth-project-name>]
[--os-trust-id <auth-trust-id>]
[--os-domain-name <auth-domain-name>]
[--os-user-domain-id <auth-user-domain-id>]
[--os-access-token-type <auth-access-token-type>]
[--os-default-domain-name <auth-default-domain-name>]
[--os-access-token-endpoint <auth-access-token-endpoint>]
[--os-access-token <auth-access-token>]
[--os-domain-id <auth-domain-id>]
[--os-user-domain-name <auth-user-domain-name>]
[--os-openid-scope <auth-openid-scope>]
[--os-user-id <auth-user-id>]
[--os-identity-provider <auth-identity-provider>]
[--os-username <auth-username>] [--os-auth-url <auth-auth-url>]
[--os-client-secret <auth-client-secret>]
[--os-default-domain-id <auth-default-domain-id>]
[--os-discovery-endpoint <auth-discovery-endpoint>]
[--os-client-id <auth-client-id>]
[--os-project-domain-name <auth-project-domain-name>]
[--os-project-domain-id <auth-project-domain-id>]
[--os-password <auth-password>]
[--os-redirect-uri <auth-redirect-uri>]
[--os-endpoint <auth-endpoint>] [--os-token <auth-token>]
[--os-passcode <auth-passcode>]
[--os-project-id <auth-project-id>]
[--monasca-api-url MONASCA_API_URL]
[--monasca-api-version MONASCA_API_VERSION]
Command-line interface to the OpenStack APIs
optional arguments:
--version show program's version number and exit
-v, --verbose Increase verbosity of output. Can be repeated.
-q, --quiet Suppress output except warnings and errors.
--log-file LOG_FILE Specify a file to log output. Disabled by default.
-h, --help Show help message and exit.
--debug Show tracebacks on errors.
--os-cloud <cloud-config-name>
Cloud name in clouds.yaml (Env: OS_CLOUD)
--os-region-name <auth-region-name>
Authentication region name (Env: OS_REGION_NAME)
--os-cacert <ca-bundle-file>
CA certificate bundle file (Env: OS_CACERT)
--os-cert <certificate-file>
Client certificate bundle file (Env: OS_CERT)
--os-key <key-file> Client certificate key file (Env: OS_KEY)
--verify Verify server certificate (default)
--insecure Disable server certificate verification
--os-default-domain <auth-domain>
Default domain ID, default=default. (Env:
OS_DEFAULT_DOMAIN)
--os-interface <interface>
Select an interface type. Valid interface types:
[admin, public, internal]. (Env: OS_INTERFACE)
--timing Print API call timing info
--os-beta-command Enable beta commands which are subject to change
--os-auth-type <auth-type>
Select an authentication type. Available types:
v2token, admin_token, v3oidcauthcode, v2password,
v3password, v3oidcaccesstoken, v3oidcpassword, token,
v3oidcclientcredentials, v3tokenlessauth, v3token,
v3totp, password. Default: selected based on --os-
username/--os-token (Env: OS_AUTH_TYPE)
--os-code <auth-code>
With v3oidcauthcode: OAuth 2.0 Authorization Code
(Env: OS_CODE)
--os-protocol <auth-protocol>
With v3oidcauthcode: Protocol for federated plugin
With v3oidcaccesstoken: Protocol for federated plugin
With v3oidcpassword: Protocol for federated plugin
With v3oidcclientcredentials: Protocol for federated
plugin (Env: OS_PROTOCOL)
--os-project-name <auth-project-name>
With v3oidcauthcode: Project name to scope to With
v3password: Project name to scope to With
v3oidcaccesstoken: Project name to scope to With
v3oidcpassword: Project name to scope to With token:
Project name to scope to With v3oidcclientcredentials:
Project name to scope to With v3tokenlessauth: Project
name to scope to With v3token: Project name to scope
to With v3totp: Project name to scope to With
password: Project name to scope to (Env:
OS_PROJECT_NAME)
--os-trust-id <auth-trust-id>
With v2token: Trust ID With v3oidcauthcode: Trust ID
With v2password: Trust ID With v3password: Trust ID
With v3oidcaccesstoken: Trust ID With v3oidcpassword:
Trust ID With token: Trust ID With
v3oidcclientcredentials: Trust ID With v3token: Trust
ID With v3totp: Trust ID With password: Trust ID (Env:
OS_TRUST_ID)
--os-domain-name <auth-domain-name>
With v3oidcauthcode: Domain name to scope to With
v3password: Domain name to scope to With
v3oidcaccesstoken: Domain name to scope to With
v3oidcpassword: Domain name to scope to With token:
Domain name to scope to With v3oidcclientcredentials:
Domain name to scope to With v3tokenlessauth: Domain
name to scope to With v3token: Domain name to scope to
With v3totp: Domain name to scope to With password:
Domain name to scope to (Env: OS_DOMAIN_NAME)
--os-user-domain-id <auth-user-domain-id>
With v3password: User's domain id With v3totp: User's
domain id With password: User's domain id (Env:
OS_USER_DOMAIN_ID)
--os-access-token-type <auth-access-token-type>
With v3oidcauthcode: OAuth 2.0 Authorization Server
Introspection token type, it is used to decide which
type of token will be used when processing token
introspection. Valid values are: "access_token" or
"id_token" With v3oidcpassword: OAuth 2.0
Authorization Server Introspection token type, it is
used to decide which type of token will be used when
processing token introspection. Valid values are:
"access_token" or "id_token" With
v3oidcclientcredentials: OAuth 2.0 Authorization
Server Introspection token type, it is used to decide
which type of token will be used when processing token
introspection. Valid values are: "access_token" or
"id_token" (Env: OS_ACCESS_TOKEN_TYPE)
--os-default-domain-name <auth-default-domain-name>
With token: Optional domain name to use with v3 API
and v2 parameters. It will be used for both the user
and project domain in v3 and ignored in v2
authentication. With password: Optional domain name to
use with v3 API and v2 parameters. It will be used for
both the user and project domain in v3 and ignored in
v2 authentication. (Env: OS_DEFAULT_DOMAIN_NAME)
--os-access-token-endpoint <auth-access-token-endpoint>
With v3oidcauthcode: OpenID Connect Provider Token
Endpoint. Note that if a discovery document is being
passed this option will override the endpoint provided
by the server in the discovery document. With
v3oidcpassword: OpenID Connect Provider Token
Endpoint. Note that if a discovery document is being
passed this option will override the endpoint provided
by the server in the discovery document. With
v3oidcclientcredentials: OpenID Connect Provider Token
Endpoint. Note that if a discovery document is being
passed this option will override the endpoint provided
by the server in the discovery document. (Env:
OS_ACCESS_TOKEN_ENDPOINT)
--os-access-token <auth-access-token>
With v3oidcaccesstoken: OAuth 2.0 Access Token (Env:
OS_ACCESS_TOKEN)
--os-domain-id <auth-domain-id>
With v3oidcauthcode: Domain ID to scope to With
v3password: Domain ID to scope to With
v3oidcaccesstoken: Domain ID to scope to With
v3oidcpassword: Domain ID to scope to With token:
Domain ID to scope to With v3oidcclientcredentials:
Domain ID to scope to With v3tokenlessauth: Domain ID
to scope to With v3token: Domain ID to scope to With
v3totp: Domain ID to scope to With password: Domain ID
to scope to (Env: OS_DOMAIN_ID)
--os-user-domain-name <auth-user-domain-name>
With v3password: User's domain name With v3totp:
User's domain name With password: User's domain name
(Env: OS_USER_DOMAIN_NAME)
--os-openid-scope <auth-openid-scope>
With v3oidcauthcode: OpenID Connect scope that is
requested from authorization server. Note that the
OpenID Connect specification states that "openid" must
be always specified. With v3oidcpassword: OpenID
Connect scope that is requested from authorization
server. Note that the OpenID Connect specification
states that "openid" must be always specified. With
v3oidcclientcredentials: OpenID Connect scope that is
requested from authorization server. Note that the
OpenID Connect specification states that "openid" must
be always specified. (Env: OS_OPENID_SCOPE)
--os-user-id <auth-user-id>
With v2password: User ID to login with With
v3password: User ID With v3totp: User ID With
password: User id (Env: OS_USER_ID)
--os-identity-provider <auth-identity-provider>
With v3oidcauthcode: Identity Provider's name With
v3oidcaccesstoken: Identity Provider's name With
v3oidcpassword: Identity Provider's name With
v3oidcclientcredentials: Identity Provider's name
(Env: OS_IDENTITY_PROVIDER)
--os-username <auth-username>
With v2password: Username to login with With
v3password: Username With v3oidcpassword: Username
With v3totp: Username With password: Username (Env:
OS_USERNAME)
--os-auth-url <auth-auth-url>
With v2token: Authentication URL With v3oidcauthcode:
Authentication URL With v2password: Authentication URL
With v3password: Authentication URL With
v3oidcaccesstoken: Authentication URL With
v3oidcpassword: Authentication URL With token:
Authentication URL With v3oidcclientcredentials:
Authentication URL With v3tokenlessauth:
Authentication URL With v3token: Authentication URL
With v3totp: Authentication URL With password:
Authentication URL (Env: OS_AUTH_URL)
--os-client-secret <auth-client-secret>
With v3oidcauthcode: OAuth 2.0 Client Secret With
v3oidcpassword: OAuth 2.0 Client Secret With
v3oidcclientcredentials: OAuth 2.0 Client Secret (Env:
OS_CLIENT_SECRET)
--os-default-domain-id <auth-default-domain-id>
With token: Optional domain ID to use with v3 and v2
parameters. It will be used for both the user and
project domain in v3 and ignored in v2 authentication.
With password: Optional domain ID to use with v3 and
v2 parameters. It will be used for both the user and
project domain in v3 and ignored in v2 authentication.
(Env: OS_DEFAULT_DOMAIN_ID)
--os-discovery-endpoint <auth-discovery-endpoint>
With v3oidcauthcode: OpenID Connect Discovery Document
URL. The discovery document will be used to obtain the
values of the access token endpoint and the
authentication endpoint. This URL should look like
https://idp.example.org/.well-known/openid-
configuration With v3oidcpassword: OpenID Connect
Discovery Document URL. The discovery document will be
used to obtain the values of the access token endpoint
and the authentication endpoint. This URL should look
like https://idp.example.org/.well-known/openid-
configuration With v3oidcclientcredentials: OpenID
Connect Discovery Document URL. The discovery document
will be used to obtain the values of the access token
endpoint and the authentication endpoint. This URL
should look like https://idp.example.org/.well-known
/openid-configuration (Env: OS_DISCOVERY_ENDPOINT)
--os-client-id <auth-client-id>
With v3oidcauthcode: OAuth 2.0 Client ID With
v3oidcpassword: OAuth 2.0 Client ID With
v3oidcclientcredentials: OAuth 2.0 Client ID (Env:
OS_CLIENT_ID)
--os-project-domain-name <auth-project-domain-name>
With v3oidcauthcode: Domain name containing project
With v3password: Domain name containing project With
v3oidcaccesstoken: Domain name containing project With
v3oidcpassword: Domain name containing project With
token: Domain name containing project With
v3oidcclientcredentials: Domain name containing
project With v3tokenlessauth: Domain name containing
project With v3token: Domain name containing project
With v3totp: Domain name containing project With
password: Domain name containing project (Env:
OS_PROJECT_DOMAIN_NAME)
--os-project-domain-id <auth-project-domain-id>
With v3oidcauthcode: Domain ID containing project With
v3password: Domain ID containing project With
v3oidcaccesstoken: Domain ID containing project With
v3oidcpassword: Domain ID containing project With
token: Domain ID containing project With
v3oidcclientcredentials: Domain ID containing project
With v3tokenlessauth: Domain ID containing project
With v3token: Domain ID containing project With
v3totp: Domain ID containing project With password:
Domain ID containing project (Env:
OS_PROJECT_DOMAIN_ID)
--os-password <auth-password>
With v2password: Password to use With v3password:
User's password With v3oidcpassword: Password With
password: User's password (Env: OS_PASSWORD)
--os-redirect-uri <auth-redirect-uri>
With v3oidcauthcode: OpenID Connect Redirect URL (Env:
OS_REDIRECT_URI)
--os-endpoint <auth-endpoint>
With admin_token: The endpoint that will always be
used (Env: OS_ENDPOINT)
--os-token <auth-token>
With v2token: Token With admin_token: The token that
will always be used With token: Token to authenticate
with With v3token: Token to authenticate with (Env:
OS_TOKEN)
--os-passcode <auth-passcode>
With v3totp: User's TOTP passcode (Env: OS_PASSCODE)
--os-project-id <auth-project-id>
With v3oidcauthcode: Project ID to scope to With
v3password: Project ID to scope to With
v3oidcaccesstoken: Project ID to scope to With
v3oidcpassword: Project ID to scope to With token:
Project ID to scope to With v3oidcclientcredentials:
Project ID to scope to With v3tokenlessauth: Project
ID to scope to With v3token: Project ID to scope to
With v3totp: Project ID to scope to With password:
Project ID to scope to (Env: OS_PROJECT_ID)
--monasca-api-url MONASCA_API_URL
Defaults to env[MONASCA_API_URL].
--monasca-api-version MONASCA_API_VERSION
Defaults to env[MONASCA_API_VERSION] or 2_0
Commands:
alarm-count Count alarms.
alarm-definition-create Create an alarm definition.
alarm-definition-delete Delete the alarm definition.
alarm-definition-list List alarm definitions for this tenant.
alarm-definition-patch Patch the alarm definition.
alarm-definition-show Describe the alarm definition.
alarm-definition-update Update the alarm definition.
alarm-delete Delete the alarm.
alarm-history Alarm state transition history.
alarm-history-list List alarms state history.
alarm-list List alarms for this tenant.
alarm-patch Patch the alarm state.
alarm-show Describe the alarm.
alarm-update Update the alarm state.
complete print bash completion command
dimension-name-list List names of metric dimensions.
dimension-value-list List names of metric dimensions.
help print detailed help for another command
measurement-list List measurements for the specified metric.
metric-create Create metric.
metric-create-raw Create metric from raw json body.
metric-list List metrics for this tenant.
metric-name-list List names of metrics.
metric-statistics List measurement statistics for the specified metric.
notification-create Create notification.
notification-delete Delete notification.
notification-list List notifications for this tenant.
notification-patch Patch notification.
notification-show Describe the notification.
notification-type-list List notification types supported by monasca.
notification-update Update notification.
Bash Completion
---------------
Basic command tab completion can be enabled by sourcing the bash completion
script.
::
monasca completion >> /usr/local/share/monasca.bash_completion

View File

@@ -1,12 +0,0 @@
=========
Debugging
=========
``-v`` (or ``--verbose``), as well as ``--debug``, option can be used
to increase amount of low-level details regarding all the steps that
client takes in order to execute the CLI command.
While ``--verbose`` does not dramatically increase the output by displaying
only basic information about the execution, ``--debug`` can be used
to additionally display low-level interactions **monascaclient** make with
**keystone** server and/or **monasca** server.

View File

@@ -1,36 +0,0 @@
===================
Changing formatting
===================
Changing displayed columns
--------------------------
If you want displayed columns in a list operation, ``-c`` option can be used.
``-c`` can be specified multiple times and the column order will be same as
the order of ``-c`` options.
Changing format
---------------
If you want to change the format data is displayed in, you can use ``-f``
option for that. Format can be specified just once and it affects they way
the data is printed to the ``STDOUT``. The available formats, data can be
presented in, can be checked with:
.. code-block:: text
monasca <command> --help
Look for section **output formatters** and the flag ``--format`` or ``-f``.
In most of the cases you will be able to pick one out of
``csv``, ``json``, ``table``, ``value``, ``yaml``.
Affecting the width
-------------------
If, for some reason, you are not happy with the width the output has taken, you
can use ```--max-width {number}``` flag and set the value to
match your preference. Without that output will not be constrained
by the terminal width. Alternatively you may want to pass ``--fit-width``
to fit the output to display width. Remember that these flags
affect the output only if ``table`` formatter is used.

View File

@@ -1,224 +0,0 @@
=================
Using monasca CLI
=================
The **monasca** shell utility interacts with OpenStack Monitoring API from the
command-line. It supports the entire features of OpenStack Monitoring API.
Basic Usage
-----------
In order to use the CLI, you must provide your OpenStack username, password,
project, domain information for both user and project, and auth endpoint. Use
the corresponding configuration options (``--os-username``, ``--os-password``,
``--os-project-name``, ``--os-user-domain-id``, ``os-project-domain-id``, and
``--os-auth-url``), but it is easier to set them in environment variables.
.. code-block:: shell
export OS_USERNAME=mini-mon
export OS_PASSWORD=password
export OS_PROJECT_NAME=mini-mon
export OS_USER_DOMAIN_ID=default
export OS_PROJECT_DOMAIN_ID=default
export OS_AUTH_URL=http://keystone:5000/v3
If you are using Identity v2.0 API (DEPRECATED), you don't need to pass domain
information.
.. code-block:: shell
export OS_USERNAME=mini-mon
export OS_PASSWORD=password
export OS_TENANT_NAME=mini-mon
export OS_AUTH_URL=http://keystone:5000/v2.0
Once you've configured your authentication parameters, you can run **monasca**
commands. All commands take the form of:
.. code-block:: text
monasca <command> [arguments...]
Run **monasca help** to get a full list of all possible commands, and run
**monasca help <command>** to get detailed help for that command.
Using with os-client-config
~~~~~~~~~~~~~~~~~~~~~~~~~~~
`os-client-config <https://docs.openstack.org/os-client-config/latest/>`_
provides more convenient way to manage a collection of client configurations
and you can easily switch multiple OpenStack-based configurations.
To use os-client-config, you first need to prepare
``~/.config/openstack/clouds.yaml`` like the following.
.. code-block:: yaml
clouds:
monitoring:
auth:
auth_url: http://keystone:5000
password: password
project_domain_id: default
project_name: mini-mon
user_domain_id: default
username: mini-mon
identity_api_version: '3'
region_name: RegionOne
Then, you need to specify a configuration name defined in the above
clouds.yaml.
.. code-block:: shell
export OS_CLOUD=monitoring
For more detail information, see the
`os-client-config <https://docs.openstack.org/os-client-config/latest/>`_
documentation.
Using with keystone token
~~~~~~~~~~~~~~~~~~~~~~~~~
The command-line tool will attempt to re-authenticate using your provided
credentials for every request. You can override this behavior by manually
supplying an auth token using ``--os-url`` and ``--os-auth-token``. You can
alternatively set these environment variables.
.. code-block:: shell
export OS_URL=http://monasca.example.org:8070/
export OS_TOKEN=3bcc3d3a03f44e3d8377f9247b0ad155
Usage Examples
----------------
metric-create::
monasca metric-create cpu1 123.40
monasca metric-create metric1 1234.56 --dimensions instance_id=123,service=ourservice
monasca metric-create metric1 2222.22 --dimensions instance_id=123,service=ourservice
monasca metric-create metric1 3333.33 --dimensions instance_id=222,service=ourservice
monasca metric-create metric1 4444.44 --dimensions instance_id=222 --value-meta rc=404
metric-list::
monasca metric-list
+---------+--------------------+
| name | dimensions |
+---------+--------------------+
| cpu1 | |
| metric1 | instance_id:123 |
| | service:ourservice |
+---------+--------------------+
measurement-list::
monasca measurement-list metric1 2014-01-01T00:00:00Z
+---------+--------------------+----------------+----------------------+--------------+-------------+
| name | dimensions | measurement_id | timestamp | value | value_meta |
+---------+--------------------+----------------+----------------------+--------------+-------------+
| metric1 | instance_id:123 | 723885 | 2014-05-08T21:46:32Z | 1234.56 | |
| | service:ourservice | 725951 | 2014-05-08T21:48:50Z | 2222.22 | |
| metric1 | instance_id:222 | 726837 | 2014-05-08T21:49:47Z | 3333.33 | |
| | service:ourservice | 726983 | 2014-05-08T21:50:27Z | 4444.44 | rc: 404 |
+---------+--------------------+----------------+----------------------+--------------+-------------+
monasca measurement-list metric1 2014-01-01T00:00:00Z --dimensions instance_id=123
+---------+--------------------+----------------+----------------------+--------------+-------------+
| name | dimensions | measurement_id | timestamp | value | value_meta |
+---------+--------------------+----------------+----------------------+--------------+-------------+
| metric1 | instance_id:123 | 723885 | 2014-05-08T21:46:32Z | 1234.56 | |
| | service:ourservice | 725951 | 2014-05-08T21:48:50Z | 2222.22 | |
+---------+--------------------+----------------+----------------------+--------------+-------------+
Notifications Examples
~~~~~~~~~~~~~~~~~~~~~~
Note: To see complete usage: 'monasca help' and 'monasca help <command>'
notification-create::
monasca notification-create cindyemail1 EMAIL cindy.employee@hp.com
monasca notification-create myapplication WEBHOOK http://localhost:5000
monasca notification-create mypagerduty PAGERDUTY nzH2LVRdMzun11HNC2oD
notification-list::
monasca notification-list
+---------------+--------------------------------------+-------+----------------------+
| name | id | type | address |
+---------------+--------------------------------------+-------+----------------------+
| cindyemail1 | 5651406c-447d-40bd-b868-b2b3e6b59e32 | EMAIL |cindy.employee@hp.com |
| myapplication | 55905ce2-91e3-41ce-b45a-de7032f8d718 | WEBHOOK |http://localhost:5000
| mypagerduty | 5720ccb5-6a3d-22ba-545g-ce467a5b41a2 | PAGERDUTY |nzH2LVRdMzun11HNC2oD
+---------------+--------------------------------------+-------+----------------------+
Alarms Examples
~~~~~~~~~~~~~~~
Note: To see complete usage: 'monasca help' and 'monasca help <command>'
alarm-definition-create::
monasca alarm-definition-create alarmPerHost "max(cpu.load_avg_1_min) > 0" --match-by hostname
alarm-definition-list::
+--------------+--------------------------------------+-----------------------------+----------+-----------------+
| name | id | expression | match_by | actions_enabled |
+--------------+--------------------------------------+-----------------------------+----------+-----------------+
| alarmPerHost | 4bf6bfc2-c5ac-4d57-b7db-cf5313b05412 | max(cpu.load_avg_1_min) > 0 | hostname | True |
+--------------+--------------------------------------+-----------------------------+----------+-----------------+
alarm-definition-show::
monasca alarm-definition-show 4bf6bfc2-c5ac-4d57-b7db-cf5313b05412
+----------------------+----------------------------------------------------------------------------------------------------+
| Property | Value |
+----------------------+----------------------------------------------------------------------------------------------------+
| actions_enabled | true |
| alarm_actions | [] |
| description | "" |
| expression | "max(cpu.load_avg_1_min) > 0" |
| id | "4bf6bfc2-c5ac-4d57-b7db-cf5313b05412" |
| links | href:http://192.168.10.4:8070/v2.0/alarm-definitions/4bf6bfc2-c5ac-4d57-b7db-cf5313b05412,rel:self |
| match_by | [ |
| | "hostname" |
| | ] |
| name | "alarmPerHost" |
| ok_actions | [] |
| severity | "LOW" |
| undetermined_actions | [] |
+----------------------+----------------------------------------------------------------------------------------------------+
alarm-definition-delete::
monasca alarm-definition-delete 4bf6bfc2-c5ac-4d57-b7db-cf5313b05412
alarm-list::
monasca alarm-list
+--------------------------------------+--------------------------------------+----------------+---------------+---------------------+----------+-------+--------------------------+--------------------------+
| id | alarm_definition_id | alarm_name | metric_name | metric_dimensions | severity | state | state_updated_timestamp | created_timestamp |
+--------------------------------------+--------------------------------------+----------------+---------------+---------------------+----------+-------+--------------------------+--------------------------+
| 11e8c15d-0263-4b71-a8b8-4ecdaeb2902c | af1f347b-cddb-46da-b7cc-924261eeecdf | High CPU usage | cpu.idle_perc | hostname: devstack | LOW | OK | 2015-03-26T21:45:15.000Z | 2015-03-26T21:41:50.000Z |
| e5797cfe-b66e-4d44-98cd-3c7fc62d4c33 | af1f347b-cddb-46da-b7cc-924261eeecdf | High CPU usage | cpu.idle_perc | hostname: mini-mon | LOW | OK | 2015-03-26T21:43:15.000Z | 2015-03-26T21:41:47.000Z |
| | | | | service: monitoring | | | | |
+--------------------------------------+--------------------------------------+----------------+---------------+---------------------+----------+-------+--------------------------+--------------------------+
alarm-history::
monasca alarm-history 9d748b72-939b-45e7-a807-c0c5ad88d3e4
+--------------------------------------+-----------+--------------+------------------------------------------------------------------------------+-------------+--------------------+---------------------+--------------------------+
| alarm_id | new_state | old_state | reason | reason_data | metric_name | metric_dimensions | timestamp |
+--------------------------------------+-----------+--------------+------------------------------------------------------------------------------+-------------+--------------------+---------------------+--------------------------+
| 9d748b72-939b-45e7-a807-c0c5ad88d3e4 | ALARM | UNDETERMINED | Thresholds were exceeded for the sub-alarms: [max(cpu.load_avg_1_min) > 0.0] | {} | cpu.load_avg_1_min | hostname: mini-mon | 2014-10-14T21:14:11.000Z |
| | | | | | | service: monitoring | |
+--------------------------------------+-----------+--------------+------------------------------------------------------------------------------+-------------+--------------------+---------------------+--------------------------+
alarm-patch::
monasca alarm-patch fda5537b-1550-435f-9d6c-262b7e05065b --state OK

View File

@@ -1,124 +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 os
import sys
sys.path = [
os.path.abspath('../..'),
os.path.abspath('../../bin')
] + sys.path
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '2.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.coverage',
'sphinx.ext.ifconfig',
'sphinx.ext.graphviz',
'sphinx.ext.viewcode',
'openstackdocstheme'
]
# geeneral information about project
openstackdocs_repo_name = u'openstack/python-monascaclient'
project = u'Monasca Client Dev Docs'
openstackdocs_use_storyboard = True
copyright = u'2014-present, OpenStack Foundation'
author = u'OpenStack Foundation'
openstackdocs_auto_name = False
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
source_suffix = '.rst'
# The encoding of source files.
source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = [
'common',
'doc',
'documentation',
'etc',
'java'
]
# 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
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = 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. See the documentation for
# a list of builtin themes.
html_theme = 'openstackdocs'
# If false, no index is generated.
html_use_index = True
# If false, no module index is generated.
html_use_modindex = True
# Output file base name for HTML help builder.
htmlhelp_basename = 'python-monascaclientdoc'
# -- Options for LaTeX output ---------------------------------------------
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'python-monascaclient.tex', u'python-monascaclient Documentation',
u'Openstack Foundation \\textless{}monasca@lists.launchpad.net\\textgreater{}', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'python-monascaclient', u'python-monascaclient Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'python-monascaclient', u'python-monascaclient Documentation',
author, 'python-monascaclient', 'Rest-API to collect logs from your cloud.',
'Miscellaneous'),
]

View File

@@ -1,47 +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.
==================================
python-monascaclient documentation
==================================
This is a client for OpenStack Monitoring API. It provides
:doc:`Python API bindings <reference/index>` (the monascaclient module) and
:doc:`command-line interface (CLI) <cli/index>`.
User Documentation
------------------
.. toctree::
:maxdepth: 2
installation
cli/index
reference/index
Usage
-----
In the :doc:`Usage <usage/index>`, you will find
information on possible ways to use python-monascaclient.
.. toctree::
:maxdepth: 2
usage/index
History
-------
Release notes is available at
http://docs.openstack.org/releasenotes/python-monascaclient/.

View File

@@ -1,20 +0,0 @@
============
Installation
============
At the command line, from PyPI::
$ pip install python-monascaclient
Or, if you have virtualenvwrapper installed::
$ mkvirtualenv python-monascaclient
$ pip install python-monascaclient
Or, you can build it manually::
$ mkvirtualenv python-monascaclient
$ git clone https://opendev.org/openstack/python-monascaclient
$ cd python-monascaclient
$ pip install -r ./requirements.txt
$ python setup.py install

View File

@@ -1,107 +0,0 @@
================
Using Python API
================
Python bindings to the OpenStack Monasca API
============================================
This is a client for the OpenStack Monasca API. It includes a Python
API (the :mod:`monascaclient` module) and a command-line script
(installed as :program:`monasca`).
Python API
==========
To use python-monascaclient in a project, you need to create a client instance
first. There are couple ways of doing this properly.
With session
------------
A pseudo-code would be similar to this::
from keystoneauth1 import identity
from keystoneauth1 import session
from monascaclient import client
auth = identity.Password(
auth_url='http://my.keystone.com/identity',
username='mini-mon',
password='password',
project_name='mini-mon',
user_domain_id='default',
project_domain_id='default'
)
sess = session.Session(auth=auth)
endpoint = 'http://monasca:8070/v2.0'
api_version = '2_0'
c = client.Client(
api_version=api_version,
endpoint=endpoint,
session=sess
)
c.alarms.list()
For more information on keystoneauth API, see `Using Sessions`_. We also
suggest taking closer look at `Keystone Auth Plugins`_. Each of the plugin
can be used to properly instantiate new session and pass it into the client.
.. note:: This is recommended way to setup a client.
Other cases, described below, create sessions internally.
Without session
---------------
If you do not want to use a session or simply prefer client to instantiate
one on its own, there are two supported ways
With token
~~~~~~~~~~
A pseudo-code would be similar to this::
from monascaclient import client
c = client.Client(
api_version='2_0',
endpoint='http://monasca:8070/v2.0',
token='3bcc3d3a03f44e3d8377f9247b0ad155',
project_name='mini-mon',
auth_url='http://my.keystone.com/identity'
)
c.alarms.list()
With username & password
~~~~~~~~~~~~~~~~~~~~~~~~
A pseudo-code would be similar to this::
from monascaclient import client
c = client.Client(
api_version='2_0',
endpoint='http://monasca:8070/v2.0',
username='mini-mon',
password='password',
project_name='mini-mon',
auth_url='http://my.keystone.com/identity'
)
c.alarms.list()
Examples
========
* `Monasca Agent Example`_ - with session
* `Monasca UI Example`_ - with token
.. _Monasca Agent Example: https://github.com/openstack/monasca-agent/blob/master/monasca_agent/forwarder/api/monasca_api.py
.. _Monasca UI Example: https://github.com/openstack/monasca-ui/blob/master/monitoring/api/client.py
.. _Using Sessions: https://docs.openstack.org/keystoneauth/latest/using-sessions.html
.. _Keystone Auth Plugins: https://docs.openstack.org/keystoneauth/latest/authentication-plugins.html

View File

@@ -1,21 +0,0 @@
=====
Usage
=====
Devstack
--------
python-monascaclient is bundled inside `Monasca API Devstack Plugin`_ and is
available right after the devstack finished stacking up. It is always built
from the **master** branch, unless specified otherwise.
Docker
------
The client is also part of `monasca-docker`_, a community effort to put
**monasca** into containers. The image is available as **monasca/client** and
can be used as drop-in replacement for traditional way of
deploying the clients.
.. _Monasca API Devstack Plugin: https://github.com/openstack/monasca-api/tree/master/devstack
.. _monasca-docker: https://github.com/monasca/monasca-docker/tree/master/monasca-client

View File

@@ -1,24 +0,0 @@
ARG DOCKER_IMAGE=monasca/client
ARG APP_REPO=https://review.opendev.org/openstack/python-monascaclient
# Branch, tag or git hash to build from.
ARG REPO_VERSION=master
ARG CONSTRAINTS_BRANCH=master
# Always start from `monasca-base` image and use specific tag of it.
ARG BASE_TAG=master
FROM monasca/base:$BASE_TAG
# Environment variables used for our service or wait scripts.
ENV \
MONASCA_URI=monasca:8070 \
OS_AUTH_URL=http://keystone:35357/v3 \
OS_USERNAME=mini-mon \
OS_PASSWORD=password \
OS_TENANT_NAME=mini-mon \
OS_DOMAIN_NAME=Default
RUN monasca --version
# Implement start script in `start.sh` file.
CMD ["/start.sh"]

View File

@@ -1,65 +0,0 @@
===============================
Docker image for Monasca Client
===============================
The Monasca Client image is based on the monasca-base image.
Building monasca-base image
===========================
See https://github.com/openstack/monasca-common/tree/master/docker/README.rst
Building Monasca Client image
=============================
Example:
$ ./build_image.sh <repository_version> <upper_constains_branch> <common_version>
Requirements from monasca-base image
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
health_check.py
This file will be used for checking the status of the Monasca API
application.
Scripts
~~~~~~~
start.sh
In this starting script provide all steps that lead to the proper service
start. Including usage of wait scripts and templating of configuration
files. You also could provide the ability to allow running container after
service died for easier debugging.
build_image.sh
Please read detailed build description inside the script.
Docker Compose
~~~~~~~~~~~~~~
When you want to use docker-compose add it as a new service and be sure that
property 'tty' is set to true to avoid exiting of container after startup.
Example:
* monasca-client:
* image: monasca/client:master
* tty: true
Running
~~~~~~~
If you don't want to use docker-compose mechanism, you can run container manually
and connect it to existing docker Monasca network.
Example:
docker network --network=<network-name> <container_name>
You can also use docker run option to start a container and connect it to a network immediately:
Example:
docker run -itd --network=<network-name> <container-name>
Inside of container it is possible to run 'monasca' shell commands, e.g. to list all metrics.
Example:
monasca metric-list
Links
~~~~~
https://docs.openstack.org/python-monascaclient/latest/

View File

@@ -1,150 +0,0 @@
#!/bin/bash
# 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.
# TODO(Dobroslaw): move this script to monasca-common/docker folder
# and leave here small script to download it and execute using env variables
# to minimize code duplication.
set -x # Print each script step.
set -eo pipefail # Exit the script if any statement returns error.
# This script is used for building Docker image with proper labels
# and proper version of monasca-common.
#
# Example usage:
# $ ./build_image.sh <repository_version> <upper_constains_branch> <common_version>
#
# Everything after `./build_image.sh` is optional and by default configured
# to get versions from `Dockerfile`.
#
# To build from master branch (default):
# $ ./build_image.sh
# To build specific version run this script in the following way:
# $ ./build_image.sh stable/queens
# Building from specific commit:
# $ ./build_image.sh cb7f226
# When building from a tag monasca-common will be used in version available
# in upper constraint file:
# $ ./build_image.sh 2.5.0
# To build image from Gerrit patch sets that is targeting branch stable/queens:
# $ ./build_image.sh refs/changes/51/558751/1 stable/queens
#
# If you want to build image with custom monasca-common version you need
# to provide it as in the following example:
# $ ./build_image.sh master master refs/changes/19/595719/3
# Go to folder with Docker files.
REAL_PATH=$(python3 -c "import os,sys; print(os.path.realpath('$0'))")
cd "$(dirname "$REAL_PATH")/../docker/"
[ -z "$DOCKER_IMAGE" ] && \
DOCKER_IMAGE=$(\grep DOCKER_IMAGE Dockerfile | cut -f2 -d"=")
: "${REPO_VERSION:=$1}"
[ -z "$REPO_VERSION" ] && \
REPO_VERSION=$(\grep REPO_VERSION Dockerfile | cut -f2 -d"=")
# Let's stick to more readable version and disable SC2001 here.
# shellcheck disable=SC2001
REPO_VERSION_CLEAN=$(echo "$REPO_VERSION" | sed 's|/|-|g')
[ -z "$APP_REPO" ] && APP_REPO=$(\grep APP_REPO Dockerfile | cut -f2 -d"=")
GITHUB_REPO=$(echo "$APP_REPO" | sed 's/review.opendev.org/github.com/' | \
sed 's/ssh:/https:/')
if [ -z "$CONSTRAINTS_FILE" ]; then
CONSTRAINTS_FILE=$(\grep CONSTRAINTS_FILE Dockerfile | cut -f2 -d"=") || true
: "${CONSTRAINTS_FILE:=https://opendev.org/openstack/requirements/raw/branch/master/upper-constraints.txt}"
fi
: "${CONSTRAINTS_BRANCH:=$2}"
[ -z "$CONSTRAINTS_BRANCH" ] && \
CONSTRAINTS_BRANCH=$(\grep CONSTRAINTS_BRANCH Dockerfile | cut -f2 -d"=")
# When using stable version of repository use same stable constraints file.
case "$REPO_VERSION" in
*stable*)
CONSTRAINTS_BRANCH_CLEAN="$REPO_VERSION"
CONSTRAINTS_FILE=${CONSTRAINTS_FILE/master/$CONSTRAINTS_BRANCH_CLEAN}
# Get monasca-common version from stable upper constraints file.
CONSTRAINTS_TMP_FILE=$(mktemp)
wget --output-document "$CONSTRAINTS_TMP_FILE" \
$CONSTRAINTS_FILE
UPPER_COMMON=$(\grep 'monasca-common' "$CONSTRAINTS_TMP_FILE")
# Get only version part from monasca-common.
UPPER_COMMON_VERSION="${UPPER_COMMON##*===}"
rm -rf "$CONSTRAINTS_TMP_FILE"
;;
*)
CONSTRAINTS_BRANCH_CLEAN="$CONSTRAINTS_BRANCH"
;;
esac
# Monasca-common variables.
if [ -z "$COMMON_REPO" ]; then
COMMON_REPO=$(\grep COMMON_REPO Dockerfile | cut -f2 -d"=") || true
: "${COMMON_REPO:=https://review.opendev.org/openstack/monasca-common}"
fi
: "${COMMON_VERSION:=$3}"
if [ -z "$COMMON_VERSION" ]; then
COMMON_VERSION=$(\grep COMMON_VERSION Dockerfile | cut -f2 -d"=") || true
if [ "$UPPER_COMMON_VERSION" ]; then
# Common from upper constraints file.
COMMON_VERSION="$UPPER_COMMON_VERSION"
fi
fi
# Clone project to temporary directory for getting proper commit number from
# branches and tags. We need this for setting proper image labels.
# Docker does not allow to get any data from inside of system when building
# image.
TMP_DIR=$(mktemp -d)
(
cd "$TMP_DIR"
# This many steps are needed to support gerrit patch sets.
git init
git remote add origin "$APP_REPO"
git fetch origin "$REPO_VERSION"
git reset --hard FETCH_HEAD
)
GIT_COMMIT=$(git -C "$TMP_DIR" rev-parse HEAD)
[ -z "${GIT_COMMIT}" ] && echo "No git commit hash found" && exit 1
rm -rf "$TMP_DIR"
# Do the same for monasca-common.
COMMON_TMP_DIR=$(mktemp -d)
(
cd "$COMMON_TMP_DIR"
# This many steps are needed to support gerrit patch sets.
git init
git remote add origin "$COMMON_REPO"
git fetch origin "$COMMON_VERSION"
git reset --hard FETCH_HEAD
)
COMMON_GIT_COMMIT=$(git -C "$COMMON_TMP_DIR" rev-parse HEAD)
[ -z "${COMMON_GIT_COMMIT}" ] && echo "No git commit hash found" && exit 1
rm -rf "$COMMON_TMP_DIR"
CREATION_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
docker build --no-cache \
--build-arg CREATION_TIME="$CREATION_TIME" \
--build-arg GITHUB_REPO="$GITHUB_REPO" \
--build-arg APP_REPO="$APP_REPO" \
--build-arg REPO_VERSION="$REPO_VERSION" \
--build-arg GIT_COMMIT="$GIT_COMMIT" \
--build-arg CONSTRAINTS_FILE="$CONSTRAINTS_FILE" \
--build-arg COMMON_REPO="$COMMON_REPO" \
--build-arg COMMON_VERSION="$COMMON_VERSION" \
--build-arg COMMON_GIT_COMMIT="$COMMON_GIT_COMMIT" \
--tag "$DOCKER_IMAGE":"$REPO_VERSION_CLEAN" .

View File

@@ -1,26 +0,0 @@
#!/usr/bin/env python
# coding=utf-8
# (C) Copyright 2018 FUJITSU LIMITED
#
# 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.
"""Health check will returns 0 when service is working properly."""
def main():
"""No health check for python client"""
return 0
if __name__ == '__main__':
main()

View File

@@ -1,8 +0,0 @@
#!/bin/sh
# Test services we need before starting our service.
echo "Start script: waiting for needed services"
python3 /kafka_wait_for_topics.py
python3 /mysql_check.py
./wait_for.sh "$MONASCA_URI"

View File

@@ -1,70 +0,0 @@
# Copyright 2017 FUJITSU LIMITED
#
# 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.
"""
Patches method that transforms error responses.
That is required to handle different format monasca follows.
"""
from keystoneauth1 import exceptions as exc
from keystoneauth1.exceptions import http
def mon_exc_from_response(response, method, url):
req_id = response.headers.get('x-openstack-request-id')
kwargs = {
'http_status': response.status_code,
'response': response,
'method': method,
'url': url,
'request_id': req_id,
}
if 'retry-after' in response.headers:
kwargs['retry_after'] = response.headers['retry-after']
content_type = response.headers.get('Content-Type', '')
if content_type.startswith('application/json'):
try:
body = response.json()
except ValueError:
pass
else:
if isinstance(body, dict):
if isinstance(body.get('error'), dict):
error = body['error']
kwargs['message'] = error.get('message')
kwargs['details'] = error.get('details')
elif {'description', 'title'} <= set(body):
# monasca-api error response structure
kwargs['message'] = body.get('title')
kwargs['details'] = body.get('description')
elif content_type.startswith('text/'):
kwargs['details'] = response.text
try:
cls = http._code_map[response.status_code]
except KeyError:
if 500 <= response.status_code < 600:
cls = exc.HttpServerError
elif 400 <= response.status_code < 500:
cls = exc.HTTPClientError
else:
cls = exc.HttpError
return cls(**kwargs)
exc.from_response = mon_exc_from_response

View File

@@ -1,163 +0,0 @@
# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
# Copyright 2017 Fujitsu LIMITED
#
# 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 warnings
from keystoneauth1 import identity
from keystoneauth1 import session as k_session
from monascaclient.osc import migration
from monascaclient import version
LOG = logging.getLogger(__name__)
_NO_VALUE_MARKER = object()
def Client(api_version, *args, **kwargs):
handle_deprecated(args, kwargs)
client = migration.make_client(
api_version=api_version,
session=_session(kwargs),
endpoint=kwargs.get('endpoint'),
service_type=kwargs.get('service_type', 'monitoring')
)
return client
def _session(kwargs):
"""Returns or reuses session.
Method takes care of providing instance of
session object for the client.
:param kwargs: all params (without api_version) client was initialized with
:type kwargs: dict
:returns: session object
:rtype keystoneauth1.session.Session
"""
if 'session' in kwargs:
LOG.debug('Reusing session')
sess = kwargs.get('session')
if not isinstance(sess, k_session.Session):
msg = ('session should be an instance of %s' % k_session.Session)
LOG.error(msg)
raise RuntimeError(msg)
else:
LOG.debug('Initializing new session')
auth = _get_auth_handler(kwargs)
sess = _get_session(auth, kwargs)
return sess
def handle_deprecated(args, kwargs):
"""Handles all deprecations.
Method goes through passed args and kwargs
and handles all values that are invalid from POV
of current client but:
* has their counterparts
* are candidates to be dropped
"""
kwargs.update(_handle_deprecated_args(args))
_handle_deprecated_kwargs(kwargs)
def _handle_deprecated_kwargs(kwargs):
depr_map = {
'tenant_name': ('project_name', lambda x: x),
'insecure': ('verify', lambda x: not x)
}
for key, new_key_transform in depr_map.items():
val = kwargs.get(key, _NO_VALUE_MARKER)
if val != _NO_VALUE_MARKER:
new_key = new_key_transform[0]
new_handler = new_key_transform[1]
warnings.warn(
'Usage of {old_key} has been deprecated in favour '
'of {new_key}. monascaclient will place value of {old_key} '
'under {new_key}'.format(old_key=key, new_key=new_key),
DeprecationWarning
)
kwargs[new_key] = new_handler(val)
del kwargs[key]
def _handle_deprecated_args(args):
kwargs_update = {}
if args is not None and len(args) > 0:
warnings.warn(
'Usage or args is deprecated for the sake of '
'explicit configuration of the client using '
'named arguments (**kwargs). '
'That argument will be removed in future releases.',
DeprecationWarning
)
# have all permissible args set here
kwargs_update.update({
'endpoint': args[0]
})
return kwargs_update
def _get_session(auth, kwargs):
return k_session.Session(auth=auth,
app_name='monascaclient',
app_version=version.version_string,
cert=kwargs.get('cert', None),
timeout=kwargs.get('timeout', None),
verify=kwargs.get('verify', True))
def _get_auth_handler(kwargs):
if 'token' in kwargs:
auth = identity.Token(
auth_url=kwargs.get('auth_url', None),
token=kwargs.get('token', None),
project_id=kwargs.get('project_id', None),
project_name=kwargs.get('project_name', None),
project_domain_id=kwargs.get('project_domain_id', None),
project_domain_name=kwargs.get('project_domain_name', None)
)
elif {'username', 'password'} <= set(kwargs):
auth = identity.Password(
auth_url=kwargs.get('auth_url', None),
username=kwargs.get('username', None),
password=kwargs.get('password', None),
project_id=kwargs.get('project_id', None),
project_name=kwargs.get('project_name', None),
project_domain_id=kwargs.get('project_domain_id', None),
project_domain_name=kwargs.get('project_domain_name', None),
user_domain_id=kwargs.get('user_domain_id', None),
user_domain_name=kwargs.get('user_domain_name', None)
)
else:
raise Exception('monascaclient can be configured with either '
'"token" or "username:password" but neither of '
'them was found in passed arguments.')
return auth

View File

@@ -1,65 +0,0 @@
# (C) Copyright 2014, 2015 Hewlett Packard Enterprise Development Company LP
# Copyright 2017 Fujitsu LIMITED
#
# 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 urllib import parse
class MonascaManager(object):
base_url = None
def __init__(self, client):
self.client = client
def _parse_body(self, body):
if type(body) is dict:
self.next = None
for link in body['links']:
if link['rel'] == 'next':
self.next = link['href']
return body['elements']
else:
return body
def _list(self, path, dim_key=None, **kwargs):
"""Get a list of metrics."""
url_str = self.base_url + path
if dim_key and dim_key in kwargs:
dim_str = self.get_dimensions_url_string(kwargs[dim_key])
kwargs[dim_key] = dim_str
if kwargs:
url_str += '?%s' % parse.urlencode(kwargs, True)
body = self.client.list(
path=url_str
)
return self._parse_body(body)
@staticmethod
def get_dimensions_url_string(dimensions):
dim_list = list()
for k, v in dimensions.items():
# In case user specifies a dimension multiple times
if isinstance(v, (list, tuple)):
v = v[-1]
if v:
dim_str = k + ':' + v
else:
dim_str = k
dim_list.append(dim_str)
return ','.join(dim_list)

View File

@@ -1,200 +0,0 @@
# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP
#
# 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 numbers
import prettytable
import yaml
from osc_lib import exceptions as exc
from oslo_serialization import jsonutils
supported_formats = {
"json": lambda x: jsonutils.dumps(x, indent=2),
"yaml": yaml.safe_dump
}
# Decorator for cli-args
def arg(*args, **kwargs):
def _decorator(func):
# Because of the semantics of decorator composition if we just append
# to the options list positional options will appear to be backwards.
func.__dict__.setdefault('arguments', []).insert(0, (args, kwargs))
return func
return _decorator
def json_formatter(js):
formatter = (jsonutils.dumps(js, indent=2, ensure_ascii=False))
return formatter
def print_list(objs, fields, field_labels=None, formatters=None, sortby=None):
if formatters is None:
formatters = {}
field_labels = field_labels or fields
pt = prettytable.PrettyTable([f for f in field_labels],
caching=False, print_empty=False)
pt.align = 'l'
for o in objs:
row = []
for field in fields:
if field in formatters:
row.append(formatters[field](o))
elif isinstance(field, int):
row.append(o[field])
else:
data = getattr(o, field, None) or ''
row.append(data)
pt.add_row(row)
field_to_sort_by = field_labels[sortby] if sortby else None
pt_string = pt.get_string(sortby=field_to_sort_by)
print(pt_string)
def print_dict(d, formatters=None):
if formatters is None:
formatters = {}
pt = prettytable.PrettyTable(['Property', 'Value'],
caching=False, print_empty=False)
pt.align = 'l'
for field in d:
if field in formatters:
pt.add_row([field, formatters[field](d[field])])
else:
pt.add_row([field, d[field]])
pt_string = pt.get_string(sortby='Property')
print(pt_string)
def format_parameters(params):
'''Reformat parameters into dict of format expected by the API.'''
if not params:
return {}
# expect multiple invocations of --parameters but fall back
# to ; delimited if only one --parameters is specified
if len(params) == 1:
if params[0].find(';') != -1: # found
params = params[0].split(';')
else:
params = params[0].split(',')
parameters = {}
for p in params:
try:
(n, v) = p.split('=', 1)
except ValueError:
msg = '%s(%s). %s.' % ('Malformed parameter', p,
'Use the key=value format')
raise exc.CommandError(msg)
if n not in parameters:
parameters[n] = v
else:
if not isinstance(parameters[n], list):
parameters[n] = [parameters[n]]
parameters[n].append(v)
return parameters
def format_dimensions_query(dims):
if not dims:
return {}
# expect multiple invocations of --parameters but fall back
# to ; delimited if only one --parameters is specified
if len(dims) == 1:
if dims[0].find(';') != -1: # found
dims = dims[0].split(';')
else:
dims = dims[0].split(',')
dimensions = {}
for p in dims:
try:
(n, v) = p.split('=', 1)
except ValueError:
n = p
v = ""
dimensions[n] = v
return dimensions
def format_dimensions(dict):
return 'dimensions: {\n' + format_dict(dict) + '\n}'
def format_expression_data(data):
# takes an dictionary containing a dict
string_list = list()
for k, v in data.items():
if k == 'dimensions':
dim_str = format_dimensions(v)
string_list.append(dim_str)
else:
if isinstance(v, numbers.Number):
d_str = k + ': ' + str(v)
else:
d_str = k + ': ' + v
string_list.append(d_str)
return '\n'.join(string_list)
def format_dictlist(dict_list):
# takes list of dictionaries to format for output
string_list = list()
for mdict in dict_list:
kv_list = list()
for k, v in sorted(mdict.items()):
kv_str = k + ':' + str(v)
kv_list.append(kv_str)
# a string of comma separated k:v
this_dict_str = ','.join(kv_list)
string_list.append(this_dict_str)
return '\n'.join(string_list)
def format_dict(dict):
# takes a dictionary to format for output
dstring_list = list()
for k, v in dict.items():
if isinstance(v, numbers.Number):
d_str = k + ': ' + str(v)
else:
d_str = k + ': ' + v
dstring_list.append(d_str)
return '\n'.join(dstring_list)
def format_list(in_list):
string_list = list()
for k in in_list:
if isinstance(k, str):
key = k.encode('utf-8')
else:
key = k
string_list.append(key)
return b'\n'.join(string_list)

View File

@@ -1,167 +0,0 @@
# Copyright 2017 FUJITSU LIMITED
#
# 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.command import command
from osc_lib import utils
from monascaclient import version
LOG = logging.getLogger(__name__)
# NOTE(trebskit) this will be moved to another module
# once initial migration is up
# the point is to show how many code can we spare
# in order to get the client working with minimum effort needed
VERSION_MAP = {
'2_0': 'monascaclient.v2_0.client.Client'
}
def make_client(api_version, session=None,
endpoint=None, service_type='monitoring'):
"""Returns an monitoring API client."""
client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP)
c = client_cls(
session=session,
service_type=service_type,
endpoint=endpoint,
app_name='monascaclient',
app_version=version.version_string,
)
return c
def create_command_class(name, func_module):
"""Dynamically creates subclass of MigratingCommand.
Method takes name of the function, module it is part of
and builds the subclass of :py:class:`MigratingCommand`.
Having a subclass of :py:class:`cliff.command.Command` is mandatory
for the osc-lib integration.
:param name: name of the function
:type name: basestring
:param func_module: the module function is part of
:type func_module: module
:return: command name, subclass of :py:class:`MigratingCommand`
:rtype: tuple(basestring, class)
"""
cmd_name = name[3:].replace('_', '-')
callback = getattr(func_module, name)
desc = callback.__doc__ or ''
help = desc.strip().split('\n')[0]
arguments = getattr(callback, 'arguments', [])
body = {
'_args': arguments,
'_callback': staticmethod(callback),
'_description': desc,
'_epilog': desc,
'_help': help
}
claz = type('%sCommand' % cmd_name.title().replace('-', ''),
(MigratingCommand,), body)
return cmd_name, claz
class MigratingCommandMeta(command.CommandMeta):
"""Overwrite module name based on osc_lib.CommandMeta requirements."""
def __new__(mcs, name, bases, cls_dict):
# NOTE(trebskit) little dirty, but should suffice for migration period
cls_dict['__module__'] = 'monascaclient.v2_0.shell'
return super(MigratingCommandMeta, mcs).__new__(mcs, name,
bases, cls_dict)
class MigratingCommand(command.Command, metaclass=MigratingCommandMeta):
"""MigratingCommand is temporary command.
MigratingCommand allows to map function defined
shell commands from :py:module:`monascaclient.v2_0.shell`
into :py:class:`command.Command` instances.
Note:
This class is temporary solution during migrating
to osc_lib and will be removed when all
shell commands are migrated to cliff commands.
"""
_help = None
_args = None
_callback = None
def __init__(self, app, app_args, cmd_name=None):
super(MigratingCommand, self).__init__(app, app_args, cmd_name)
self._client = None
self._endpoint = None
def take_action(self, parsed_args):
return self._callback(self.mon_client, parsed_args)
def get_parser(self, prog_name):
parser = super(MigratingCommand, self).get_parser(prog_name)
for (args, kwargs) in self._args:
parser.add_argument(*args, **kwargs)
parser.add_argument('-j', '--json',
action='store_true',
help='output raw json response')
return parser
@property
def mon_client(self):
if not self._client:
self.log.debug('Initializing mon-client')
self._client = make_client(api_version=self.mon_version,
endpoint=self.mon_url,
session=self.app.client_manager.session)
return self._client
@property
def mon_version(self):
return self.app_args.monasca_api_version
@property
def mon_url(self):
if self._endpoint:
return self._endpoint
app_args = self.app_args
cm = self.app.client_manager
endpoint = app_args.monasca_api_url
if not endpoint:
req_data = {
'service_type': 'monitoring',
'region_name': cm.region_name,
'interface': cm.interface,
}
LOG.debug('Discovering monasca endpoint using %s' % req_data)
endpoint = cm.get_endpoint_for_service_type(**req_data)
else:
LOG.debug('Using supplied endpoint=%s' % endpoint)
self._endpoint = endpoint
return self._endpoint

View File

@@ -1,111 +0,0 @@
# (C) Copyright 2014-2015 Hewlett Packard Enterprise Development Company LP
# Copyright 2017 Fujitsu LIMITED
#
# 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.
"""
Command-line interface to the monasca-client API.
"""
import argparse
import sys
from osc_lib.api import auth
from osc_lib.cli import client_config as cloud_config
from osc_lib import shell
from osc_lib import utils
from oslo_utils import importutils
from monascaclient.osc import migration
from monascaclient import version as mc_version
class MonascaShell(shell.OpenStackShell):
def __init__(self):
super(MonascaShell, self).__init__(
description=__doc__.strip(),
version=mc_version.version_string
)
self.cloud_config = None
def initialize_app(self, argv):
super(MonascaShell, self).initialize_app(argv)
self.cloud_config = cloud_config.OSC_Config(
override_defaults={
'interface': None,
'auth_type': self._auth_type,
},
)
def build_option_parser(self, description, version):
parser = super(MonascaShell, self).build_option_parser(
description,
version
)
parser.set_defaults(cloud=None)
parser = auth.build_auth_plugins_option_parser(parser)
parser = self._append_monasca_args(parser)
return parser
@staticmethod
def _append_monasca_args(parser):
parser.add_argument('--monasca-api-url',
default=utils.env('MONASCA_API_URL'),
help='Defaults to env[MONASCA_API_URL].')
parser.add_argument('--monasca_api_url',
help=argparse.SUPPRESS)
parser.add_argument('--monasca-api-version',
default=utils.env(
'MONASCA_API_VERSION',
default='2_0'),
help='Defaults to env[MONASCA_API_VERSION] or 2_0')
parser.add_argument('--monasca_api_version',
help=argparse.SUPPRESS)
return parser
def _load_commands(self):
version = self.options.monasca_api_version
submodule = importutils.import_versioned_module('monascaclient',
version,
'shell')
self._find_actions(submodule)
def _find_actions(self, actions_module):
for attr in (a for a in dir(actions_module) if a.startswith('do_')):
name, clazz = migration.create_command_class(attr, actions_module)
if 'help' == name:
# help requires no auth
clazz.auth_required = False
self.command_manager.add_command(name, clazz)
def main(args=None):
try:
if args is None:
args = sys.argv[1:]
return MonascaShell().run(args)
except Exception as e:
if '--debug' in args or '-d' in args:
raise
else:
print(e)
sys.exit(1)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

View File

@@ -1,172 +0,0 @@
# (C) Copyright 2014-2017 Hewlett Packard Enterprise Development LP
# Copyright 2017 FUJITSU LIMITED
#
# 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 unittest import mock
import warnings
from oslotest import base
from monascaclient import client
class TestMonascaClient(base.BaseTestCase):
@mock.patch('monascaclient.client.migration')
@mock.patch('monascaclient.client._get_auth_handler')
@mock.patch('monascaclient.client._get_session')
def test_should_warn_when_passing_args(self, _, __, ___):
api_version = mock.Mock()
endpoint = mock.Mock()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
client.Client(api_version, endpoint)
self.assertEqual(1, len(w))
self.assertEqual(DeprecationWarning, w[0].category)
self.assertRegex(
str(w[0].message),
'explicit configuration of the client using'
)
@mock.patch('monascaclient.client.migration')
@mock.patch('monascaclient.client._get_auth_handler')
@mock.patch('monascaclient.client._get_session')
def test_should_not_warn_when_passing_no_args(self, _, __, ___):
api_version = mock.Mock()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
client.Client(api_version)
self.assertEqual(0, len(w))
@mock.patch('monascaclient.client.migration')
@mock.patch('monascaclient.client._get_auth_handler')
@mock.patch('monascaclient.client._get_session')
def test_should_override_endpoint_if_passed_as_arg(self, get_session,
get_auth, _):
api_version = mock.Mock()
endpoint = mock.Mock()
endpoint_fake = mock.Mock()
auth_val = mock.Mock()
get_auth.return_value = auth_val
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
client.Client(api_version, endpoint, endpoint=endpoint_fake)
self.assertEqual(1, len(w))
get_auth.assert_called_once_with({
'endpoint': endpoint
})
get_session.assert_called_once_with(auth_val, {
'endpoint': endpoint
})
@mock.patch('monascaclient.client.migration')
@mock.patch('monascaclient.client._get_auth_handler')
@mock.patch('monascaclient.client._get_session')
def test_should_override_tenant_name_with_project_name(self,
_,
get_auth,
__):
api_version = mock.Mock()
auth_val = mock.Mock()
tenant_name = mock.Mock()
project_name = tenant_name
get_auth.return_value = auth_val
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
client.Client(api_version, tenant_name=tenant_name)
self.assertEqual(1, len(w))
self.assertEqual(DeprecationWarning, w[0].category)
self.assertRegex(
str(w[0].message),
'Usage of tenant_name has been deprecated in favour '
)
get_auth.assert_called_once_with({
'project_name': project_name
})
@mock.patch('monascaclient.client.migration')
@mock.patch('monascaclient.client._get_auth_handler')
@mock.patch('monascaclient.client._get_session')
def test_should_override_insecure_with_negated_verify(self,
_,
get_auth,
__):
api_version = mock.Mock()
auth_val = mock.Mock()
get_auth.return_value = auth_val
for insecure in [True, False]:
warnings.resetwarnings()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
client.Client(api_version, insecure=insecure)
self.assertEqual(1, len(w))
self.assertEqual(DeprecationWarning, w[0].category)
self.assertRegex(
str(w[0].message),
'Usage of insecure has been deprecated in favour of'
)
get_auth.assert_called_once_with({
'verify': not insecure
})
get_auth.reset_mock()
@mock.patch('monascaclient.client.migration')
@mock.patch('monascaclient.client._get_auth_handler')
@mock.patch('monascaclient.client._get_session')
def test_should_reuse_the_session_if_initialized_with_one(self,
get_session,
get_auth,
_):
from keystoneauth1 import session as k_session
api_version = mock.Mock()
session = mock.Mock(spec=k_session.Session)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
client.Client(api_version, session=session)
self.assertEqual(0, len(w))
get_auth.assert_not_called()
get_session.assert_not_called()
@mock.patch('monascaclient.client.migration')
@mock.patch('monascaclient.client._get_auth_handler')
@mock.patch('monascaclient.client._get_session')
def test_should_error_if_session_is_not_in_correct_type(self,
_,
__,
___):
api_version = mock.Mock()
for cls in [str, int, float]:
session = mock.Mock(spec=cls)
self.assertRaises(RuntimeError, client.Client,
api_version, session=session)

View File

@@ -1,61 +0,0 @@
# (C) Copyright 2014-2017 Hewlett Packard Enterprise Development LP
# Copyright 2017 FUJITSU LIMITED
#
# 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 unittest import mock
from oslotest import base
from monascaclient import shell
class TestMonascaShell(base.BaseTestCase):
@mock.patch('monascaclient.shell.auth')
def test_should_use_auth_plugin_option_parser(self, auth):
auth.build_auth_plugins_option_parser = apop = mock.Mock()
shell.MonascaShell().run([])
apop.assert_called_once()
def test_should_specify_monasca_args(self):
expected_args = [
'--monasca-api-url',
'--monasca-api-version',
'--monasca_api_url',
'--monasca_api_version',
]
parser = mock.Mock()
parser.add_argument = aa = mock.Mock()
shell.MonascaShell._append_monasca_args(parser)
aa.assert_called()
for mc in aa.mock_calls:
name = mc[1][0]
self.assertIn(name, expected_args)
@mock.patch('monascaclient.shell.importutils')
def test_should_load_commands_based_on_api_version(self, iu):
iu.import_versioned_module = ivm = mock.Mock()
instance = shell.MonascaShell()
instance.options = mock.Mock()
instance.options.monasca_api_version = version = mock.Mock()
instance._find_actions = mock.Mock()
instance._load_commands()
ivm.assert_called_once_with('monascaclient', version, 'shell')

View File

@@ -1,165 +0,0 @@
# Copyright 2017 FUJITSU LIMITED
#
# 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 unittest import mock
from oslotest import base
from monascaclient.osc import migration as migr
from monascaclient.v2_0 import alarm_definitions as ad
from monascaclient.v2_0 import shell
class FakeV2Client(object):
def __init__(self):
super(FakeV2Client, self).__init__()
self.alarm_definitions = mock.Mock(
spec=ad.AlarmDefinitionsManager)
class TestAlarmDefinitionShellV2(base.BaseTestCase):
@mock.patch('monascaclient.osc.migration.make_client')
def test_should_update(self, mc):
mc.return_value = c = FakeV2Client()
ad_id = '0495340b-58fd-4e1c-932b-5e6f9cc96490'
ad_name = 'alarm_name'
ad_desc = 'test_alarm_definition'
ad_expr = 'avg(Test_Metric_1)>=10'
ad_action_id = '16012650-0b62-4692-9103-2d04fe81cc93'
ad_action_enabled = 'True'
ad_match_by = 'hostname'
ad_severity = 'CRITICAL'
raw_args = [
ad_id, ad_name, ad_desc, ad_expr,
ad_action_id, ad_action_id, ad_action_id, ad_action_enabled,
ad_match_by, ad_severity
]
name, cmd_clazz = migr.create_command_class(
'do_alarm_definition_update',
shell
)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
c.alarm_definitions.update.assert_called_once_with(
actions_enabled=True,
alarm_actions=[ad_action_id],
alarm_id=ad_id,
description=ad_desc,
expression=ad_expr,
match_by=[ad_match_by],
name=ad_name,
ok_actions=[ad_action_id],
severity=ad_severity,
undetermined_actions=[ad_action_id]
)
@mock.patch('monascaclient.osc.migration.make_client')
def test_alarm_definitions_list(self, mc):
mc.return_value = c = FakeV2Client()
c.alarm_definitions.list.return_value = [{
"name": "ntp_sync_check",
"id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"expression": "(max(ntp.offset{}, deterministic)>=1)",
"match_by": ['hostname'],
"description": "NTP time sync check",
"actions_enabled": True,
"deterministic": True,
"alarm_actions": ['aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'],
"ok_actions": [],
"undetermined_actions": [],
"severity": "HIGH",
}]
name, cmd_class = migr.create_command_class(
'do_alarm_definition_list',
shell
)
cmd = cmd_class(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
raw_args = []
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
c.alarm_definitions.list.assert_called_once()
@mock.patch('monascaclient.osc.migration.make_client')
def test_should_patch_name(self, mc):
ad_id = '0495340b-58fd-4e1c-932b-5e6f9cc96490'
ad_name = 'patch_name'
raw_args = '{0} --name {1}'.format(ad_id, ad_name).split(' ')
self._patch_test(mc, raw_args, alarm_id=ad_id, name=ad_name)
@mock.patch('monascaclient.osc.migration.make_client')
def test_should_patch_actions(self, mc):
ad_id = '0495340b-58fd-4e1c-932b-5e6f9cc96490'
ad_action_id = '16012650-0b62-4692-9103-2d04fe81cc93'
actions = ['alarm-actions', 'ok-actions',
'undetermined-actions']
for action in actions:
raw_args = ('{0} --{1} {2}'.format(ad_id, action, ad_action_id)
.split(' '))
self._patch_test(mc, raw_args, **{
'alarm_id': ad_id,
action.replace('-', '_'): [ad_action_id]
})
@mock.patch('monascaclient.osc.migration.make_client')
def test_should_patch_severity(self, mc):
ad_id = '0495340b-58fd-4e1c-932b-5e6f9cc96490'
severity_types = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']
for st in severity_types:
raw_args = ('{0} --severity {1}'.format(ad_id, st)
.split(' '))
self._patch_test(mc, raw_args, alarm_id=ad_id, severity=st)
@mock.patch('monascaclient.osc.migration.make_client')
def test_should_not_patch_unknown_severity(self, mc):
ad_id = '0495340b-58fd-4e1c-932b-5e6f9cc96490'
st = 'foo'
raw_args = ('{0} --severity {1}'.format(ad_id, st)
.split(' '))
self._patch_test(mc, raw_args, called=False)
@staticmethod
def _patch_test(mc, args, called=True, **kwargs):
mc.return_value = c = FakeV2Client()
name, cmd_clazz = migr.create_command_class(
'do_alarm_definition_patch',
shell
)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(args)
cmd.run(parsed_args)
if called:
c.alarm_definitions.patch.assert_called_once_with(**kwargs)
else:
c.alarm_definitions.patch.assert_not_called()

View File

@@ -1,85 +0,0 @@
# Copyright 2017 FUJITSU LIMITED
#
# 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 unittest import mock
from oslotest import base
from monascaclient.osc import migration as migr
from monascaclient.v2_0 import metrics
from monascaclient.v2_0 import shell
class FakeV2Client(object):
def __init__(self):
super(FakeV2Client, self).__init__()
self.metrics = mock.Mock(spec=metrics.MetricsManager)
class TestMetricsShellV2(base.BaseTestCase):
def test_bad_metrics(self):
raw_args_list = [
['metric1'],
['123'],
['']
]
name, cmd_clazz = migr.create_command_class('do_metric_create',
shell)
for raw_args in raw_args_list:
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
self.assertRaises(SystemExit, parser.parse_args, raw_args)
@mock.patch('monascaclient.osc.migration.make_client')
def test_metric_create(self, mc):
mc.return_value = c = FakeV2Client()
raw_args = 'metric1 123 --time 1395691090'.split(' ')
name, cmd_clazz = migr.create_command_class('do_metric_create',
shell)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
data = {'timestamp': 1395691090,
'name': 'metric1',
'value': 123.0}
c.metrics.create.assert_called_once_with(**data)
@mock.patch('monascaclient.osc.migration.make_client')
def test_metric_create_with_project_id(self, mc):
mc.return_value = c = FakeV2Client()
project_id = 'd48e63e76a5c4e05ba26a1185f31d4aa'
raw_args = ('metric1 123 --time 1395691090 --project-id %s'
% project_id).split(' ')
name, cmd_clazz = migr.create_command_class('do_metric_create',
shell)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
data = {'timestamp': 1395691090,
'name': 'metric1',
'tenant_id': project_id,
'value': 123.0}
c.metrics.create.assert_called_once_with(**data)

View File

@@ -1,52 +0,0 @@
# Copyright 2017 FUJITSU LIMITED
#
# 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 unittest import mock
from oslotest import base
from monascaclient.osc import migration as migr
from monascaclient.v2_0 import notificationtypes
from monascaclient.v2_0 import shell
class FakeV2Client(object):
def __init__(self):
super(FakeV2Client, self).__init__()
self.notificationtypes = mock.Mock(
spec=notificationtypes.NotificationTypesManager)
class TestNotificationsTypesShellV2(base.BaseTestCase):
@mock.patch('monascaclient.osc.migration.make_client')
def test_notification_types_list(self, mc):
mc.return_value = c = FakeV2Client()
c.notificationtypes.list.return_value = [
{"type": "WEBHOOK"},
{"type": "EMAIL"},
{"type": "PAGERDUTY"}
]
raw_args = []
name, cmd_clazz = migr.create_command_class('do_notification_type_list',
shell)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
c.notificationtypes.list.assert_called_once()

View File

@@ -1,151 +0,0 @@
# Copyright 2017 FUJITSU LIMITED
#
# 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 unittest import mock
from oslotest import base
from monascaclient.osc import migration as migr
from monascaclient.v2_0 import notifications
from monascaclient.v2_0 import shell
class FakeV2Client(object):
def __init__(self):
super(FakeV2Client, self).__init__()
self.notifications = mock.Mock(spec=notifications.NotificationsManager)
class TestNotificationsShellV2(base.BaseTestCase):
@mock.patch('monascaclient.osc.migration.make_client')
def test_notification_create_email(self, mc):
mc.return_value = c = FakeV2Client()
raw_args = ['email1', 'EMAIL', 'john.doe@hp.com']
name, cmd_clazz = migr.create_command_class('do_notification_create',
shell)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
data = {'name': 'email1',
'type': 'EMAIL',
'address': 'john.doe@hp.com'}
c.notifications.create.assert_called_once_with(**data)
@mock.patch('monascaclient.osc.migration.make_client')
def test_notification_create_webhook(self, mc):
mc.return_value = c = FakeV2Client()
raw_args = ['mypost', 'WEBHOOK', 'http://localhost:8080']
name, cmd_clazz = migr.create_command_class('do_notification_create',
shell)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
data = {'name': 'mypost',
'type': 'WEBHOOK',
'address': 'http://localhost:8080'}
c.notifications.create.assert_called_once_with(**data)
@mock.patch('monascaclient.osc.migration.make_client')
def test_good_notifications_patch(self, mc):
args = '--type EMAIL --address john.doe@hpe.com --period 0'
data = {'type': 'EMAIL',
'address': 'john.doe@hpe.com',
'period': 0}
self._patch_test(mc, args, data)
@mock.patch('monascaclient.osc.migration.make_client')
def test_good_notifications_patch_just_name(self, mc):
name = 'fred'
args = '--name ' + name
data = {'name': name}
self._patch_test(mc, args, data)
@mock.patch('monascaclient.osc.migration.make_client')
def test_good_notifications_patch_just_address(self, mc):
address = 'fred@fl.com'
args = '--address ' + address
data = {'address': address}
self._patch_test(mc, args, data)
@mock.patch('monascaclient.osc.migration.make_client')
def test_good_notifications_patch_just_period(self, mc):
period = 0
args = '--period ' + str(period)
data = {'period': period}
self._patch_test(mc, args, data)
@mock.patch('monascaclient.osc.migration.make_client')
def test_good_notifications_patch_recurring_email(self, mc):
args = '--type EMAIL --address john.doe@hpe.com --period 60'
data = {'type': 'EMAIL',
'address': 'john.doe@hpe.com',
'period': 60}
self._patch_test(mc, args, data)
@mock.patch('monascaclient.osc.migration.make_client')
def test_good_notifications_update(self, mc):
mc.return_value = c = FakeV2Client()
id_str = '0495340b-58fd-4e1c-932b-5e6f9cc96491'
raw_args = ('{0} notification_updated_name '
'EMAIL john.doe@hpe.com 0').format(id_str).split(' ')
name, cmd_clazz = migr.create_command_class('do_notification_update',
shell)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
data = {
'name': 'notification_updated_name',
'type': 'EMAIL',
'address': 'john.doe@hpe.com',
'period': 0,
'notification_id': id_str
}
c.notifications.update.assert_called_once_with(**data)
@staticmethod
def _patch_test(mc, args, data):
mc.return_value = c = FakeV2Client()
id_str = '0495340b-58fd-4e1c-932b-5e6f9cc96490'
raw_args = '{0} {1}'.format(id_str, args).split(' ')
name, cmd_clazz = migr.create_command_class('do_notification_patch',
shell)
cmd = cmd_clazz(mock.Mock(), mock.Mock())
parser = cmd.get_parser(name)
parsed_args = parser.parse_args(raw_args)
cmd.run(parsed_args)
# add notification_id to data
data['notification_id'] = id_str
c.notifications.patch.assert_called_once_with(**data)

View File

@@ -1,18 +0,0 @@
# (C) Copyright 2014 Hewlett Packard Enterprise Development Company LP
#
# 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 monascaclient.v2_0.client import Client
__all__ = ['Client']

View File

@@ -1,69 +0,0 @@
# (C) Copyright 2014-2015 Hewlett Packard Enterprise Development Company LP
# Copyright 2017 FUJITSU LIMITED
#
# 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 monascaclient.common import monasca_manager
class AlarmDefinitionsManager(monasca_manager.MonascaManager):
base_url = '/alarm-definitions'
def create(self, **kwargs):
"""Create an alarm definition."""
resp = self.client.create(url=self.base_url,
json=kwargs)
return resp
def get(self, **kwargs):
"""Get the details for a specific alarm definition."""
# NOTE(trebskit) should actually be find_one, but
# monasca does not support expected response format
url = '%s/%s' % (self.base_url, kwargs['alarm_id'])
resp = self.client.list(path=url)
return resp
def list(self, **kwargs):
"""Get a list of alarm definitions."""
return self._list('', 'dimensions', **kwargs)
def delete(self, **kwargs):
"""Delete a specific alarm definition."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
resp = self.client.delete(url_str)
return resp
def update(self, **kwargs):
"""Update a specific alarm definition."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
resp = self.client.create(url=url_str,
method='PUT',
json=kwargs)
return resp
def patch(self, **kwargs):
"""Patch a specific alarm definition."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
resp = self.client.create(url=url_str,
method='PATCH',
json=kwargs)
return resp

View File

@@ -1,97 +0,0 @@
# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP
# Copyright 2017 FUJITSU LIMITED
#
# 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 urllib import parse
from monascaclient.common import monasca_manager
class AlarmsManager(monasca_manager.MonascaManager):
base_url = '/alarms'
def get(self, **kwargs):
"""Get the details for a specific alarm."""
# NOTE(trebskit) should actually be find_one, but
# monasca does not support expected response format
url = '%s/%s' % (self.base_url, kwargs['alarm_id'])
resp = self.client.list(path=url)
return resp
def list(self, **kwargs):
"""Get a list of alarms."""
return self._list('', 'metric_dimensions', **kwargs)
def delete(self, **kwargs):
"""Delete a specific alarm."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
resp = self.client.delete(url_str)
return resp
def update(self, **kwargs):
"""Update a specific alarm."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
body = self.client.create(url=url_str,
method='PUT',
json=kwargs)
return body
def patch(self, **kwargs):
"""Patch a specific alarm."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
resp = self.client.create(url=url_str,
method='PATCH',
json=kwargs)
return resp
def count(self, **kwargs):
url_str = self.base_url + '/count'
if 'metric_dimensions' in kwargs:
dimstr = self.get_dimensions_url_string(
kwargs['metric_dimensions'])
kwargs['metric_dimensions'] = dimstr
if kwargs:
url_str = url_str + '?%s' % parse.urlencode(kwargs, True)
body = self.client.list(url_str)
return body
def history(self, **kwargs):
"""History of a specific alarm."""
url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id']
del kwargs['alarm_id']
if kwargs:
url_str = url_str + '?%s' % parse.urlencode(kwargs, True)
resp = self.client.list(url_str)
return resp['elements'] if type(resp) is dict else resp
def history_list(self, **kwargs):
"""History list of alarm state."""
url_str = self.base_url + '/state-history/'
if 'dimensions' in kwargs:
dimstr = self.get_dimensions_url_string(kwargs['dimensions'])
kwargs['dimensions'] = dimstr
if kwargs:
url_str = url_str + '?%s' % parse.urlencode(kwargs, True)
resp = self.client.list(url_str)
return resp['elements'] if type(resp) is dict else resp

View File

@@ -1,40 +0,0 @@
# (C) Copyright 2014-2015 Hewlett Packard Enterprise Development Company LP
# Copyright 2017 FUJITSU LIMITED
#
# 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 osc_lib.api import api
from monascaclient.v2_0 import alarm_definitions as ad
from monascaclient.v2_0 import alarms
from monascaclient.v2_0 import metrics
from monascaclient.v2_0 import notifications
from monascaclient.v2_0 import notificationtypes as nt
class Client(object):
def __init__(self, *args, **kwargs):
"""Initialize a new http client for the monasca API."""
client = MonascaApi(*args, **kwargs)
self.metrics = metrics.MetricsManager(client)
self.notifications = notifications.NotificationsManager(client)
self.alarms = alarms.AlarmsManager(client)
self.alarm_definitions = ad.AlarmDefinitionsManager(client)
self.notificationtypes = nt.NotificationTypesManager(client)
class MonascaApi(api.BaseAPI):
SERVICE_TYPE = "monitoring"

View File

@@ -1,56 +0,0 @@
# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
# Copyright 2017 FUJITSU LIMITED
#
# 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 monascaclient.common import monasca_manager
class MetricsManager(monasca_manager.MonascaManager):
base_url = '/metrics'
def create(self, **kwargs):
"""Create a metric."""
url_str = self.base_url
if 'tenant_id' in kwargs:
url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id']
del kwargs['tenant_id']
data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs
body = self.client.create(url=url_str, json=data)
return body
def list(self, **kwargs):
"""Get a list of metrics."""
return self._list('', 'dimensions', **kwargs)
def list_names(self, **kwargs):
"""Get a list of metric names."""
return self._list('/names', 'dimensions', **kwargs)
def list_measurements(self, **kwargs):
"""Get a list of measurements based on metric definition filters."""
return self._list('/measurements', 'dimensions', **kwargs)
def list_statistics(self, **kwargs):
"""Get a list of measurement statistics based on metric def filters."""
return self._list('/statistics', 'dimensions', **kwargs)
def list_dimension_names(self, **kwargs):
"""Get a list of metric dimension names."""
return self._list('/dimensions/names', **kwargs)
def list_dimension_values(self, **kwargs):
"""Get a list of metric dimension values."""
return self._list('/dimensions/names/values', **kwargs)

View File

@@ -1,68 +0,0 @@
# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
# Copyright 2017 FUJITSU LIMITED
#
# 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 monascaclient.common import monasca_manager
class NotificationsManager(monasca_manager.MonascaManager):
base_url = '/notification-methods'
def create(self, **kwargs):
"""Create a notification."""
body = self.client.create(url=self.base_url,
json=kwargs)
return body
def get(self, **kwargs):
"""Get the details for a specific notification."""
# NOTE(trebskit) should actually be find_one, but
# monasca does not support expected response format
url = '%s/%s' % (self.base_url, kwargs['notification_id'])
resp = self.client.list(path=url)
return resp
def list(self, **kwargs):
"""Get a list of notifications."""
return self._list('', **kwargs)
def delete(self, **kwargs):
"""Delete a notification."""
url = self.base_url + '/%s' % kwargs['notification_id']
resp = self.client.delete(url=url)
return resp
def update(self, **kwargs):
"""Update a notification."""
url_str = self.base_url + '/%s' % kwargs['notification_id']
del kwargs['notification_id']
resp = self.client.create(url=url_str,
method='PUT',
json=kwargs)
return resp
def patch(self, **kwargs):
"""Patch a notification."""
url_str = self.base_url + '/%s' % kwargs['notification_id']
del kwargs['notification_id']
resp = self.client.create(url=url_str,
method='PATCH',
json=kwargs)
return resp

View File

@@ -1,25 +0,0 @@
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright 2017 FUJITSU LIMITED
#
# 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 monascaclient.common import monasca_manager
class NotificationTypesManager(monasca_manager.MonascaManager):
base_url = '/notification-methods/types'
def list(self, **kwargs):
"""Get a list of notifications."""
return self._list('', **kwargs)

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +0,0 @@
# Copyright 2017 FUJITSU LIMITED
#
# 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 pbr import version
__all__ = ['version_info', 'version_string']
version_info = version.VersionInfo('python-monascaclient')
version_string = version_info.version_string()

View File

@@ -1,12 +0,0 @@
---
- hosts: all
tasks:
- name: Login to Dockerhub
command: "docker login -u {{ doker_hub_login_client.user }} -p {{ doker_hub_login_client.password }}"
no_log: true
- name: List images
shell: "docker images --format '{% raw %}{{ .Repository }}:{{ .Tag }}{% endraw %}' | grep monasca"
- name: Push to Docker Hub all tags
shell: "docker push monasca/client:{{ zuul.tag if zuul.pipeline == 'release' else 'master'}}"

View File

@@ -1,6 +0,0 @@
---
upgrade:
- |
Python 2.7 support has been dropped. Last release of python-monascaclient
to support python 2.7 is OpenStack Train. The minimum version of Python now
supported is Python 3.6.

View File

@@ -1,11 +0,0 @@
---
prelude: >
Documentation done right by Openstack process.
issues:
- |
Removed the case where command documentation (held previously in markdown)
is out-of-sync with the command itself.
upgrade:
- |
Added details about using the CLI variant. Documented the usage
of Python API.

View File

@@ -1,4 +0,0 @@
---
features:
- |
Adds support for setting notification period for all types.

View File

@@ -1,82 +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.
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.6'
# 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',
'reno.sphinxext'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
openstackdocs_repo_name = u'openstack/python-monascaclient'
project = u'Monasca Client ReleaseNotes Docs'
# Release notes do not need a version number in the title, they
# cover multiple releases.
version = ''
release = ''
openstackdocs_use_storyboard = True
openstackdocs_auto_name = False
copyright = u'2014-present, OpenStack Foundation'
author = u'OpenStack Foundation'
# 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. See the documentation for
# a list of builtin themes.
html_theme = 'openstackdocs'
# Output file base name for HTML help builder.
htmlhelp_basename = 'MonascaClientReleaseNotesDoc'
# -- Options for LaTeX output ---------------------------------------------
latex_documents = [(
master_doc, 'MonascaClientReleaseNotes.tex',
u'Monasca Client Release Notes', [author],
'manual'
)]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'monascaclientreleasenotes',
u'Monasca Client Release Notes', [author],
1)
]
# -- Options for Internationalization output ------------------------------
locale_dirs = ['locale/']

View File

@@ -1,19 +0,0 @@
============================
Monitoring API Release Notes
============================
Contents:
.. toctree::
:maxdepth: 1
unreleased
yoga
xena
wallaby
victoria
ussuri
train
stein
rocky
queens

View File

@@ -1,6 +0,0 @@
===================================
Queens Series Release Notes
===================================
.. release-notes::
:branch: stable/queens

View File

@@ -1,6 +0,0 @@
===================================
Rocky Series Release Notes
===================================
.. release-notes::
:branch: stable/rocky

View File

@@ -1,6 +0,0 @@
===================================
Stein Series Release Notes
===================================
.. release-notes::
:branch: stable/stein

View File

@@ -1,6 +0,0 @@
==========================
Train Series Release Notes
==========================
.. release-notes::
:branch: stable/train

View File

@@ -1,5 +0,0 @@
==============================
Current Series Release Notes
==============================
.. release-notes::

View File

@@ -1,6 +0,0 @@
===========================
Ussuri Series Release Notes
===========================
.. release-notes::
:branch: stable/ussuri

View File

@@ -1,6 +0,0 @@
=============================
Victoria Series Release Notes
=============================
.. release-notes::
:branch: stable/victoria

View File

@@ -1,6 +0,0 @@
============================
Wallaby Series Release Notes
============================
.. release-notes::
:branch: stable/wallaby

View File

@@ -1,6 +0,0 @@
=========================
Xena Series Release Notes
=========================
.. release-notes::
:branch: stable/xena

View File

@@ -1,6 +0,0 @@
=========================
Yoga Series Release Notes
=========================
.. release-notes::
:branch: stable/yoga

View File

@@ -1,19 +0,0 @@
# Requirements lower bounds listed here are our best effort to keep them up to
# date but we do not test them so no guarantee of having them all correct. If
# you find any incorrect lower bounds, let us know or propose a fix.
# The order of packages is significant, because pip processes them in the order
# of appearance. Changing the order has an impact on the overall integration
# process, which may cause wedges in the gate later.
osc-lib>=1.8.0 # Apache-2.0
oslo.serialization!=2.19.1,>=2.18.0 # Apache-2.0
oslo.utils>=3.33.0 # Apache-2.0
Babel!=2.4.0,>=2.3.4 # BSD
iso8601>=0.1.11 # MIT
pbr!=2.1.0,>=2.0.0 # Apache-2.0
PrettyTable>=0.7.2 # BSD
PyYAML>=3.12 # MIT

View File

@@ -1,28 +0,0 @@
[metadata]
name = python-monascaclient
summary = Monasca API Client Library
description-file = README.rst
author = OpenStack
author-email = openstack-discuss@lists.openstack.org
home-page = https://docs.openstack.org/python-monascaclient/latest/
python-requires = >=3.6
classifier =
Environment :: Console
Intended Audience :: Information Technology
Intended Audience :: System Administrators
License :: OSI Approved :: Apache Software License
Operating System :: POSIX :: Linux
Programming Language :: Python
Programming Language :: Python :: Implementation :: CPython
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: 3
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
[files]
packages = monascaclient
[entry_points]
console_scripts =
monasca = monascaclient.shell:main

View File

@@ -1,20 +0,0 @@
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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 setuptools
setuptools.setup(
setup_requires=['pbr>=2.0.0'],
pbr=True)

View File

@@ -1,14 +0,0 @@
# The order of packages is significant, because pip processes them in the order
# of appearance. Changing the order has an impact on the overall integration
# process, which may cause wedges in the gate later.
hacking>=3.0.1,<3.1.0 # Apache-2.0
bandit>=1.1.0 # Apache-2.0
coverage!=4.4,>=4.0 # Apache-2.0
oslotest>=3.2.0 # Apache-2.0
stestr>=1.0.0
testscenarios>=0.4 # Apache-2.0/BSD
testtools>=2.2.0 # MIT
doc8>=0.8.1 # Apache-2.0

99
tox.ini
View File

@@ -1,99 +0,0 @@
[tox]
envlist = py38,pypy,cover,pep8
minversion = 3.1.1
skipsdist = True
ignore_basepython_conflict = True
[testenv]
basepython = python3
setenv =
VIRTUAL_ENV={envdir}
OS_TEST_PATH=monascaclient/tests
PYTHONWARNINGS=default::DeprecationWarning
passenv = *_proxy
*_PROXY
usedevelop = True
install_command = pip install {opts} {packages}
deps =
-c{env:UPPER_CONSTRAINTS_FILE:https://releases.openstack.org/constraints/upper/master}
-r{toxinidir}/test-requirements.txt
-r{toxinidir}/requirements.txt
allowlist_externals = bash
find
rm
commands =
find {toxinidir} -type f -name "*.pyc" -delete
stestr run {posargs}
[testenv:cover]
setenv =
PYTHON=coverage run --source monascaclient --parallel-mode
commands =
coverage erase
stestr run {posargs}
coverage combine
coverage html -d cover
coverage xml -o cover/coverage.xml
coverage report
[testenv:debug]
commands = oslo_debug_helper -t {env:OS_TEST_PATH} {posargs}
[testenv:pep8]
skip_install = True
usedevelop = False
commands =
{[testenv:flake8]commands}
{[testenv:bandit]commands}
{[testenv:checkniceness]commands}
[testenv:flake8]
skip_install = True
usedevelop = False
commands = flake8 monascaclient
[testenv:bandit]
skip_install = True
usedevelop = False
commands = bandit -r monascaclient -n5 -x {env:OS_TEST_PATH}
[testenv:docs]
deps = -c{env:TOX_CONSTRAINTS_FILE:https://releases.openstack.org/constraints/upper/master}
-r{toxinidir}/doc/requirements.txt
description = Builds full monascaclient documentation
commands =
{[testenv:devdocs]commands}
{[testenv:releasenotes]commands}
[testenv:devdocs]
deps = {[testenv:docs]deps}
description = Builds developer documentation
commands =
rm -rf {toxinidir}/doc/build {toxinidir}/doc/source/contributor/api
sphinx-build -a -W -b html doc/source doc/build/html
[testenv:releasenotes]
deps = {[testenv:docs]deps}
description = Called from CI script to test and publish the Release Notes
commands =
rm -rf releasenotes/build
sphinx-build -a -W -E -d {toxinidir}/releasenotes/build/doctrees -b html \
{toxinidir}/releasenotes/source {toxinidir}/releasenotes/build/html
[testenv:checkniceness]
description = Validates (pep-like) documenation
commands =
doc8 --file-encoding utf-8 {toxinidir}/doc
doc8 --file-encoding utf-8 {toxinidir}/releasenotes
[testenv:venv]
commands = {posargs}
[hacking]
import_exceptions =
[flake8]
show-source = True
max-line-length = 100
builtins = _
exclude=.venv,.git,.tox,dist,client_api_example.py,*lib/python*,*egg,build