Merge "Cleanup repo and update documentation"

This commit is contained in:
Jenkins 2017-08-07 07:11:33 +00:00 committed by Gerrit Code Review
commit 84cf30a4f1
11 changed files with 404 additions and 854 deletions

View File

@ -63,8 +63,6 @@ Usage:
monasca help <command>
monasca -j <command>
This outputs the results in json format. Normally output is in table format.
@ -73,7 +71,7 @@ Monasca API RESTful interface. This is provided through environment or CLI
parameters.
Environmental Variables
~~~~~~~~~~~~~~~~~~~~~~~
=======================
Environmental variables can be sourced, or optionally passed in as CLI arguments.
It is easiest to source them first and then use the CLI.
@ -106,28 +104,312 @@ When using Vagrant Environment with middleware disabled::
The Monasca API will treat the auth token as the tenant ID when Keystone is not enabled.
Usage
=====
You'll find complete documentation on the shell by running
``monasca help``::
usage: monasca [-j] [--version] [-d] [-v] [-k] [--cert-file CERT_FILE]
[--key-file KEY_FILE] [--os-cacert OS_CACERT]
[--timeout TIMEOUT] [--os-username OS_USERNAME]
[--os-password OS_PASSWORD] [--os-project-id OS_PROJECT_ID]
[--os-user-domain-id OS_USER_DOMAIN_ID] [--os-user-domain-name OS_USER_DOMAIN_NAME]
[--os-project-name OS_PROJECT_NAME]
[--os-project-domain-id OS_PROJECT_DOMAIN_ID] [--os-project-domain-name OS_PROJECT_DOMAIN_NAME]
[--os-auth-url OS_AUTH_URL] [--os-auth-version OS_AUTH_VERSION] [--os-region-name OS_REGION_NAME]
[--os-auth-token OS_AUTH_TOKEN] [--os-no-client-auth]
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]
[--os-service-type OS_SERVICE_TYPE]
[--os-endpoint-type OS_ENDPOINT_TYPE]
<subcommand> ...
Command-line interface to the monasca-client API.
Command-line interface to the OpenStack APIs
positional arguments:
<subcommand>
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.
@ -135,14 +417,16 @@ You'll find complete documentation on the shell by running
alarm-definition-show Describe the alarm definition.
alarm-definition-update Update the alarm definition.
alarm-delete Delete the alarm.
alarm-history Alarm state history.
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.
alarm-patch Patch the alarm state.
alarm-show Describe the alarm.
alarm-update Update the alarm.
dimension-name-list List names of dimensions.
dimension-value-list List the dimension values for a given dimension name.
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.
@ -154,73 +438,22 @@ You'll find complete documentation on the shell by running
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 Prints all of the commands and options to stdout.
help Display help about this program or one of its
subcommands.
optional arguments:
-j, --json output raw json response
--version Shows the client version and exits.
-d, --debug Defaults to env[MONASCA_DEBUG].
-v, --verbose Print more verbose output.
-k, --insecure Explicitly allow the client to perform "insecure" SSL
(https) requests. The server's certificate will not
be verified against any certificate authorities. This
option should be used with caution.
--cert-file CERT_FILE Path of certificate file to use in SSL connection.
This file can optionally be prepended with the
private key.
--key-file KEY_FILE Path of client key to use in SSL connection.This
option is not necessary if your key is prepended to
your cert file.
--os-cacert OS_CACERT Specify a CA bundle file to use in verifying a
TLS (https) server certificate. Defaults to
env[OS_CACERT]. Without either of these, the
client looks for the default system CA
certificates.
--timeout TIMEOUT Number of seconds to wait for a response.
--os-username OS_USERNAME Defaults to env[OS_USERNAME].
--os-password OS_PASSWORD Defaults to env[OS_PASSWORD].
--os-project-id OS_PROJECT_ID
Defaults to env[OS_PROJECT_ID].
--os-project-name OS_PROJECT_NAME
Defaults to env[OS_PROJECT_NAME].
--os-domain-id OS_DOMAIN_ID
Defaults to env[OS_DOMAIN_ID].
--os-domain-name OS_DOMAIN_NAME
Defaults to env[OS_DOMAIN_NAME].
--os-auth-url OS_AUTH_URL Defaults to env[OS_AUTH_URL].
--os-auth-version OS_AUTH_VERSION
Defaults to env[OS_AUTH_VERSION].
--os-region-name OS_REGION_NAME
Defaults to env[OS_REGION_NAME].
--os-auth-token OS_AUTH_TOKEN
Defaults to env[OS_AUTH_TOKEN].
--os-no-client-auth Do not contact keystone for a token. Defaults to
env[OS_NO_CLIENT_AUTH].
--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
--os-service-type OS_SERVICE_TYPE
Defaults to env[OS_SERVICE_TYPE].
--os-endpoint-type OS_ENDPOINT_TYPE
Defaults to env[OS_ENDPOINT_TYPE].
See "mon help COMMAND" for help on a specific command.
Bash Completion
~~~~~~~~~~~~~~~
---------------
Basic command tab completion can be enabled by sourcing the bash completion script.
::
source /usr/local/share/monasca.bash_completion
monasca completion >> /usr/local/share/monasca.bash_completion
Metrics Examples
~~~~~~~~~~~~~~~~
----------------
Note: To see complete usage: 'monasca help' and 'monasca help <command>'
metric-create::
@ -354,74 +587,90 @@ alarm-patch::
Python API
----------
==========
There's also a complete Python API.
In order to use the python api directly, you must pass in a valid auth token and
There are three possible approaches, at the moment, you can take to use the client
directly. On high level, these approaches can be described as:
* using **username** and **password**
* using **token**
* using existing <session `https://github.com/openstack/keystoneauth/blob/master/keystoneauth1/session.py>_`
Username & password
-------------------
Following approach allows to initialize the monascaclient in a traditional way.
It requires **username** and **password**. Initialization of the client
can be threfore executed with::
c = mon_client.Client(api_version='2_0',
username=os.environ.get('OS_USERNAME', 'mini-mon'),
password=os.environ.get('OS_PASSWORD', 'password'),
auth_url=os.environ.get('OS_AUTH_URL', 'http://127.0.0.1/identity'),
project_name=os.environ.get('OS_PROJECT_NAME', 'mini-mon'),
endpoint='http://127.0.0.1:8070/v2.0')
Token
-----
In order to use the monasclient directly, you must pass in a valid auth token and
monasca api endpoint, or you can pass in the credentials required by the keystone
client and let the Python API do the authentication. The user can obtain the token
and endpoint using the keystone client api:
http://docs.openstack.org/python-keystoneclient/latest/.
The service catalog name for our API endpoint is "monasca".
http://docs.openstack.org/developer/python-keystoneclient/. Once **token**
is available, a monascaclient can be initialized with following code::
Start using the monascaclient API by constructing the monascaclient client.Client class.
The Client class takes these parameters: api_version, endpoint, and token.
The Client class is used to call all monasca-api resource commands (i.e.
client.Client.metrics.create(fields)).
c = mon_client.Client(api_version='2_0',
endpoint='http://127.0.0.1:8070/v2.0'
token=token_id,
auth_url=os.environ.get('OS_AUTH_URL', 'http://127.0.0.1/identity'),
project_name=os.environ.get('OS_PROJECT_NAME', 'mini-mon'))
Long running users of the Client will receive an indication
that the keystone token has expired when they receive an HTTP response
code of 401 Unauthorized from the monasca-API. In this case, it is
up to the user to get a new token from keystone which can be passed
into the client.Client.replace_token(token) method. If you constructed
the Client with all the keystone credentials needed to authenticate,
then the API will automatically try one time to re-authenticate with
keystone whenever the token expires.
The api_version matches the version of the Monasca API. Currently it is 'v2_0'.
When calling the commands, refer to monascaclient.v2_0.shell.py 'do_<command>'
to see the required and optional fields for each command.
https://github.com/openstack/python-monascaclient/blob/master/monascaclient/v2_0/shell.py
Refer to the example in python-monascaclient/client_api_example.py for more detail::
from monascaclient import client
from monascaclient import ksclient
import monascaclient.exc as exc
import time
api_version = '2_0'
# Authenticate to Keystone
keystone_url = 'http://keystone:5000/v3'
ks = ksclient.KSClient(auth_url=keystone_url, username='user', password='password')
# construct the mon client
monasca_client = client.Client(api_version, ks.monasca_url, token=ks.token)
# call the metric-create command
dimensions = {'instance_id': '12345', 'service': 'hello'}
fields = {}
fields['name'] = 'cindy1'
fields['dimensions'] = dimensions
fields['timestamp'] = time.time() * 1000
fields['value'] = 222.333
try:
resp = monasca_client.metrics.create(**fields)
except exc.HTTPException as he:
print(he.code)
print(he.message)
else:
print(resp)
License
Session
-------
Usage of the monasclient with existing session can be expressed
with following code::
from keystoneauth1 import session
from keystoneauth1 import identity
auth = identity.Token(auth_url=os.environ.get('OS_AUTH_URL', 'http://127.0.0.1/identity'),
token=token_id,
project_name=os.environ.get('OS_PROJECT_NAME', 'mini-mon'))
sess = session.Session(auth=auth)
c = client.Client(api_version='2_0',
endpoint='http://127.0.0.1:8070/v2.0'
session=sess)
The session object construction is much broader topic. It involves picking
one of the following authorization methods:
* Password
* Token
Alternatively, if Keystone version is known, you may choose:
* V2Password or V3Password
* V2Token of V3Token
* V3OidcClientCredentials
* V3OidcPassword
* V3OidcAuthorizationCode
* V3OidcAccessToken
* V3TOTP
* V3TokenlessAuth
For more details about each one of those methods, please visit
`official documentation <https://docs.openstack.org/keystoneauth/latest/authentication-plugins.html>`_.
License
=======
(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.

View File

@ -1,90 +0,0 @@
# Copyright (c) 2014 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.
"""An example using monascaclient via the Python API"""
from monascaclient import client
import monascaclient.exc as exc
import time
# In order to use the python api directly, you must first obtain an
# auth token and identify which endpoint you wish to speak to.
endpoint = 'http://192.168.10.4:8070/v2.0'
# The api version of monasca-api
api_version = '2_0'
# Pass in the keystone authentication kwargs to construct a monasca client.
# The monasca_client will try to authenticate with keystone one time
# when it sees a 401 unauthorized resp, to take care of a stale token.
# In this example no token is input, so it will get a 401 when executing the
# first metrics.create request, and will authenticate and try again.
auth_kwargs = {'username': 'mini-mon',
'password': 'password',
'project_name': 'mini-mon',
'auth_url': 'http://192.168.10.5:35357/v3/'}
monasca_client = client.Client(api_version, endpoint, **auth_kwargs)
# you can reference the monascaclient.v2_0.shell.py
# do_commands for command field initialization.
# post a metric
dimensions = {'instance_id': '12345', 'service': 'nova'}
fields = {}
fields['name'] = 'metric1'
fields['dimensions'] = dimensions
# time in milliseconds
fields['timestamp'] = time.time() * 1000
fields['value'] = 222.333
try:
resp = monasca_client.metrics.create(**fields)
except exc.HTTPException as he:
print('HTTPException code=%s message=%s' % (he.code, he.message))
else:
print(resp)
print('Successfully created metric')
# post a metric with a unicode service name
dimensions = {'instance_id': '12345', 'service': u'\u76db\u5927'}
fields = {}
fields['name'] = 'metric1'
fields['dimensions'] = dimensions
fields['timestamp'] = time.time() * 1000
fields['value'] = 222.333
try:
resp = monasca_client.metrics.create(**fields)
except exc.HTTPException as he:
print('HTTPException code=%s message=%s' % (he.code, he.message))
else:
print(resp)
print('Successfully created metric')
print('Giving the DB time to update...')
time.sleep(5)
# metric-list
name = 'metric1'
dimensions = None
fields = {}
if name:
fields['name'] = name
if dimensions:
fields['dimensions'] = dimensions
try:
body = monasca_client.metrics.list(**fields)
except exc.HTTPException as he:
print('HTTPException code=%s message=%s' % (he.code, he.message))
else:
print(body)

View File

@ -1,136 +0,0 @@
#!/usr/bin/env python
#
# (C) Copyright 2016 Hewlett Packard Enterprise Development 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 getopt
import os
import sys
from monascaclient import client
def usage():
usage = """
Requires services.osrc variables in bash environment (OS_USERNAME etc).
check_monasca -d <dimension> -v <value>
-h --help Prints this
-d dimension Dimension to filter on
-v value Value of dimension
Examples
check_monasca -d hostname -v test-c0-m1-mgmt # Retrieve all alarms for a host
check_monasca -d service -v nova # Retrieve all nova alarms
"""
print(usage)
def get_keystone_creds():
creds = {'username': os.environ['OS_USERNAME'], 'password': os.environ['OS_PASSWORD'],
'auth_url': os.environ['OS_AUTH_URL'], 'project_name': os.environ['OS_PROJECT_NAME'],
'endpoint': os.environ['OS_MONASCA_URL'], 'os_cacert': os.environ['OS_CACERT']}
return creds
def format_alarm(alarm):
output = "%s %s ( Metric = %s)" % (
alarm['metrics'][0]['dimensions']['hostname'],
alarm['alarm_definition']['name'],
alarm['metrics'][0]['name'])
if "process." in alarm['metrics'][0]['name']:
output += "-%s," % (alarm['metrics'][0]['dimensions']['process_name'])
if "disk." in alarm['metrics'][0]['name']:
output += "-%s," % (alarm['metrics'][0]['dimensions']['mount_point'])
output += ","
return output
def main(argv):
# Initialise Variables
warns = 0
crits = 0
warns_output = ""
crits_output = ""
dimension = ""
dim_value = ""
# Test parameters
try:
opts, args = getopt.getopt(argv, "h::d:v:", ["dimension=", "value="])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit()
elif opt in ("-d", "--dimension"):
dimension = arg
elif opt in ("-v", "--value"):
dim_value = arg
if dimension == "" or dim_value == "":
usage()
sys.exit(2)
# Set the api version of monasca-api
api_version = '2_0'
creds = get_keystone_creds()
# Build request
dimensions = {}
dimensions[dimension] = dim_value
fields = {}
fields['metric_dimensions'] = dimensions
monasca_client = client.Client(api_version, **creds)
body = monasca_client.alarms.list(**fields)
# Process retrieved alarms
# Note Monasca has state and severity, these are mapped to Nagios values as
# State ALARM and severity = LOW or MEDIUM is Nagios Warning
# State = UNDERTERMINED is Nagios Warning
# State ALARM and severity = HIGH it Nagios Critical
for alarm in body:
if alarm['lifecycle_state'] != "RESOLVED":
if (alarm['state'] == "ALARM" and
(alarm['alarm_definition']['severity'] == "LOW" or
alarm['alarm_definition']['severity'] == "MEDIUM")):
warns += 1
warns_output += format_alarm(alarm)
if alarm['state'] == "UNDETERMINED":
warns += 1
warns_output += format_alarm(alarm)
if alarm['state'] == "ALARM" and alarm['alarm_definition']['severity'] == "HIGH":
crits += 1
crits_output += format_alarm(alarm)
if warns == 0 and crits == 0:
print("OK")
return
elif warns > 0 and crits == 0:
print(str(warns) + " WARNING - " + warns_output)
sys.exit(1)
elif crits > 0:
print(str(crits) + " CRITICAL - " + crits_output + str(warns) + " WARNING - " + warns_output)
sys.exit(2)
if __name__ == "__main__":
main(sys.argv[1:])

View File

@ -1,36 +0,0 @@
Nagios style monasca plugin
===========================
check_monasca.py is a Nagios style plugin to query a monasca endpoint based dimensions and values. It is best called via a wrapper script that will set the following environment variables.
OS_USERNAME - a keystone user
OS_PASSWORD - user password
OS_PROJECT_NAME - Default
OS_AUTH_URL - Keystone URL
OS_MONASCA_URL ( note monasca URL should be something like http://192.168.1.10:8070/v2.0 )
Then the script should be called with the relevant dimensions and values.
e.g
check_monasca.py -d service -v nova - for all nova alarms
check_monasca.py -d hostname -v server1 - for all alarms relating to server1.
License
-------
(C) Copyright 2014-2016 Hewlett Packard Enterprise Development 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.

View File

@ -1,120 +0,0 @@
#!/bin/bash
BASE_DIR=`dirname $0`
function usage {
echo "Usage: $0 [OPTION]..."
echo "Run monascaclient test suite(s)"
echo ""
echo " -V, --virtual-env Use virtualenv. Install automatically if not present."
echo " (Default is to run tests in local environment)"
echo " -F, --force Force a clean re-build of the virtual environment. Useful when dependencies have been added."
echo " -f, --func Functional tests have been removed."
echo " -u, --unit Run unit tests (default when nothing specified)"
echo " -p, --pep8 Run pep8 tests"
echo " --all Run pep8 and unit tests"
echo " -c, --coverage Generate coverage report"
echo " -d, --debug Run tests with testtools instead of testr. This allows you to use the debugger."
echo " -h, --help Print this usage message"
exit
}
# must not assign -a as an option, needed for selecting custom attributes
no_venv=1
function process_option {
case "$1" in
-V|--virtual-env) no_venv=0;;
-F|--force) force=1;;
-f|--func) test_func=1;;
-u|--unit) test_unit=1;;
-p|--pep8) test_pep8=1;;
--all) test_unit=1; test_pep8=1;;
-c|--coverage) coverage=1;;
-d|--debug) debug=1;;
-h|--help) usage;;
*) args="$args $1"; test_unit=1;;
esac
}
venv=.venv
with_venv=tools/with_venv.sh
wrapper=""
debug=0
function run_tests {
echo 'Running tests'
if [ $debug -eq 1 ]; then
echo "Debugging..."
if [ "$args" = "" ]; then
# Default to running all tests if specific test is not
# provided.
testrargs="discover ./monascaclient/tests"
fi
${wrapper} python -m testtools.run $args $testrargs
# Short circuit because all of the testr and coverage stuff
# below does not make sense when running testtools.run for
# debugging purposes.
return $?
fi
# Just run the test suites in current environment
if [ -n "$args" ] ; then
args="-t $args"
fi
${wrapper} python setup.py testr --slowest $args
}
function run_pep8 {
echo "Running flake8..."
bash -c "${wrapper} flake8"
}
# run unit tests with pep8 when no arguments are specified
# otherwise process CLI options
if [[ $# == 0 ]]; then
test_pep8=1
test_unit=1
else
for arg in "$@"; do
process_option $arg
done
fi
if [ "$no_venv" == 0 ]; then
# Remove the virtual environment if --force used
if [ "$force" == 1 ]; then
echo "Cleaning virtualenv..."
rm -rf ${venv}
fi
if [ -e ${venv} ]; then
wrapper="${with_venv}"
else
# Automatically install the virtualenv
python tools/install_venv.py
wrapper="${with_venv}"
fi
fi
result=0
# If functional or unit tests have been selected, run them
if [ "$test_unit" == 1 ] || [ "$debug" == 1 ] ; then
run_tests
result=$?
fi
# Run pep8 if it was selected
if [ "$test_pep8" == 1 ]; then
run_pep8
fi
# Generate coverage report
if [ "$coverage" == 1 ]; then
echo "Generating coverage report in ./cover"
${wrapper} python setup.py testr --coverage --slowest
${wrapper} python -m coverage report --show-missing
fi
exit $result

View File

@ -19,8 +19,6 @@ classifier =
[files]
packages = monascaclient
data_files =
share = tools/monasca.bash_completion
[entry_points]
console_scripts =

View File

@ -1,76 +0,0 @@
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2010 OpenStack Foundation
# Copyright 2013 IBM Corp.
# 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 os
import sys
import install_venv_common as install_venv # flake8: noqa
from six.moves import configparser as ConfigParser
def print_help(project, venv, root):
help = """
%(project)s development environment setup is complete.
%(project)s development uses virtualenv to track and manage Python
dependencies while in development and testing.
To activate the %(project)s virtualenv for the extent of your current
shell session you can run:
$ source %(venv)s/bin/activate
Or, if you prefer, you can run commands in the virtualenv on a case by
case basis by running:
$ %(root)s/tools/with_venv.sh <your command>
"""
print(help % dict(project=project, venv=venv, root=root))
def main(argv):
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if os.environ.get('tools_path'):
root = os.environ['tools_path']
venv = os.path.join(root, '.venv')
if os.environ.get('venv'):
venv = os.environ['venv']
pip_requires = os.path.join(root, 'requirements.txt')
test_requires = os.path.join(root, 'test-requirements.txt')
py_version = "python%s.%s" % (sys.version_info[0], sys.version_info[1])
setup_cfg = ConfigParser.ConfigParser()
setup_cfg.read('setup.cfg')
project = setup_cfg.get('metadata', 'name')
install = install_venv.InstallVenv(
root, venv, pip_requires, test_requires, py_version, project)
options = install.parse_args(argv)
install.check_python_version()
install.check_dependencies()
install.create_virtualenv(no_site_packages=options.no_site_packages)
install.install_dependencies()
#install.post_process()
print_help(project, venv, root)
if __name__ == '__main__':
main(sys.argv)

View File

@ -1,172 +0,0 @@
# Copyright 2013 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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.
"""Provides methods needed by installation script for OpenStack development
virtual environments.
Since this script is used to bootstrap a virtualenv from the system's Python
environment, it should be kept strictly compatible with Python 2.6.
Synced in from openstack-common
"""
from __future__ import print_function
import optparse
import os
import subprocess
import sys
class InstallVenv(object):
def __init__(self, root, venv, requirements,
test_requirements, py_version,
project):
self.root = root
self.venv = venv
self.requirements = requirements
self.test_requirements = test_requirements
self.py_version = py_version
self.project = project
def die(self, message, *args):
print(message % args, file=sys.stderr)
sys.exit(1)
def check_python_version(self):
if sys.version_info < (2, 6):
self.die("Need Python Version >= 2.6")
def run_command_with_code(self, cmd, redirect_output=True,
check_exit_code=True):
"""Runs a command in an out-of-process shell.
Returns the output of that command. Working directory is self.root.
"""
if redirect_output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout)
output = proc.communicate()[0]
if check_exit_code and proc.returncode != 0:
self.die('Command "%s" failed.\n%s', ' '.join(cmd), output)
return (output, proc.returncode)
def run_command(self, cmd, redirect_output=True, check_exit_code=True):
return self.run_command_with_code(cmd, redirect_output,
check_exit_code)[0]
def get_distro(self):
if (os.path.exists('/etc/fedora-release') or
os.path.exists('/etc/redhat-release')):
return Fedora(
self.root, self.venv, self.requirements,
self.test_requirements, self.py_version, self.project)
else:
return Distro(
self.root, self.venv, self.requirements,
self.test_requirements, self.py_version, self.project)
def check_dependencies(self):
self.get_distro().install_virtualenv()
def create_virtualenv(self, no_site_packages=True):
"""Creates the virtual environment and installs PIP.
Creates the virtual environment and installs PIP only into the
virtual environment.
"""
if not os.path.isdir(self.venv):
print('Creating venv...', end=' ')
if no_site_packages:
self.run_command(['virtualenv', '-q', '--no-site-packages',
self.venv])
else:
self.run_command(['virtualenv', '-q', self.venv])
print('done.')
else:
print("venv already exists...")
pass
def pip_install(self, *args):
self.run_command(['tools/with_venv.sh',
'pip', 'install', '--upgrade'] + list(args),
redirect_output=False)
def install_dependencies(self):
print('Installing dependencies with pip (this can take a while)...')
# First things first, make sure our venv has the latest pip and
# setuptools and pbr
self.pip_install('pip>=1.4')
self.pip_install('setuptools')
self.pip_install('pbr')
self.pip_install('-r', self.requirements, '-r', self.test_requirements)
def parse_args(self, argv):
"""Parses command-line arguments."""
parser = optparse.OptionParser()
parser.add_option('-n', '--no-site-packages',
action='store_true',
help="Do not inherit packages from global Python "
"install")
return parser.parse_args(argv[1:])[0]
class Distro(InstallVenv):
def check_cmd(self, cmd):
return bool(self.run_command(['which', cmd],
check_exit_code=False).strip())
def install_virtualenv(self):
if self.check_cmd('virtualenv'):
return
if self.check_cmd('easy_install'):
print('Installing virtualenv via easy_install...', end=' ')
if self.run_command(['easy_install', 'virtualenv']):
print('Succeeded')
return
else:
print('Failed')
self.die('ERROR: virtualenv not found.\n\n%s development'
' requires virtualenv, please install it using your'
' favorite package management tool' % self.project)
class Fedora(Distro):
"""This covers all Fedora-based distributions.
Includes: Fedora, RHEL, CentOS, Scientific Linux
"""
def check_pkg(self, pkg):
return self.run_command_with_code(['rpm', '-q', pkg],
check_exit_code=False)[1] == 0
def install_virtualenv(self):
if self.check_cmd('virtualenv'):
return
if not self.check_pkg('python-virtualenv'):
self.die("Please install 'python-virtualenv'.")
super(Fedora, self).install_virtualenv()

View File

@ -1,27 +0,0 @@
# bash completion for openstack monasca
_monasca_opts="" # lazy init
_monasca_flags="" # lazy init
_monasca_opts_exp="" # lazy init
_monasca()
{
local cur prev kbc
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
if [ "x$_monasca_opts" == "x" ] ; then
kbc="`monasca bash-completion | sed -e "s/ -h / /"`"
_monasca_opts="`echo "$kbc" | sed -e "s/--[a-z0-9_-]*//g" -e "s/[ ][ ]*/ /g"`"
_monasca_flags="`echo " $kbc" | sed -e "s/ [^-][^-][a-z0-9_-]*//g" -e "s/[ ][ ]*/ /g"`"
_monasca_opts_exp="`echo $_monasca_opts | sed -e "s/[ ]/|/g"`"
fi
if [[ " ${COMP_WORDS[@]} " =~ " "($_monasca_opts_exp)" " && "$prev" != "help" ]] ; then
COMPREPLY=($(compgen -W "${_monasca_flags}" -- ${cur}))
else
COMPREPLY=($(compgen -W "${_monasca_opts}" -- ${cur}))
fi
return 0
}
complete -o default -F _monasca monasca

View File

@ -1,30 +0,0 @@
#!/bin/bash
#
# Enforce the requirement that dependencies are listed in the input
# files in alphabetical order.
# FIXME(dhellmann): This doesn't deal with URL requirements very
# well. We should probably sort those on the egg-name, rather than the
# full line.
function check_file {
typeset f=$1
# We don't care about comment lines.
grep -v '^#' $f > ${f}.unsorted
sort -i -f ${f}.unsorted > ${f}.sorted
diff -c ${f}.unsorted ${f}.sorted
rc=$?
rm -f ${f}.sorted ${f}.unsorted
return $rc
}
exit_code=0
for filename in $@; do
check_file $filename
if [ $? -ne 0 ]; then
echo "Please list requirements in $filename in alphabetical order" 1>&2
exit_code=1
fi
done
exit $exit_code

View File

@ -1,10 +0,0 @@
#!/bin/bash
command -v tox > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo 'This script requires "tox" to run.'
echo 'You can install it with "pip install tox".'
exit 1;
fi
tox -evenv -- $@