Compare commits
101 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5217c987e3 | ||
|
|
345c0cbc36 | ||
|
|
d4e21b53c0 | ||
|
|
b1fe13ddd6 | ||
|
|
f21f04e937 | ||
|
|
4881aa259a | ||
|
|
733472aa51 | ||
|
|
15763e9343 | ||
|
|
dc459ba408 | ||
|
|
629cc47e88 | ||
|
|
5b8522b1f5 | ||
|
|
22665522da | ||
|
|
3a77770597 | ||
|
|
c94edfa3f2 | ||
|
|
01eab7d347 | ||
|
|
d1577ed830 | ||
|
|
3d7c7cd0b1 | ||
|
|
078f344adb | ||
|
|
dd463cce70 | ||
|
|
eeede3cc68 | ||
|
|
462284d817 | ||
|
|
6ec3904818 | ||
|
|
214ad23fbe | ||
|
|
fefecbcfe7 | ||
|
|
ecffc10b16 | ||
|
|
041cb460f9 | ||
|
|
6e40fea91e | ||
|
|
afa95cb8eb | ||
|
|
1db46a2283 | ||
|
|
c243de9232 | ||
|
|
89f1e4eac7 | ||
|
|
ced9795f05 | ||
|
|
e834eb86bf | ||
|
|
7340b04b80 | ||
|
|
339086ce64 | ||
|
|
3a469df201 | ||
|
|
3710127a5f | ||
|
|
faf5c656af | ||
|
|
fc425e741d | ||
|
|
74a382ecb6 | ||
|
|
59ef5ebda0 | ||
|
|
e273aa5b55 | ||
|
|
fae4ef7a03 | ||
|
|
f3ca2e6944 | ||
|
|
ac61ea3499 | ||
|
|
e689b3233e | ||
|
|
1f422f4c5c | ||
|
|
fda6cdfb7b | ||
|
|
448bb4468f | ||
|
|
ce263ecc9e | ||
|
|
d2d3a475e2 | ||
|
|
e0a2b0edcd | ||
|
|
49aae96f22 | ||
|
|
6113f97d2f | ||
|
|
b7ceed787e | ||
|
|
f18cf64f9d | ||
|
|
c0bddb93d5 | ||
|
|
25beeb0819 | ||
|
|
4c6a252b76 | ||
|
|
7c3ab24bf1 | ||
|
|
b304d5978d | ||
|
|
bfc9c63952 | ||
|
|
0fc2893234 | ||
|
|
51e14a5231 | ||
|
|
7e81c138ec | ||
|
|
d8da515092 | ||
|
|
271998a5e8 | ||
|
|
ef4f89da06 | ||
|
|
6b3ba9f4af | ||
|
|
44f20e3019 | ||
|
|
321b6f640a | ||
|
|
86b59bd334 | ||
|
|
c25f584fa0 | ||
|
|
2879e0df18 | ||
|
|
811a4f0ad0 | ||
|
|
9e8380d8d5 | ||
|
|
6d10a66474 | ||
|
|
6f30c77f41 | ||
|
|
368eaf9aed | ||
|
|
ea3e6e775a | ||
|
|
4599b87f1c | ||
|
|
a0a38d5e68 | ||
|
|
7b16de4908 | ||
|
|
9292e6fb2e | ||
|
|
25971fd867 | ||
|
|
0644b6e175 | ||
|
|
20139d066f | ||
|
|
4225036154 | ||
|
|
db20090283 | ||
|
|
537ce1ed60 | ||
|
|
18ae2eb061 | ||
|
|
34a9e75754 | ||
|
|
fb37a4ad52 | ||
|
|
17342e3d01 | ||
|
|
66c6ff898c | ||
|
|
a1f6310356 | ||
|
|
77df0bfe89 | ||
|
|
f70d2500ee | ||
|
|
923dd9b83b | ||
|
|
a54697d7bc | ||
|
|
b8cbc418e4 |
@@ -1,7 +1,7 @@
|
||||
[run]
|
||||
branch = True
|
||||
source = smaugclient
|
||||
omit = smaugclient/tests/*,smaug/openstack/*
|
||||
source = karborclient
|
||||
omit = karborclient/tests/*,karborclient/openstack/*
|
||||
|
||||
[report]
|
||||
ignore_errors = True
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
[gerrit]
|
||||
host=review.openstack.org
|
||||
port=29418
|
||||
project=openstack/python-smaugclient.git
|
||||
project=openstack/python-karborclient.git
|
||||
|
||||
@@ -14,4 +14,4 @@ Pull requests submitted through GitHub will be ignored.
|
||||
|
||||
Bugs should be filed on Launchpad, not GitHub:
|
||||
|
||||
https://launchpad.net/python-smaugclient
|
||||
https://launchpad.net/python-karborclient
|
||||
|
||||
51
README.rst
51
README.rst
@@ -1,16 +1,25 @@
|
||||
Smaug
|
||||
========================
|
||||
Team and repository tags
|
||||
========================
|
||||
|
||||
.. image:: http://governance.openstack.org/badges/python-karborclient.svg
|
||||
:target: http://governance.openstack.org/reference/tags/index.html
|
||||
|
||||
.. Change things from this point on
|
||||
|
||||
Karbor
|
||||
======
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/python-smaugclient.svg
|
||||
:target: https://pypi.python.org/pypi/python-smaugclient/
|
||||
.. image:: https://img.shields.io/pypi/v/python-karborclient.svg
|
||||
:target: https://pypi.python.org/pypi/python-karborclient/
|
||||
:alt: Latest Version
|
||||
|
||||
.. image:: https://img.shields.io/pypi/dm/python-smaugclient.svg
|
||||
:target: https://pypi.python.org/pypi/python-smaugclient/
|
||||
.. image:: https://img.shields.io/pypi/dm/python-karborclient.svg
|
||||
:target: https://pypi.python.org/pypi/python-karborclient/
|
||||
:alt: Downloads
|
||||
|
||||
|
||||
Smaug Mission Statement
|
||||
Karbor Mission Statement
|
||||
|
||||
* Formalize Application Data Protection in OpenStack (APIs, Services, Plugins, …)
|
||||
* Be able to protect Any Resource in OpenStack(as well as their dependencies)
|
||||
@@ -25,37 +34,39 @@ Smaug Mission Statement
|
||||
* `Specs`_
|
||||
* `How to Contribute`_
|
||||
|
||||
.. _PyPi: https://pypi.python.org/pypi/python-smaugclient
|
||||
.. _Launchpad project: https://launchpad.net/python-smaugclient
|
||||
.. _Blueprints: https://blueprints.launchpad.net/python-smaugclient
|
||||
.. _Bugs: https://bugs.launchpad.net/python-smaugclient
|
||||
.. _Source: https://git.openstack.org/cgit/openstack/python-smaugclient
|
||||
.. _PyPi: https://pypi.python.org/pypi/python-karborclient
|
||||
.. _Launchpad project: https://launchpad.net/python-karborclient
|
||||
.. _Blueprints: https://blueprints.launchpad.net/python-karborclient
|
||||
.. _Bugs: https://bugs.launchpad.net/python-karborclient
|
||||
.. _Source: https://git.openstack.org/cgit/openstack/python-karborclient
|
||||
.. _Specs: http://docs.openstack.org/developer/karbor/specs/index.html
|
||||
.. _How to Contribute: http://docs.openstack.org/infra/manual/developers.html
|
||||
|
||||
|
||||
Python Smaugclient
|
||||
Python Karborclient
|
||||
-------------------
|
||||
python-smaugclient is a client library for Smaug built on the Smaug API.
|
||||
It provides a Python API (the ``smaugclient`` module) and a command-line tool
|
||||
(``smaug``).
|
||||
python-karborclient is a client library for karbor built on the karbor API.
|
||||
It provides a Python API (the ``karborclient`` module) and a command-line tool
|
||||
(``karbor``).
|
||||
|
||||
Project Resources
|
||||
-----------------
|
||||
|
||||
Project status, bugs, and blueprints are tracked on Launchpad:
|
||||
|
||||
* Client bug tracker
|
||||
* https://launchpad.net/python-smaugclient
|
||||
* https://launchpad.net/python-karborclient
|
||||
|
||||
* Smaug bug tracker
|
||||
* https://launchpad.net/smaug
|
||||
* Karbor bug tracker
|
||||
* https://launchpad.net/karbor
|
||||
|
||||
Developer documentation can be found here:
|
||||
|
||||
http://docs.openstack.org/developer/smaug
|
||||
http://docs.openstack.org/developer/karbor
|
||||
|
||||
Additional resources are linked from the project wiki page:
|
||||
|
||||
https://wiki.openstack.org/wiki/Smaug
|
||||
https://wiki.openstack.org/wiki/karbor
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
@@ -37,7 +37,7 @@ source_suffix = '.rst'
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'python-smaugclient'
|
||||
project = u'python-karborclient'
|
||||
copyright = u'2013, OpenStack Foundation'
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Welcome to smaugclient's documentation!
|
||||
Welcome to karborclient's documentation!
|
||||
========================================================
|
||||
|
||||
Contents:
|
||||
|
||||
@@ -4,9 +4,9 @@ Installation
|
||||
|
||||
At the command line::
|
||||
|
||||
$ pip install python-smaugclient
|
||||
$ pip install python-karborclient
|
||||
|
||||
Or, if you have virtualenvwrapper installed::
|
||||
|
||||
$ mkvirtualenv python-smaugclient
|
||||
$ pip install python-smaugclient
|
||||
$ mkvirtualenv python-karborclient
|
||||
$ pip install python-karborclient
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
Usage
|
||||
========
|
||||
|
||||
To use smaugclient in a project::
|
||||
To use karborclient in a project::
|
||||
|
||||
import smaugclient
|
||||
import karborclient
|
||||
|
||||
@@ -16,4 +16,4 @@ import pbr.version
|
||||
|
||||
|
||||
__version__ = pbr.version.VersionInfo(
|
||||
'python-smaugclient').version_string()
|
||||
'python-karborclient').version_string()
|
||||
@@ -1,18 +1,20 @@
|
||||
# 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 smaugclient.common import utils
|
||||
|
||||
|
||||
def Client(version, *args, **kwargs):
|
||||
module = utils.import_versioned_module(version, 'client')
|
||||
client_class = getattr(module, 'Client')
|
||||
return client_class(*args, **kwargs)
|
||||
# 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 oslo_utils import importutils
|
||||
|
||||
|
||||
def Client(version, *args, **kwargs):
|
||||
module = importutils.import_versioned_module(
|
||||
'karborclient', version, 'client'
|
||||
)
|
||||
client_class = getattr(module, 'Client')
|
||||
return client_class(*args, **kwargs)
|
||||
@@ -1,221 +1,218 @@
|
||||
# Copyright 2013 OpenStack Foundation
|
||||
# Copyright 2013 Spanish National Research Council.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
# E0202: An attribute inherited from %s hide this method
|
||||
# pylint: disable=E0202
|
||||
|
||||
import abc
|
||||
import argparse
|
||||
import os
|
||||
|
||||
import six
|
||||
from stevedore import extension
|
||||
|
||||
from smaugclient.openstack.common.apiclient import exceptions
|
||||
|
||||
|
||||
_discovered_plugins = {}
|
||||
|
||||
|
||||
def discover_auth_systems():
|
||||
"""Discover the available auth-systems.
|
||||
|
||||
This won't take into account the old style auth-systems.
|
||||
"""
|
||||
global _discovered_plugins
|
||||
_discovered_plugins = {}
|
||||
|
||||
def add_plugin(ext):
|
||||
_discovered_plugins[ext.name] = ext.plugin
|
||||
|
||||
ep_namespace = "smaugclient.openstack.common.apiclient.auth"
|
||||
mgr = extension.ExtensionManager(ep_namespace)
|
||||
mgr.map(add_plugin)
|
||||
|
||||
|
||||
def load_auth_system_opts(parser):
|
||||
"""Load options needed by the available auth-systems into a parser.
|
||||
|
||||
This function will try to populate the parser with options from the
|
||||
available plugins.
|
||||
"""
|
||||
group = parser.add_argument_group("Common auth options")
|
||||
BaseAuthPlugin.add_common_opts(group)
|
||||
for name, auth_plugin in six.iteritems(_discovered_plugins):
|
||||
group = parser.add_argument_group(
|
||||
"Auth-system '%s' options" % name,
|
||||
conflict_handler="resolve")
|
||||
auth_plugin.add_opts(group)
|
||||
|
||||
|
||||
def load_plugin(auth_system):
|
||||
try:
|
||||
plugin_class = _discovered_plugins[auth_system]
|
||||
except KeyError:
|
||||
raise exceptions.AuthSystemNotFound(auth_system)
|
||||
return plugin_class(auth_system=auth_system)
|
||||
|
||||
|
||||
def load_plugin_from_args(args):
|
||||
"""Load required plugin and populate it with options.
|
||||
|
||||
Try to guess auth system if it is not specified. Systems are tried in
|
||||
alphabetical order.
|
||||
|
||||
:type args: argparse.Namespace
|
||||
:raises: AuthPluginOptionsMissing
|
||||
"""
|
||||
auth_system = args.os_auth_system
|
||||
if auth_system:
|
||||
plugin = load_plugin(auth_system)
|
||||
plugin.parse_opts(args)
|
||||
plugin.sufficient_options()
|
||||
return plugin
|
||||
|
||||
for plugin_auth_system in sorted(six.iterkeys(_discovered_plugins)):
|
||||
plugin_class = _discovered_plugins[plugin_auth_system]
|
||||
plugin = plugin_class()
|
||||
plugin.parse_opts(args)
|
||||
try:
|
||||
plugin.sufficient_options()
|
||||
except exceptions.AuthPluginOptionsMissing:
|
||||
continue
|
||||
return plugin
|
||||
raise exceptions.AuthPluginOptionsMissing(["auth_system"])
|
||||
|
||||
|
||||
@six.add_metaclass(abc.ABCMeta)
|
||||
class BaseAuthPlugin(object):
|
||||
"""Base class for authentication plugins.
|
||||
|
||||
An authentication plugin needs to override at least the authenticate
|
||||
method to be a valid plugin.
|
||||
"""
|
||||
|
||||
auth_system = None
|
||||
opt_names = []
|
||||
common_opt_names = [
|
||||
"auth_system",
|
||||
"username",
|
||||
"password",
|
||||
"tenant_name",
|
||||
"token",
|
||||
"auth_url",
|
||||
]
|
||||
|
||||
def __init__(self, auth_system=None, **kwargs):
|
||||
self.auth_system = auth_system or self.auth_system
|
||||
self.opts = dict((name, kwargs.get(name))
|
||||
for name in self.opt_names)
|
||||
|
||||
@staticmethod
|
||||
def _parser_add_opt(parser, opt):
|
||||
"""Add an option to parser in two variants.
|
||||
|
||||
:param opt: option name (with underscores)
|
||||
"""
|
||||
dashed_opt = opt.replace("_", "-")
|
||||
env_var = "OS_%s" % opt.upper()
|
||||
arg_default = os.environ.get(env_var, "")
|
||||
arg_help = "Defaults to env[%s]." % env_var
|
||||
parser.add_argument(
|
||||
"--os-%s" % dashed_opt,
|
||||
metavar="<%s>" % dashed_opt,
|
||||
default=arg_default,
|
||||
help=arg_help)
|
||||
parser.add_argument(
|
||||
"--os_%s" % opt,
|
||||
metavar="<%s>" % dashed_opt,
|
||||
help=argparse.SUPPRESS)
|
||||
|
||||
@classmethod
|
||||
def add_opts(cls, parser):
|
||||
"""Populate the parser with the options for this plugin.
|
||||
"""
|
||||
for opt in cls.opt_names:
|
||||
# use `BaseAuthPlugin.common_opt_names` since it is never
|
||||
# changed in child classes
|
||||
if opt not in BaseAuthPlugin.common_opt_names:
|
||||
cls._parser_add_opt(parser, opt)
|
||||
|
||||
@classmethod
|
||||
def add_common_opts(cls, parser):
|
||||
"""Add options that are common for several plugins.
|
||||
"""
|
||||
for opt in cls.common_opt_names:
|
||||
cls._parser_add_opt(parser, opt)
|
||||
|
||||
@staticmethod
|
||||
def get_opt(opt_name, args):
|
||||
"""Return option name and value.
|
||||
|
||||
:param opt_name: name of the option, e.g., "username"
|
||||
:param args: parsed arguments
|
||||
"""
|
||||
return (opt_name, getattr(args, "os_%s" % opt_name, None))
|
||||
|
||||
def parse_opts(self, args):
|
||||
"""Parse the actual auth-system options if any.
|
||||
|
||||
This method is expected to populate the attribute `self.opts` with a
|
||||
dict containing the options and values needed to make authentication.
|
||||
"""
|
||||
self.opts.update(dict(self.get_opt(opt_name, args)
|
||||
for opt_name in self.opt_names))
|
||||
|
||||
def authenticate(self, http_client):
|
||||
"""Authenticate using plugin defined method.
|
||||
|
||||
The method usually analyses `self.opts` and performs
|
||||
a request to authentication server.
|
||||
|
||||
:param http_client: client object that needs authentication
|
||||
:type http_client: HTTPClient
|
||||
:raises: AuthorizationFailure
|
||||
"""
|
||||
self.sufficient_options()
|
||||
self._do_authenticate(http_client)
|
||||
|
||||
@abc.abstractmethod
|
||||
def _do_authenticate(self, http_client):
|
||||
"""Protected method for authentication.
|
||||
"""
|
||||
|
||||
def sufficient_options(self):
|
||||
"""Check if all required options are present.
|
||||
|
||||
:raises: AuthPluginOptionsMissing
|
||||
"""
|
||||
missing = [opt
|
||||
for opt in self.opt_names
|
||||
if not self.opts.get(opt)]
|
||||
if missing:
|
||||
raise exceptions.AuthPluginOptionsMissing(missing)
|
||||
|
||||
@abc.abstractmethod
|
||||
def token_and_endpoint(self, endpoint_type, service_type):
|
||||
"""Return token and endpoint.
|
||||
|
||||
:param service_type: Service type of the endpoint
|
||||
:type service_type: string
|
||||
:param endpoint_type: Type of endpoint.
|
||||
Possible values: public or publicURL,
|
||||
internal or internalURL,
|
||||
admin or adminURL
|
||||
:type endpoint_type: string
|
||||
:returns: tuple of token and endpoint strings
|
||||
:raises: EndpointException
|
||||
"""
|
||||
# Copyright 2013 OpenStack Foundation
|
||||
# Copyright 2013 Spanish National Research Council.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
# E0202: An attribute inherited from %s hide this method
|
||||
# pylint: disable=E0202
|
||||
|
||||
import abc
|
||||
import argparse
|
||||
import os
|
||||
|
||||
import six
|
||||
from stevedore import extension
|
||||
|
||||
from karborclient.common.apiclient import exceptions
|
||||
|
||||
|
||||
_discovered_plugins = {}
|
||||
|
||||
|
||||
def discover_auth_systems():
|
||||
"""Discover the available auth-systems.
|
||||
|
||||
This won't take into account the old style auth-systems.
|
||||
"""
|
||||
global _discovered_plugins
|
||||
_discovered_plugins = {}
|
||||
|
||||
def add_plugin(ext):
|
||||
_discovered_plugins[ext.name] = ext.plugin
|
||||
|
||||
ep_namespace = "karborclient.common.apiclient.auth"
|
||||
mgr = extension.ExtensionManager(ep_namespace)
|
||||
mgr.map(add_plugin)
|
||||
|
||||
|
||||
def load_auth_system_opts(parser):
|
||||
"""Load options needed by the available auth-systems into a parser.
|
||||
|
||||
This function will try to populate the parser with options from the
|
||||
available plugins.
|
||||
"""
|
||||
group = parser.add_argument_group("Common auth options")
|
||||
BaseAuthPlugin.add_common_opts(group)
|
||||
for name, auth_plugin in six.iteritems(_discovered_plugins):
|
||||
group = parser.add_argument_group(
|
||||
"Auth-system '%s' options" % name,
|
||||
conflict_handler="resolve")
|
||||
auth_plugin.add_opts(group)
|
||||
|
||||
|
||||
def load_plugin(auth_system):
|
||||
try:
|
||||
plugin_class = _discovered_plugins[auth_system]
|
||||
except KeyError:
|
||||
raise exceptions.AuthSystemNotFound(auth_system)
|
||||
return plugin_class(auth_system=auth_system)
|
||||
|
||||
|
||||
def load_plugin_from_args(args):
|
||||
"""Load required plugin and populate it with options.
|
||||
|
||||
Try to guess auth system if it is not specified. Systems are tried in
|
||||
alphabetical order.
|
||||
|
||||
:type args: argparse.Namespace
|
||||
:raises: AuthPluginOptionsMissing
|
||||
"""
|
||||
auth_system = args.os_auth_system
|
||||
if auth_system:
|
||||
plugin = load_plugin(auth_system)
|
||||
plugin.parse_opts(args)
|
||||
plugin.sufficient_options()
|
||||
return plugin
|
||||
|
||||
for plugin_auth_system in sorted(six.iterkeys(_discovered_plugins)):
|
||||
plugin_class = _discovered_plugins[plugin_auth_system]
|
||||
plugin = plugin_class()
|
||||
plugin.parse_opts(args)
|
||||
try:
|
||||
plugin.sufficient_options()
|
||||
except exceptions.AuthPluginOptionsMissing:
|
||||
continue
|
||||
return plugin
|
||||
raise exceptions.AuthPluginOptionsMissing(["auth_system"])
|
||||
|
||||
|
||||
@six.add_metaclass(abc.ABCMeta)
|
||||
class BaseAuthPlugin(object):
|
||||
"""Base class for authentication plugins.
|
||||
|
||||
An authentication plugin needs to override at least the authenticate
|
||||
method to be a valid plugin.
|
||||
"""
|
||||
|
||||
auth_system = None
|
||||
opt_names = []
|
||||
common_opt_names = [
|
||||
"auth_system",
|
||||
"username",
|
||||
"password",
|
||||
"tenant_name",
|
||||
"token",
|
||||
"auth_url",
|
||||
]
|
||||
|
||||
def __init__(self, auth_system=None, **kwargs):
|
||||
self.auth_system = auth_system or self.auth_system
|
||||
self.opts = dict((name, kwargs.get(name))
|
||||
for name in self.opt_names)
|
||||
|
||||
@staticmethod
|
||||
def _parser_add_opt(parser, opt):
|
||||
"""Add an option to parser in two variants.
|
||||
|
||||
:param opt: option name (with underscores)
|
||||
"""
|
||||
dashed_opt = opt.replace("_", "-")
|
||||
env_var = "OS_%s" % opt.upper()
|
||||
arg_default = os.environ.get(env_var, "")
|
||||
arg_help = "Defaults to env[%s]." % env_var
|
||||
parser.add_argument(
|
||||
"--os-%s" % dashed_opt,
|
||||
metavar="<%s>" % dashed_opt,
|
||||
default=arg_default,
|
||||
help=arg_help)
|
||||
parser.add_argument(
|
||||
"--os_%s" % opt,
|
||||
metavar="<%s>" % dashed_opt,
|
||||
help=argparse.SUPPRESS)
|
||||
|
||||
@classmethod
|
||||
def add_opts(cls, parser):
|
||||
"""Populate the parser with the options for this plugin."""
|
||||
for opt in cls.opt_names:
|
||||
# use `BaseAuthPlugin.common_opt_names` since it is never
|
||||
# changed in child classes
|
||||
if opt not in BaseAuthPlugin.common_opt_names:
|
||||
cls._parser_add_opt(parser, opt)
|
||||
|
||||
@classmethod
|
||||
def add_common_opts(cls, parser):
|
||||
"""Add options that are common for several plugins."""
|
||||
for opt in cls.common_opt_names:
|
||||
cls._parser_add_opt(parser, opt)
|
||||
|
||||
@staticmethod
|
||||
def get_opt(opt_name, args):
|
||||
"""Return option name and value.
|
||||
|
||||
:param opt_name: name of the option, e.g., "username"
|
||||
:param args: parsed arguments
|
||||
"""
|
||||
return (opt_name, getattr(args, "os_%s" % opt_name, None))
|
||||
|
||||
def parse_opts(self, args):
|
||||
"""Parse the actual auth-system options if any.
|
||||
|
||||
This method is expected to populate the attribute `self.opts` with a
|
||||
dict containing the options and values needed to make authentication.
|
||||
"""
|
||||
self.opts.update(dict(self.get_opt(opt_name, args)
|
||||
for opt_name in self.opt_names))
|
||||
|
||||
def authenticate(self, http_client):
|
||||
"""Authenticate using plugin defined method.
|
||||
|
||||
The method usually analyses `self.opts` and performs
|
||||
a request to authentication server.
|
||||
|
||||
:param http_client: client object that needs authentication
|
||||
:type http_client: HTTPClient
|
||||
:raises: AuthorizationFailure
|
||||
"""
|
||||
self.sufficient_options()
|
||||
self._do_authenticate(http_client)
|
||||
|
||||
@abc.abstractmethod
|
||||
def _do_authenticate(self, http_client):
|
||||
"""Protected method for authentication."""
|
||||
|
||||
def sufficient_options(self):
|
||||
"""Check if all required options are present.
|
||||
|
||||
:raises: AuthPluginOptionsMissing
|
||||
"""
|
||||
missing = [opt
|
||||
for opt in self.opt_names
|
||||
if not self.opts.get(opt)]
|
||||
if missing:
|
||||
raise exceptions.AuthPluginOptionsMissing(missing)
|
||||
|
||||
@abc.abstractmethod
|
||||
def token_and_endpoint(self, endpoint_type, service_type):
|
||||
"""Return token and endpoint.
|
||||
|
||||
:param service_type: Service type of the endpoint
|
||||
:type service_type: string
|
||||
:param endpoint_type: Type of endpoint.
|
||||
Possible values: public or publicURL,
|
||||
internal or internalURL,
|
||||
admin or adminURL
|
||||
:type endpoint_type: string
|
||||
:returns: tuple of token and endpoint strings
|
||||
:raises: EndpointException
|
||||
"""
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,365 +1,363 @@
|
||||
# Copyright 2010 Jacob Kaplan-Moss
|
||||
# Copyright 2011 OpenStack Foundation
|
||||
# Copyright 2011 Piston Cloud Computing, Inc.
|
||||
# Copyright 2013 Alessio Ababilov
|
||||
# Copyright 2013 Grid Dynamics
|
||||
# Copyright 2013 OpenStack Foundation
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
OpenStack Client interface. Handles the REST calls and responses.
|
||||
"""
|
||||
|
||||
# E0202: An attribute inherited from %s hide this method
|
||||
# pylint: disable=E0202
|
||||
|
||||
try:
|
||||
import simplejson as json
|
||||
except ImportError:
|
||||
import json
|
||||
|
||||
import time
|
||||
|
||||
from oslo_log import log as logging
|
||||
from oslo_utils import importutils
|
||||
import requests
|
||||
|
||||
from smaugclient.i18n import _
|
||||
from smaugclient.openstack.common.apiclient import exceptions
|
||||
|
||||
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HTTPClient(object):
|
||||
"""This client handles sending HTTP requests to OpenStack servers.
|
||||
|
||||
Features:
|
||||
|
||||
- share authentication information between several clients to different
|
||||
services (e.g., for compute and image clients);
|
||||
- reissue authentication request for expired tokens;
|
||||
- encode/decode JSON bodies;
|
||||
- raise exceptions on HTTP errors;
|
||||
- pluggable authentication;
|
||||
- store authentication information in a keyring;
|
||||
- store time spent for requests;
|
||||
- register clients for particular services, so one can use
|
||||
`http_client.identity` or `http_client.compute`;
|
||||
- log requests and responses in a format that is easy to copy-and-paste
|
||||
into terminal and send the same request with curl.
|
||||
"""
|
||||
|
||||
user_agent = "smaugclient.openstack.common.apiclient"
|
||||
|
||||
def __init__(self,
|
||||
auth_plugin,
|
||||
region_name=None,
|
||||
endpoint_type="publicURL",
|
||||
original_ip=None,
|
||||
verify=True,
|
||||
cert=None,
|
||||
timeout=None,
|
||||
timings=False,
|
||||
keyring_saver=None,
|
||||
debug=False,
|
||||
user_agent=None,
|
||||
http=None):
|
||||
self.auth_plugin = auth_plugin
|
||||
|
||||
self.endpoint_type = endpoint_type
|
||||
self.region_name = region_name
|
||||
|
||||
self.original_ip = original_ip
|
||||
self.timeout = timeout
|
||||
self.verify = verify
|
||||
self.cert = cert
|
||||
|
||||
self.keyring_saver = keyring_saver
|
||||
self.debug = debug
|
||||
self.user_agent = user_agent or self.user_agent
|
||||
|
||||
self.times = [] # [("item", starttime, endtime), ...]
|
||||
self.timings = timings
|
||||
|
||||
# requests within the same session can reuse TCP connections from pool
|
||||
self.http = http or requests.Session()
|
||||
|
||||
self.cached_token = None
|
||||
|
||||
def _http_log_req(self, method, url, kwargs):
|
||||
if not self.debug:
|
||||
return
|
||||
|
||||
string_parts = [
|
||||
"curl -i",
|
||||
"-X '%s'" % method,
|
||||
"'%s'" % url,
|
||||
]
|
||||
|
||||
for element in kwargs['headers']:
|
||||
header = "-H '%s: %s'" % (element, kwargs['headers'][element])
|
||||
string_parts.append(header)
|
||||
|
||||
_logger.debug("REQ: %s" % " ".join(string_parts))
|
||||
if 'data' in kwargs:
|
||||
_logger.debug("REQ BODY: %s\n" % (kwargs['data']))
|
||||
|
||||
def _http_log_resp(self, resp):
|
||||
if not self.debug:
|
||||
return
|
||||
_logger.debug(
|
||||
"RESP: [%s] %s\n",
|
||||
resp.status_code,
|
||||
resp.headers)
|
||||
if resp._content_consumed:
|
||||
_logger.debug(
|
||||
"RESP BODY: %s\n",
|
||||
resp.text)
|
||||
|
||||
def serialize(self, kwargs):
|
||||
if kwargs.get('json') is not None:
|
||||
kwargs['headers']['Content-Type'] = 'application/json'
|
||||
kwargs['data'] = json.dumps(kwargs['json'])
|
||||
try:
|
||||
del kwargs['json']
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
def get_timings(self):
|
||||
return self.times
|
||||
|
||||
def reset_timings(self):
|
||||
self.times = []
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
"""Send an http request with the specified characteristics.
|
||||
|
||||
Wrapper around `requests.Session.request` to handle tasks such as
|
||||
setting headers, JSON encoding/decoding, and error handling.
|
||||
|
||||
:param method: method of HTTP request
|
||||
:param url: URL of HTTP request
|
||||
:param kwargs: any other parameter that can be passed to
|
||||
requests.Session.request (such as `headers`) or `json`
|
||||
that will be encoded as JSON and used as `data` argument
|
||||
"""
|
||||
kwargs.setdefault("headers", kwargs.get("headers", {}))
|
||||
kwargs["headers"]["User-Agent"] = self.user_agent
|
||||
if self.original_ip:
|
||||
kwargs["headers"]["Forwarded"] = "for=%s;by=%s" % (
|
||||
self.original_ip, self.user_agent)
|
||||
if self.timeout is not None:
|
||||
kwargs.setdefault("timeout", self.timeout)
|
||||
kwargs.setdefault("verify", self.verify)
|
||||
if self.cert is not None:
|
||||
kwargs.setdefault("cert", self.cert)
|
||||
self.serialize(kwargs)
|
||||
|
||||
self._http_log_req(method, url, kwargs)
|
||||
if self.timings:
|
||||
start_time = time.time()
|
||||
resp = self.http.request(method, url, **kwargs)
|
||||
if self.timings:
|
||||
self.times.append(("%s %s" % (method, url),
|
||||
start_time, time.time()))
|
||||
self._http_log_resp(resp)
|
||||
|
||||
if resp.status_code >= 400:
|
||||
_logger.debug(
|
||||
"Request returned failure status: %s",
|
||||
resp.status_code)
|
||||
raise exceptions.from_response(resp, method, url)
|
||||
|
||||
return resp
|
||||
|
||||
@staticmethod
|
||||
def concat_url(endpoint, url):
|
||||
"""Concatenate endpoint and final URL.
|
||||
|
||||
E.g., "http://keystone/v2.0/" and "/tokens" are concatenated to
|
||||
"http://keystone/v2.0/tokens".
|
||||
|
||||
:param endpoint: the base URL
|
||||
:param url: the final URL
|
||||
"""
|
||||
return "%s/%s" % (endpoint.rstrip("/"), url.strip("/"))
|
||||
|
||||
def client_request(self, client, method, url, **kwargs):
|
||||
"""Send an http request using `client`'s endpoint and specified `url`.
|
||||
|
||||
If request was rejected as unauthorized (possibly because the token is
|
||||
expired), issue one authorization attempt and send the request once
|
||||
again.
|
||||
|
||||
:param client: instance of BaseClient descendant
|
||||
:param method: method of HTTP request
|
||||
:param url: URL of HTTP request
|
||||
:param kwargs: any other parameter that can be passed to
|
||||
`HTTPClient.request`
|
||||
"""
|
||||
|
||||
filter_args = {
|
||||
"endpoint_type": client.endpoint_type or self.endpoint_type,
|
||||
"service_type": client.service_type,
|
||||
}
|
||||
token, endpoint = (self.cached_token, client.cached_endpoint)
|
||||
just_authenticated = False
|
||||
if not (token and endpoint):
|
||||
try:
|
||||
token, endpoint = self.auth_plugin.token_and_endpoint(
|
||||
**filter_args)
|
||||
except exceptions.EndpointException:
|
||||
pass
|
||||
if not (token and endpoint):
|
||||
self.authenticate()
|
||||
just_authenticated = True
|
||||
token, endpoint = self.auth_plugin.token_and_endpoint(
|
||||
**filter_args)
|
||||
if not (token and endpoint):
|
||||
raise exceptions.AuthorizationFailure(
|
||||
_("Cannot find endpoint or token for request"))
|
||||
|
||||
old_token_endpoint = (token, endpoint)
|
||||
kwargs.setdefault("headers", {})["X-Auth-Token"] = token
|
||||
self.cached_token = token
|
||||
client.cached_endpoint = endpoint
|
||||
# Perform the request once. If we get Unauthorized, then it
|
||||
# might be because the auth token expired, so try to
|
||||
# re-authenticate and try again. If it still fails, bail.
|
||||
try:
|
||||
return self.request(
|
||||
method, self.concat_url(endpoint, url), **kwargs)
|
||||
except exceptions.Unauthorized as unauth_ex:
|
||||
if just_authenticated:
|
||||
raise
|
||||
self.cached_token = None
|
||||
client.cached_endpoint = None
|
||||
self.authenticate()
|
||||
try:
|
||||
token, endpoint = self.auth_plugin.token_and_endpoint(
|
||||
**filter_args)
|
||||
except exceptions.EndpointException:
|
||||
raise unauth_ex
|
||||
if (not (token and endpoint) or
|
||||
old_token_endpoint == (token, endpoint)):
|
||||
raise unauth_ex
|
||||
self.cached_token = token
|
||||
client.cached_endpoint = endpoint
|
||||
kwargs["headers"]["X-Auth-Token"] = token
|
||||
return self.request(
|
||||
method, self.concat_url(endpoint, url), **kwargs)
|
||||
|
||||
def add_client(self, base_client_instance):
|
||||
"""Add a new instance of :class:`BaseClient` descendant.
|
||||
|
||||
`self` will store a reference to `base_client_instance`.
|
||||
|
||||
Example:
|
||||
|
||||
>>> def test_clients():
|
||||
... from keystoneclient.auth import keystone
|
||||
... from openstack.common.apiclient import client
|
||||
... auth = keystone.KeystoneAuthPlugin(
|
||||
... username="user", password="pass", tenant_name="tenant",
|
||||
... auth_url="http://auth:5000/v2.0")
|
||||
... openstack_client = client.HTTPClient(auth)
|
||||
... # create nova client
|
||||
... from novaclient.v1_1 import client
|
||||
... client.Client(openstack_client)
|
||||
... # create keystone client
|
||||
... from keystoneclient.v2_0 import client
|
||||
... client.Client(openstack_client)
|
||||
... # use them
|
||||
... openstack_client.identity.tenants.list()
|
||||
... openstack_client.compute.servers.list()
|
||||
"""
|
||||
service_type = base_client_instance.service_type
|
||||
if service_type and not hasattr(self, service_type):
|
||||
setattr(self, service_type, base_client_instance)
|
||||
|
||||
def authenticate(self):
|
||||
self.auth_plugin.authenticate(self)
|
||||
# Store the authentication results in the keyring for later requests
|
||||
if self.keyring_saver:
|
||||
self.keyring_saver.save(self)
|
||||
|
||||
|
||||
class BaseClient(object):
|
||||
"""Top-level object to access the OpenStack API.
|
||||
|
||||
This client uses :class:`HTTPClient` to send requests. :class:`HTTPClient`
|
||||
will handle a bunch of issues such as authentication.
|
||||
"""
|
||||
|
||||
service_type = None
|
||||
endpoint_type = None # "publicURL" will be used
|
||||
cached_endpoint = None
|
||||
|
||||
def __init__(self, http_client, extensions=None):
|
||||
self.http_client = http_client
|
||||
http_client.add_client(self)
|
||||
|
||||
# Add in any extensions...
|
||||
if extensions:
|
||||
for extension in extensions:
|
||||
if extension.manager_class:
|
||||
setattr(self, extension.name,
|
||||
extension.manager_class(self))
|
||||
|
||||
def client_request(self, method, url, **kwargs):
|
||||
return self.http_client.client_request(
|
||||
self, method, url, **kwargs)
|
||||
|
||||
def head(self, url, **kwargs):
|
||||
return self.client_request("HEAD", url, **kwargs)
|
||||
|
||||
def get(self, url, **kwargs):
|
||||
return self.client_request("GET", url, **kwargs)
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
return self.client_request("POST", url, **kwargs)
|
||||
|
||||
def put(self, url, **kwargs):
|
||||
return self.client_request("PUT", url, **kwargs)
|
||||
|
||||
def delete(self, url, **kwargs):
|
||||
return self.client_request("DELETE", url, **kwargs)
|
||||
|
||||
def patch(self, url, **kwargs):
|
||||
return self.client_request("PATCH", url, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def get_class(api_name, version, version_map):
|
||||
"""Returns the client class for the requested API version
|
||||
|
||||
:param api_name: the name of the API, e.g. 'compute', 'image', etc
|
||||
:param version: the requested API version
|
||||
:param version_map: a dict of client classes keyed by version
|
||||
:rtype: a client class for the requested API version
|
||||
"""
|
||||
try:
|
||||
client_path = version_map[str(version)]
|
||||
except (KeyError, ValueError):
|
||||
msg = _("Invalid %(api_name)s client version '%(version)s'. "
|
||||
"Must be one of: %(version_map)s") % {
|
||||
'api_name': api_name,
|
||||
'version': version,
|
||||
'version_map': ', '.join(version_map.keys())
|
||||
}
|
||||
raise exceptions.UnsupportedVersion(msg)
|
||||
|
||||
return importutils.import_class(client_path)
|
||||
# Copyright 2010 Jacob Kaplan-Moss
|
||||
# Copyright 2011 OpenStack Foundation
|
||||
# Copyright 2011 Piston Cloud Computing, Inc.
|
||||
# Copyright 2013 Alessio Ababilov
|
||||
# Copyright 2013 Grid Dynamics
|
||||
# Copyright 2013 OpenStack Foundation
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
OpenStack Client interface. Handles the REST calls and responses.
|
||||
"""
|
||||
|
||||
# E0202: An attribute inherited from %s hide this method
|
||||
# pylint: disable=E0202
|
||||
|
||||
try:
|
||||
import simplejson as json
|
||||
except ImportError:
|
||||
import json
|
||||
|
||||
import time
|
||||
|
||||
from oslo_log import log as logging
|
||||
from oslo_utils import importutils
|
||||
import requests
|
||||
|
||||
from karborclient.i18n import _
|
||||
from karborclient.openstack.common.apiclient import exceptions
|
||||
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HTTPClient(object):
|
||||
"""This client handles sending HTTP requests to OpenStack servers.
|
||||
|
||||
Features:
|
||||
|
||||
- share authentication information between several clients to different
|
||||
services (e.g., for compute and image clients);
|
||||
- reissue authentication request for expired tokens;
|
||||
- encode/decode JSON bodies;
|
||||
- raise exceptions on HTTP errors;
|
||||
- pluggable authentication;
|
||||
- store authentication information in a keyring;
|
||||
- store time spent for requests;
|
||||
- register clients for particular services, so one can use
|
||||
`http_client.identity` or `http_client.compute`;
|
||||
- log requests and responses in a format that is easy to copy-and-paste
|
||||
into terminal and send the same request with curl.
|
||||
"""
|
||||
|
||||
user_agent = "karborclient.common.apiclient"
|
||||
|
||||
def __init__(self,
|
||||
auth_plugin,
|
||||
region_name=None,
|
||||
endpoint_type="publicURL",
|
||||
original_ip=None,
|
||||
verify=True,
|
||||
cert=None,
|
||||
timeout=None,
|
||||
timings=False,
|
||||
keyring_saver=None,
|
||||
debug=False,
|
||||
user_agent=None,
|
||||
http=None):
|
||||
self.auth_plugin = auth_plugin
|
||||
|
||||
self.endpoint_type = endpoint_type
|
||||
self.region_name = region_name
|
||||
|
||||
self.original_ip = original_ip
|
||||
self.timeout = timeout
|
||||
self.verify = verify
|
||||
self.cert = cert
|
||||
|
||||
self.keyring_saver = keyring_saver
|
||||
self.debug = debug
|
||||
self.user_agent = user_agent or self.user_agent
|
||||
|
||||
self.times = [] # [("item", starttime, endtime), ...]
|
||||
self.timings = timings
|
||||
|
||||
# requests within the same session can reuse TCP connections from pool
|
||||
self.http = http or requests.Session()
|
||||
|
||||
self.cached_token = None
|
||||
|
||||
def _http_log_req(self, method, url, kwargs):
|
||||
if not self.debug:
|
||||
return
|
||||
|
||||
string_parts = [
|
||||
"curl -i",
|
||||
"-X '%s'" % method,
|
||||
"'%s'" % url,
|
||||
]
|
||||
|
||||
for element in kwargs['headers']:
|
||||
header = "-H '%s: %s'" % (element, kwargs['headers'][element])
|
||||
string_parts.append(header)
|
||||
|
||||
_logger.debug("REQ: %s" % " ".join(string_parts))
|
||||
if 'data' in kwargs:
|
||||
_logger.debug("REQ BODY: %s\n" % (kwargs['data']))
|
||||
|
||||
def _http_log_resp(self, resp):
|
||||
if not self.debug:
|
||||
return
|
||||
_logger.debug(
|
||||
"RESP: [%s] %s\n",
|
||||
resp.status_code,
|
||||
resp.headers)
|
||||
if resp._content_consumed:
|
||||
_logger.debug(
|
||||
"RESP BODY: %s\n",
|
||||
resp.text)
|
||||
|
||||
def serialize(self, kwargs):
|
||||
if kwargs.get('json') is not None:
|
||||
kwargs['headers']['Content-Type'] = 'application/json'
|
||||
kwargs['data'] = json.dumps(kwargs['json'])
|
||||
try:
|
||||
del kwargs['json']
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
def get_timings(self):
|
||||
return self.times
|
||||
|
||||
def reset_timings(self):
|
||||
self.times = []
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
"""Send an http request with the specified characteristics.
|
||||
|
||||
Wrapper around `requests.Session.request` to handle tasks such as
|
||||
setting headers, JSON encoding/decoding, and error handling.
|
||||
|
||||
:param method: method of HTTP request
|
||||
:param url: URL of HTTP request
|
||||
:param kwargs: any other parameter that can be passed to
|
||||
requests.Session.request (such as `headers`) or `json`
|
||||
that will be encoded as JSON and used as `data` argument
|
||||
"""
|
||||
kwargs.setdefault("headers", kwargs.get("headers", {}))
|
||||
kwargs["headers"]["User-Agent"] = self.user_agent
|
||||
if self.original_ip:
|
||||
kwargs["headers"]["Forwarded"] = "for=%s;by=%s" % (
|
||||
self.original_ip, self.user_agent)
|
||||
if self.timeout is not None:
|
||||
kwargs.setdefault("timeout", self.timeout)
|
||||
kwargs.setdefault("verify", self.verify)
|
||||
if self.cert is not None:
|
||||
kwargs.setdefault("cert", self.cert)
|
||||
self.serialize(kwargs)
|
||||
|
||||
self._http_log_req(method, url, kwargs)
|
||||
if self.timings:
|
||||
start_time = time.time()
|
||||
resp = self.http.request(method, url, **kwargs)
|
||||
if self.timings:
|
||||
self.times.append(("%s %s" % (method, url),
|
||||
start_time, time.time()))
|
||||
self._http_log_resp(resp)
|
||||
|
||||
if resp.status_code >= 400:
|
||||
_logger.debug(
|
||||
"Request returned failure status: %s",
|
||||
resp.status_code)
|
||||
raise exceptions.from_response(resp, method, url)
|
||||
|
||||
return resp
|
||||
|
||||
@staticmethod
|
||||
def concat_url(endpoint, url):
|
||||
"""Concatenate endpoint and final URL.
|
||||
|
||||
E.g., "http://keystone/v2.0/" and "/tokens" are concatenated to
|
||||
"http://keystone/v2.0/tokens".
|
||||
|
||||
:param endpoint: the base URL
|
||||
:param url: the final URL
|
||||
"""
|
||||
return "%s/%s" % (endpoint.rstrip("/"), url.strip("/"))
|
||||
|
||||
def client_request(self, client, method, url, **kwargs):
|
||||
"""Send an http request using `client`'s endpoint and specified `url`.
|
||||
|
||||
If request was rejected as unauthorized (possibly because the token is
|
||||
expired), issue one authorization attempt and send the request once
|
||||
again.
|
||||
|
||||
:param client: instance of BaseClient descendant
|
||||
:param method: method of HTTP request
|
||||
:param url: URL of HTTP request
|
||||
:param kwargs: any other parameter that can be passed to
|
||||
`HTTPClient.request`
|
||||
"""
|
||||
|
||||
filter_args = {
|
||||
"endpoint_type": client.endpoint_type or self.endpoint_type,
|
||||
"service_type": client.service_type,
|
||||
}
|
||||
token, endpoint = (self.cached_token, client.cached_endpoint)
|
||||
just_authenticated = False
|
||||
if not (token and endpoint):
|
||||
try:
|
||||
token, endpoint = self.auth_plugin.token_and_endpoint(
|
||||
**filter_args)
|
||||
except exceptions.EndpointException:
|
||||
pass
|
||||
if not (token and endpoint):
|
||||
self.authenticate()
|
||||
just_authenticated = True
|
||||
token, endpoint = self.auth_plugin.token_and_endpoint(
|
||||
**filter_args)
|
||||
if not (token and endpoint):
|
||||
raise exceptions.AuthorizationFailure(
|
||||
_("Cannot find endpoint or token for request"))
|
||||
|
||||
old_token_endpoint = (token, endpoint)
|
||||
kwargs.setdefault("headers", {})["X-Auth-Token"] = token
|
||||
self.cached_token = token
|
||||
client.cached_endpoint = endpoint
|
||||
# Perform the request once. If we get Unauthorized, then it
|
||||
# might be because the auth token expired, so try to
|
||||
# re-authenticate and try again. If it still fails, bail.
|
||||
try:
|
||||
return self.request(
|
||||
method, self.concat_url(endpoint, url), **kwargs)
|
||||
except exceptions.Unauthorized as unauth_ex:
|
||||
if just_authenticated:
|
||||
raise
|
||||
self.cached_token = None
|
||||
client.cached_endpoint = None
|
||||
self.authenticate()
|
||||
try:
|
||||
token, endpoint = self.auth_plugin.token_and_endpoint(
|
||||
**filter_args)
|
||||
except exceptions.EndpointException:
|
||||
raise unauth_ex
|
||||
if (not (token and endpoint) or
|
||||
old_token_endpoint == (token, endpoint)):
|
||||
raise unauth_ex
|
||||
self.cached_token = token
|
||||
client.cached_endpoint = endpoint
|
||||
kwargs["headers"]["X-Auth-Token"] = token
|
||||
return self.request(
|
||||
method, self.concat_url(endpoint, url), **kwargs)
|
||||
|
||||
def add_client(self, base_client_instance):
|
||||
"""Add a new instance of :class:`BaseClient` descendant.
|
||||
|
||||
`self` will store a reference to `base_client_instance`.
|
||||
|
||||
Example:
|
||||
|
||||
>>> def test_clients():
|
||||
... from keystoneclient.auth import keystone
|
||||
... from karborclient.common.apiclient import client
|
||||
... auth = keystone.KeystoneAuthPlugin(
|
||||
... username="user", password="pass", tenant_name="tenant",
|
||||
... auth_url="http://auth:5000/v2.0")
|
||||
... openstack_client = client.HTTPClient(auth)
|
||||
... # create nova client
|
||||
... from novaclient.v1_1 import client
|
||||
... client.Client(openstack_client)
|
||||
... # create keystone client
|
||||
... from keystoneclient.v2_0 import client
|
||||
... client.Client(openstack_client)
|
||||
... # use them
|
||||
... openstack_client.identity.tenants.list()
|
||||
... openstack_client.compute.servers.list()
|
||||
"""
|
||||
service_type = base_client_instance.service_type
|
||||
if service_type and not hasattr(self, service_type):
|
||||
setattr(self, service_type, base_client_instance)
|
||||
|
||||
def authenticate(self):
|
||||
self.auth_plugin.authenticate(self)
|
||||
# Store the authentication results in the keyring for later requests
|
||||
if self.keyring_saver:
|
||||
self.keyring_saver.save(self)
|
||||
|
||||
|
||||
class BaseClient(object):
|
||||
"""Top-level object to access the OpenStack API.
|
||||
|
||||
This client uses :class:`HTTPClient` to send requests. :class:`HTTPClient`
|
||||
will handle a bunch of issues such as authentication.
|
||||
"""
|
||||
|
||||
service_type = None
|
||||
endpoint_type = None # "publicURL" will be used
|
||||
cached_endpoint = None
|
||||
|
||||
def __init__(self, http_client, extensions=None):
|
||||
self.http_client = http_client
|
||||
http_client.add_client(self)
|
||||
|
||||
# Add in any extensions...
|
||||
if extensions:
|
||||
for extension in extensions:
|
||||
if extension.manager_class:
|
||||
setattr(self, extension.name,
|
||||
extension.manager_class(self))
|
||||
|
||||
def client_request(self, method, url, **kwargs):
|
||||
return self.http_client.client_request(
|
||||
self, method, url, **kwargs)
|
||||
|
||||
def head(self, url, **kwargs):
|
||||
return self.client_request("HEAD", url, **kwargs)
|
||||
|
||||
def get(self, url, **kwargs):
|
||||
return self.client_request("GET", url, **kwargs)
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
return self.client_request("POST", url, **kwargs)
|
||||
|
||||
def put(self, url, **kwargs):
|
||||
return self.client_request("PUT", url, **kwargs)
|
||||
|
||||
def delete(self, url, **kwargs):
|
||||
return self.client_request("DELETE", url, **kwargs)
|
||||
|
||||
def patch(self, url, **kwargs):
|
||||
return self.client_request("PATCH", url, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def get_class(api_name, version, version_map):
|
||||
"""Returns the client class for the requested API version
|
||||
|
||||
:param api_name: the name of the API, e.g. 'compute', 'image', etc
|
||||
:param version: the requested API version
|
||||
:param version_map: a dict of client classes keyed by version
|
||||
:rtype: a client class for the requested API version
|
||||
"""
|
||||
try:
|
||||
client_path = version_map[str(version)]
|
||||
except (KeyError, ValueError):
|
||||
msg = _("Invalid %(api_name)s client version '%(version)s'. "
|
||||
"Must be one of: %(version_map)s") % {
|
||||
'api_name': api_name,
|
||||
'version': version,
|
||||
'version_map': ', '.join(version_map.keys())}
|
||||
raise exceptions.UnsupportedVersion(msg)
|
||||
|
||||
return importutils.import_class(client_path)
|
||||
@@ -1,465 +1,463 @@
|
||||
# Copyright 2011 Nebula, Inc.
|
||||
# Copyright 2013 Alessio Ababilov
|
||||
# Copyright 2013 OpenStack Foundation
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
Exception definitions.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
import sys
|
||||
|
||||
import six
|
||||
|
||||
from smaugclient.i18n import _
|
||||
|
||||
|
||||
class ClientException(Exception):
|
||||
"""The base exception class for all exceptions this library raises.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class MissingArgs(ClientException):
|
||||
"""Supplied arguments are not sufficient for calling a function."""
|
||||
def __init__(self, missing):
|
||||
self.missing = missing
|
||||
msg = _("Missing arguments: %s") % ", ".join(missing)
|
||||
super(MissingArgs, self).__init__(msg)
|
||||
|
||||
|
||||
class ValidationError(ClientException):
|
||||
"""Error in validation on API client side."""
|
||||
pass
|
||||
|
||||
|
||||
class UnsupportedVersion(ClientException):
|
||||
"""User is trying to use an unsupported version of the API."""
|
||||
pass
|
||||
|
||||
|
||||
class CommandError(ClientException):
|
||||
"""Error in CLI tool."""
|
||||
pass
|
||||
|
||||
|
||||
class AuthorizationFailure(ClientException):
|
||||
"""Cannot authorize API client."""
|
||||
pass
|
||||
|
||||
|
||||
class ConnectionRefused(ClientException):
|
||||
"""Cannot connect to API service."""
|
||||
pass
|
||||
|
||||
|
||||
class AuthPluginOptionsMissing(AuthorizationFailure):
|
||||
"""Auth plugin misses some options."""
|
||||
def __init__(self, opt_names):
|
||||
super(AuthPluginOptionsMissing, self).__init__(
|
||||
_("Authentication failed. Missing options: %s") %
|
||||
", ".join(opt_names))
|
||||
self.opt_names = opt_names
|
||||
|
||||
|
||||
class AuthSystemNotFound(AuthorizationFailure):
|
||||
"""User has specified an AuthSystem that is not installed."""
|
||||
def __init__(self, auth_system):
|
||||
super(AuthSystemNotFound, self).__init__(
|
||||
_("AuthSystemNotFound: %s") % repr(auth_system))
|
||||
self.auth_system = auth_system
|
||||
|
||||
|
||||
class NoUniqueMatch(ClientException):
|
||||
"""Multiple entities found instead of one."""
|
||||
pass
|
||||
|
||||
|
||||
class EndpointException(ClientException):
|
||||
"""Something is rotten in Service Catalog."""
|
||||
pass
|
||||
|
||||
|
||||
class EndpointNotFound(EndpointException):
|
||||
"""Could not find requested endpoint in Service Catalog."""
|
||||
pass
|
||||
|
||||
|
||||
class AmbiguousEndpoints(EndpointException):
|
||||
"""Found more than one matching endpoint in Service Catalog."""
|
||||
def __init__(self, endpoints=None):
|
||||
super(AmbiguousEndpoints, self).__init__(
|
||||
_("AmbiguousEndpoints: %s") % repr(endpoints))
|
||||
self.endpoints = endpoints
|
||||
|
||||
|
||||
class HttpError(ClientException):
|
||||
"""The base exception class for all HTTP exceptions.
|
||||
"""
|
||||
http_status = 0
|
||||
message = _("HTTP Error")
|
||||
|
||||
def __init__(self, message=None, details=None,
|
||||
response=None, request_id=None,
|
||||
url=None, method=None, http_status=None):
|
||||
self.http_status = http_status or self.http_status
|
||||
self.message = message or self.message
|
||||
self.details = details
|
||||
self.request_id = request_id
|
||||
self.response = response
|
||||
self.url = url
|
||||
self.method = method
|
||||
formatted_string = "%s (HTTP %s)" % (self.message, self.http_status)
|
||||
if request_id:
|
||||
formatted_string += " (Request-ID: %s)" % request_id
|
||||
super(HttpError, self).__init__(formatted_string)
|
||||
|
||||
|
||||
class HTTPRedirection(HttpError):
|
||||
"""HTTP Redirection."""
|
||||
message = _("HTTP Redirection")
|
||||
|
||||
|
||||
class HTTPClientError(HttpError):
|
||||
"""Client-side HTTP error.
|
||||
|
||||
Exception for cases in which the client seems to have erred.
|
||||
"""
|
||||
message = _("HTTP Client Error")
|
||||
|
||||
|
||||
class HttpServerError(HttpError):
|
||||
"""Server-side HTTP error.
|
||||
|
||||
Exception for cases in which the server is aware that it has
|
||||
erred or is incapable of performing the request.
|
||||
"""
|
||||
message = _("HTTP Server Error")
|
||||
|
||||
|
||||
class MultipleChoices(HTTPRedirection):
|
||||
"""HTTP 300 - Multiple Choices.
|
||||
|
||||
Indicates multiple options for the resource that the client may follow.
|
||||
"""
|
||||
|
||||
http_status = 300
|
||||
message = _("Multiple Choices")
|
||||
|
||||
|
||||
class BadRequest(HTTPClientError):
|
||||
"""HTTP 400 - Bad Request.
|
||||
|
||||
The request cannot be fulfilled due to bad syntax.
|
||||
"""
|
||||
http_status = 400
|
||||
message = _("Bad Request")
|
||||
|
||||
|
||||
class Unauthorized(HTTPClientError):
|
||||
"""HTTP 401 - Unauthorized.
|
||||
|
||||
Similar to 403 Forbidden, but specifically for use when authentication
|
||||
is required and has failed or has not yet been provided.
|
||||
"""
|
||||
http_status = 401
|
||||
message = _("Unauthorized")
|
||||
|
||||
|
||||
class PaymentRequired(HTTPClientError):
|
||||
"""HTTP 402 - Payment Required.
|
||||
|
||||
Reserved for future use.
|
||||
"""
|
||||
http_status = 402
|
||||
message = _("Payment Required")
|
||||
|
||||
|
||||
class Forbidden(HTTPClientError):
|
||||
"""HTTP 403 - Forbidden.
|
||||
|
||||
The request was a valid request, but the server is refusing to respond
|
||||
to it.
|
||||
"""
|
||||
http_status = 403
|
||||
message = _("Forbidden")
|
||||
|
||||
|
||||
class NotFound(HTTPClientError):
|
||||
"""HTTP 404 - Not Found.
|
||||
|
||||
The requested resource could not be found but may be available again
|
||||
in the future.
|
||||
"""
|
||||
http_status = 404
|
||||
message = _("Not Found")
|
||||
|
||||
|
||||
class MethodNotAllowed(HTTPClientError):
|
||||
"""HTTP 405 - Method Not Allowed.
|
||||
|
||||
A request was made of a resource using a request method not supported
|
||||
by that resource.
|
||||
"""
|
||||
http_status = 405
|
||||
message = _("Method Not Allowed")
|
||||
|
||||
|
||||
class NotAcceptable(HTTPClientError):
|
||||
"""HTTP 406 - Not Acceptable.
|
||||
|
||||
The requested resource is only capable of generating content not
|
||||
acceptable according to the Accept headers sent in the request.
|
||||
"""
|
||||
http_status = 406
|
||||
message = _("Not Acceptable")
|
||||
|
||||
|
||||
class ProxyAuthenticationRequired(HTTPClientError):
|
||||
"""HTTP 407 - Proxy Authentication Required.
|
||||
|
||||
The client must first authenticate itself with the proxy.
|
||||
"""
|
||||
http_status = 407
|
||||
message = _("Proxy Authentication Required")
|
||||
|
||||
|
||||
class RequestTimeout(HTTPClientError):
|
||||
"""HTTP 408 - Request Timeout.
|
||||
|
||||
The server timed out waiting for the request.
|
||||
"""
|
||||
http_status = 408
|
||||
message = _("Request Timeout")
|
||||
|
||||
|
||||
class Conflict(HTTPClientError):
|
||||
"""HTTP 409 - Conflict.
|
||||
|
||||
Indicates that the request could not be processed because of conflict
|
||||
in the request, such as an edit conflict.
|
||||
"""
|
||||
http_status = 409
|
||||
message = _("Conflict")
|
||||
|
||||
|
||||
class Gone(HTTPClientError):
|
||||
"""HTTP 410 - Gone.
|
||||
|
||||
Indicates that the resource requested is no longer available and will
|
||||
not be available again.
|
||||
"""
|
||||
http_status = 410
|
||||
message = _("Gone")
|
||||
|
||||
|
||||
class LengthRequired(HTTPClientError):
|
||||
"""HTTP 411 - Length Required.
|
||||
|
||||
The request did not specify the length of its content, which is
|
||||
required by the requested resource.
|
||||
"""
|
||||
http_status = 411
|
||||
message = _("Length Required")
|
||||
|
||||
|
||||
class PreconditionFailed(HTTPClientError):
|
||||
"""HTTP 412 - Precondition Failed.
|
||||
|
||||
The server does not meet one of the preconditions that the requester
|
||||
put on the request.
|
||||
"""
|
||||
http_status = 412
|
||||
message = _("Precondition Failed")
|
||||
|
||||
|
||||
class RequestEntityTooLarge(HTTPClientError):
|
||||
"""HTTP 413 - Request Entity Too Large.
|
||||
|
||||
The request is larger than the server is willing or able to process.
|
||||
"""
|
||||
http_status = 413
|
||||
message = _("Request Entity Too Large")
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
try:
|
||||
self.retry_after = int(kwargs.pop('retry_after'))
|
||||
except (KeyError, ValueError):
|
||||
self.retry_after = 0
|
||||
|
||||
super(RequestEntityTooLarge, self).__init__(*args, **kwargs)
|
||||
|
||||
|
||||
class RequestUriTooLong(HTTPClientError):
|
||||
"""HTTP 414 - Request-URI Too Long.
|
||||
|
||||
The URI provided was too long for the server to process.
|
||||
"""
|
||||
http_status = 414
|
||||
message = _("Request-URI Too Long")
|
||||
|
||||
|
||||
class UnsupportedMediaType(HTTPClientError):
|
||||
"""HTTP 415 - Unsupported Media Type.
|
||||
|
||||
The request entity has a media type which the server or resource does
|
||||
not support.
|
||||
"""
|
||||
http_status = 415
|
||||
message = _("Unsupported Media Type")
|
||||
|
||||
|
||||
class RequestedRangeNotSatisfiable(HTTPClientError):
|
||||
"""HTTP 416 - Requested Range Not Satisfiable.
|
||||
|
||||
The client has asked for a portion of the file, but the server cannot
|
||||
supply that portion.
|
||||
"""
|
||||
http_status = 416
|
||||
message = _("Requested Range Not Satisfiable")
|
||||
|
||||
|
||||
class ExpectationFailed(HTTPClientError):
|
||||
"""HTTP 417 - Expectation Failed.
|
||||
|
||||
The server cannot meet the requirements of the Expect request-header field.
|
||||
"""
|
||||
http_status = 417
|
||||
message = _("Expectation Failed")
|
||||
|
||||
|
||||
class UnprocessableEntity(HTTPClientError):
|
||||
"""HTTP 422 - Unprocessable Entity.
|
||||
|
||||
The request was well-formed but was unable to be followed due to semantic
|
||||
errors.
|
||||
"""
|
||||
http_status = 422
|
||||
message = _("Unprocessable Entity")
|
||||
|
||||
|
||||
class InternalServerError(HttpServerError):
|
||||
"""HTTP 500 - Internal Server Error.
|
||||
|
||||
A generic error message, given when no more specific message is suitable.
|
||||
"""
|
||||
http_status = 500
|
||||
message = _("Internal Server Error")
|
||||
|
||||
|
||||
# NotImplemented is a python keyword.
|
||||
class HttpNotImplemented(HttpServerError):
|
||||
"""HTTP 501 - Not Implemented.
|
||||
|
||||
The server either does not recognize the request method, or it lacks
|
||||
the ability to fulfill the request.
|
||||
"""
|
||||
http_status = 501
|
||||
message = _("Not Implemented")
|
||||
|
||||
|
||||
class BadGateway(HttpServerError):
|
||||
"""HTTP 502 - Bad Gateway.
|
||||
|
||||
The server was acting as a gateway or proxy and received an invalid
|
||||
response from the upstream server.
|
||||
"""
|
||||
http_status = 502
|
||||
message = _("Bad Gateway")
|
||||
|
||||
|
||||
class ServiceUnavailable(HttpServerError):
|
||||
"""HTTP 503 - Service Unavailable.
|
||||
|
||||
The server is currently unavailable.
|
||||
"""
|
||||
http_status = 503
|
||||
message = _("Service Unavailable")
|
||||
|
||||
|
||||
class GatewayTimeout(HttpServerError):
|
||||
"""HTTP 504 - Gateway Timeout.
|
||||
|
||||
The server was acting as a gateway or proxy and did not receive a timely
|
||||
response from the upstream server.
|
||||
"""
|
||||
http_status = 504
|
||||
message = _("Gateway Timeout")
|
||||
|
||||
|
||||
class HttpVersionNotSupported(HttpServerError):
|
||||
"""HTTP 505 - HttpVersion Not Supported.
|
||||
|
||||
The server does not support the HTTP protocol version used in the request.
|
||||
"""
|
||||
http_status = 505
|
||||
message = _("HTTP Version Not Supported")
|
||||
|
||||
|
||||
# _code_map contains all the classes that have http_status attribute.
|
||||
_code_map = dict(
|
||||
(getattr(obj, 'http_status', None), obj)
|
||||
for name, obj in six.iteritems(vars(sys.modules[__name__]))
|
||||
if inspect.isclass(obj) and getattr(obj, 'http_status', False)
|
||||
)
|
||||
|
||||
|
||||
def from_response(response, method, url):
|
||||
"""Returns an instance of :class:`HttpError` or subclass based on response.
|
||||
|
||||
:param response: instance of `requests.Response` class
|
||||
:param method: HTTP method used for request
|
||||
:param url: URL used for request
|
||||
"""
|
||||
|
||||
req_id = response.headers.get("x-openstack-request-id")
|
||||
#NOTE(hdd) true for older versions of nova and cinder
|
||||
if not req_id:
|
||||
req_id = response.headers.get("x-compute-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):
|
||||
error = list(body.values())[0]
|
||||
kwargs["message"] = error.get("message")
|
||||
kwargs["details"] = error.get("details")
|
||||
elif content_type.startswith("text/"):
|
||||
kwargs["details"] = response.text
|
||||
|
||||
try:
|
||||
cls = _code_map[response.status_code]
|
||||
except KeyError:
|
||||
if 500 <= response.status_code < 600:
|
||||
cls = HttpServerError
|
||||
elif 400 <= response.status_code < 500:
|
||||
cls = HTTPClientError
|
||||
else:
|
||||
cls = HttpError
|
||||
return cls(**kwargs)
|
||||
# Copyright 2011 Nebula, Inc.
|
||||
# Copyright 2013 Alessio Ababilov
|
||||
# Copyright 2013 OpenStack Foundation
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
Exception definitions.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
import sys
|
||||
|
||||
import six
|
||||
|
||||
from karborclient.i18n import _
|
||||
|
||||
|
||||
class ClientException(Exception):
|
||||
"""The base exception class for all exceptions this library raises."""
|
||||
pass
|
||||
|
||||
|
||||
class MissingArgs(ClientException):
|
||||
"""Supplied arguments are not sufficient for calling a function."""
|
||||
def __init__(self, missing):
|
||||
self.missing = missing
|
||||
msg = _("Missing arguments: %s") % ", ".join(missing)
|
||||
super(MissingArgs, self).__init__(msg)
|
||||
|
||||
|
||||
class ValidationError(ClientException):
|
||||
"""Error in validation on API client side."""
|
||||
pass
|
||||
|
||||
|
||||
class UnsupportedVersion(ClientException):
|
||||
"""User is trying to use an unsupported version of the API."""
|
||||
pass
|
||||
|
||||
|
||||
class CommandError(ClientException):
|
||||
"""Error in CLI tool."""
|
||||
pass
|
||||
|
||||
|
||||
class AuthorizationFailure(ClientException):
|
||||
"""Cannot authorize API client."""
|
||||
pass
|
||||
|
||||
|
||||
class ConnectionRefused(ClientException):
|
||||
"""Cannot connect to API service."""
|
||||
pass
|
||||
|
||||
|
||||
class AuthPluginOptionsMissing(AuthorizationFailure):
|
||||
"""Auth plugin misses some options."""
|
||||
def __init__(self, opt_names):
|
||||
super(AuthPluginOptionsMissing, self).__init__(
|
||||
_("Authentication failed. Missing options: %s") %
|
||||
", ".join(opt_names))
|
||||
self.opt_names = opt_names
|
||||
|
||||
|
||||
class AuthSystemNotFound(AuthorizationFailure):
|
||||
"""User has specified an AuthSystem that is not installed."""
|
||||
def __init__(self, auth_system):
|
||||
super(AuthSystemNotFound, self).__init__(
|
||||
_("AuthSystemNotFound: %s") % repr(auth_system))
|
||||
self.auth_system = auth_system
|
||||
|
||||
|
||||
class NoUniqueMatch(ClientException):
|
||||
"""Multiple entities found instead of one."""
|
||||
pass
|
||||
|
||||
|
||||
class EndpointException(ClientException):
|
||||
"""Something is rotten in Service Catalog."""
|
||||
pass
|
||||
|
||||
|
||||
class EndpointNotFound(EndpointException):
|
||||
"""Could not find requested endpoint in Service Catalog."""
|
||||
pass
|
||||
|
||||
|
||||
class AmbiguousEndpoints(EndpointException):
|
||||
"""Found more than one matching endpoint in Service Catalog."""
|
||||
def __init__(self, endpoints=None):
|
||||
super(AmbiguousEndpoints, self).__init__(
|
||||
_("AmbiguousEndpoints: %s") % repr(endpoints))
|
||||
self.endpoints = endpoints
|
||||
|
||||
|
||||
class HttpError(ClientException):
|
||||
"""The base exception class for all HTTP exceptions."""
|
||||
http_status = 0
|
||||
message = _("HTTP Error")
|
||||
|
||||
def __init__(self, message=None, details=None,
|
||||
response=None, request_id=None,
|
||||
url=None, method=None, http_status=None):
|
||||
self.http_status = http_status or self.http_status
|
||||
self.message = message or self.message
|
||||
self.details = details
|
||||
self.request_id = request_id
|
||||
self.response = response
|
||||
self.url = url
|
||||
self.method = method
|
||||
formatted_string = "%s (HTTP %s)" % (self.message, self.http_status)
|
||||
if request_id:
|
||||
formatted_string += " (Request-ID: %s)" % request_id
|
||||
super(HttpError, self).__init__(formatted_string)
|
||||
|
||||
|
||||
class HTTPRedirection(HttpError):
|
||||
"""HTTP Redirection."""
|
||||
message = _("HTTP Redirection")
|
||||
|
||||
|
||||
class HTTPClientError(HttpError):
|
||||
"""Client-side HTTP error.
|
||||
|
||||
Exception for cases in which the client seems to have erred.
|
||||
"""
|
||||
message = _("HTTP Client Error")
|
||||
|
||||
|
||||
class HttpServerError(HttpError):
|
||||
"""Server-side HTTP error.
|
||||
|
||||
Exception for cases in which the server is aware that it has
|
||||
erred or is incapable of performing the request.
|
||||
"""
|
||||
message = _("HTTP Server Error")
|
||||
|
||||
|
||||
class MultipleChoices(HTTPRedirection):
|
||||
"""HTTP 300 - Multiple Choices.
|
||||
|
||||
Indicates multiple options for the resource that the client may follow.
|
||||
"""
|
||||
|
||||
http_status = 300
|
||||
message = _("Multiple Choices")
|
||||
|
||||
|
||||
class BadRequest(HTTPClientError):
|
||||
"""HTTP 400 - Bad Request.
|
||||
|
||||
The request cannot be fulfilled due to bad syntax.
|
||||
"""
|
||||
http_status = 400
|
||||
message = _("Bad Request")
|
||||
|
||||
|
||||
class Unauthorized(HTTPClientError):
|
||||
"""HTTP 401 - Unauthorized.
|
||||
|
||||
Similar to 403 Forbidden, but specifically for use when authentication
|
||||
is required and has failed or has not yet been provided.
|
||||
"""
|
||||
http_status = 401
|
||||
message = _("Unauthorized")
|
||||
|
||||
|
||||
class PaymentRequired(HTTPClientError):
|
||||
"""HTTP 402 - Payment Required.
|
||||
|
||||
Reserved for future use.
|
||||
"""
|
||||
http_status = 402
|
||||
message = _("Payment Required")
|
||||
|
||||
|
||||
class Forbidden(HTTPClientError):
|
||||
"""HTTP 403 - Forbidden.
|
||||
|
||||
The request was a valid request, but the server is refusing to respond
|
||||
to it.
|
||||
"""
|
||||
http_status = 403
|
||||
message = _("Forbidden")
|
||||
|
||||
|
||||
class NotFound(HTTPClientError):
|
||||
"""HTTP 404 - Not Found.
|
||||
|
||||
The requested resource could not be found but may be available again
|
||||
in the future.
|
||||
"""
|
||||
http_status = 404
|
||||
message = _("Not Found")
|
||||
|
||||
|
||||
class MethodNotAllowed(HTTPClientError):
|
||||
"""HTTP 405 - Method Not Allowed.
|
||||
|
||||
A request was made of a resource using a request method not supported
|
||||
by that resource.
|
||||
"""
|
||||
http_status = 405
|
||||
message = _("Method Not Allowed")
|
||||
|
||||
|
||||
class NotAcceptable(HTTPClientError):
|
||||
"""HTTP 406 - Not Acceptable.
|
||||
|
||||
The requested resource is only capable of generating content not
|
||||
acceptable according to the Accept headers sent in the request.
|
||||
"""
|
||||
http_status = 406
|
||||
message = _("Not Acceptable")
|
||||
|
||||
|
||||
class ProxyAuthenticationRequired(HTTPClientError):
|
||||
"""HTTP 407 - Proxy Authentication Required.
|
||||
|
||||
The client must first authenticate itself with the proxy.
|
||||
"""
|
||||
http_status = 407
|
||||
message = _("Proxy Authentication Required")
|
||||
|
||||
|
||||
class RequestTimeout(HTTPClientError):
|
||||
"""HTTP 408 - Request Timeout.
|
||||
|
||||
The server timed out waiting for the request.
|
||||
"""
|
||||
http_status = 408
|
||||
message = _("Request Timeout")
|
||||
|
||||
|
||||
class Conflict(HTTPClientError):
|
||||
"""HTTP 409 - Conflict.
|
||||
|
||||
Indicates that the request could not be processed because of conflict
|
||||
in the request, such as an edit conflict.
|
||||
"""
|
||||
http_status = 409
|
||||
message = _("Conflict")
|
||||
|
||||
|
||||
class Gone(HTTPClientError):
|
||||
"""HTTP 410 - Gone.
|
||||
|
||||
Indicates that the resource requested is no longer available and will
|
||||
not be available again.
|
||||
"""
|
||||
http_status = 410
|
||||
message = _("Gone")
|
||||
|
||||
|
||||
class LengthRequired(HTTPClientError):
|
||||
"""HTTP 411 - Length Required.
|
||||
|
||||
The request did not specify the length of its content, which is
|
||||
required by the requested resource.
|
||||
"""
|
||||
http_status = 411
|
||||
message = _("Length Required")
|
||||
|
||||
|
||||
class PreconditionFailed(HTTPClientError):
|
||||
"""HTTP 412 - Precondition Failed.
|
||||
|
||||
The server does not meet one of the preconditions that the requester
|
||||
put on the request.
|
||||
"""
|
||||
http_status = 412
|
||||
message = _("Precondition Failed")
|
||||
|
||||
|
||||
class RequestEntityTooLarge(HTTPClientError):
|
||||
"""HTTP 413 - Request Entity Too Large.
|
||||
|
||||
The request is larger than the server is willing or able to process.
|
||||
"""
|
||||
http_status = 413
|
||||
message = _("Request Entity Too Large")
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
try:
|
||||
self.retry_after = int(kwargs.pop('retry_after'))
|
||||
except (KeyError, ValueError):
|
||||
self.retry_after = 0
|
||||
|
||||
super(RequestEntityTooLarge, self).__init__(*args, **kwargs)
|
||||
|
||||
|
||||
class RequestUriTooLong(HTTPClientError):
|
||||
"""HTTP 414 - Request-URI Too Long.
|
||||
|
||||
The URI provided was too long for the server to process.
|
||||
"""
|
||||
http_status = 414
|
||||
message = _("Request-URI Too Long")
|
||||
|
||||
|
||||
class UnsupportedMediaType(HTTPClientError):
|
||||
"""HTTP 415 - Unsupported Media Type.
|
||||
|
||||
The request entity has a media type which the server or resource does
|
||||
not support.
|
||||
"""
|
||||
http_status = 415
|
||||
message = _("Unsupported Media Type")
|
||||
|
||||
|
||||
class RequestedRangeNotSatisfiable(HTTPClientError):
|
||||
"""HTTP 416 - Requested Range Not Satisfiable.
|
||||
|
||||
The client has asked for a portion of the file, but the server cannot
|
||||
supply that portion.
|
||||
"""
|
||||
http_status = 416
|
||||
message = _("Requested Range Not Satisfiable")
|
||||
|
||||
|
||||
class ExpectationFailed(HTTPClientError):
|
||||
"""HTTP 417 - Expectation Failed.
|
||||
|
||||
The server cannot meet the requirements of the Expect request-header field.
|
||||
"""
|
||||
http_status = 417
|
||||
message = _("Expectation Failed")
|
||||
|
||||
|
||||
class UnprocessableEntity(HTTPClientError):
|
||||
"""HTTP 422 - Unprocessable Entity.
|
||||
|
||||
The request was well-formed but was unable to be followed due to semantic
|
||||
errors.
|
||||
"""
|
||||
http_status = 422
|
||||
message = _("Unprocessable Entity")
|
||||
|
||||
|
||||
class InternalServerError(HttpServerError):
|
||||
"""HTTP 500 - Internal Server Error.
|
||||
|
||||
A generic error message, given when no more specific message is suitable.
|
||||
"""
|
||||
http_status = 500
|
||||
message = _("Internal Server Error")
|
||||
|
||||
|
||||
# NotImplemented is a python keyword.
|
||||
class HttpNotImplemented(HttpServerError):
|
||||
"""HTTP 501 - Not Implemented.
|
||||
|
||||
The server either does not recognize the request method, or it lacks
|
||||
the ability to fulfill the request.
|
||||
"""
|
||||
http_status = 501
|
||||
message = _("Not Implemented")
|
||||
|
||||
|
||||
class BadGateway(HttpServerError):
|
||||
"""HTTP 502 - Bad Gateway.
|
||||
|
||||
The server was acting as a gateway or proxy and received an invalid
|
||||
response from the upstream server.
|
||||
"""
|
||||
http_status = 502
|
||||
message = _("Bad Gateway")
|
||||
|
||||
|
||||
class ServiceUnavailable(HttpServerError):
|
||||
"""HTTP 503 - Service Unavailable.
|
||||
|
||||
The server is currently unavailable.
|
||||
"""
|
||||
http_status = 503
|
||||
message = _("Service Unavailable")
|
||||
|
||||
|
||||
class GatewayTimeout(HttpServerError):
|
||||
"""HTTP 504 - Gateway Timeout.
|
||||
|
||||
The server was acting as a gateway or proxy and did not receive a timely
|
||||
response from the upstream server.
|
||||
"""
|
||||
http_status = 504
|
||||
message = _("Gateway Timeout")
|
||||
|
||||
|
||||
class HttpVersionNotSupported(HttpServerError):
|
||||
"""HTTP 505 - HttpVersion Not Supported.
|
||||
|
||||
The server does not support the HTTP protocol version used in the request.
|
||||
"""
|
||||
http_status = 505
|
||||
message = _("HTTP Version Not Supported")
|
||||
|
||||
|
||||
# _code_map contains all the classes that have http_status attribute.
|
||||
_code_map = dict(
|
||||
(getattr(obj, 'http_status', None), obj)
|
||||
for name, obj in six.iteritems(vars(sys.modules[__name__]))
|
||||
if inspect.isclass(obj) and getattr(obj, 'http_status', False)
|
||||
)
|
||||
|
||||
|
||||
def from_response(response, method, url):
|
||||
"""Returns an instance of :class:`HttpError` or subclass based on response.
|
||||
|
||||
:param response: instance of `requests.Response` class
|
||||
:param method: HTTP method used for request
|
||||
:param url: URL used for request
|
||||
"""
|
||||
|
||||
req_id = response.headers.get("x-openstack-request-id")
|
||||
# NOTE(hdd) true for older versions of nova and cinder
|
||||
if not req_id:
|
||||
req_id = response.headers.get("x-compute-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):
|
||||
error = list(body.values())[0]
|
||||
kwargs["message"] = error.get("message")
|
||||
kwargs["details"] = error.get("details")
|
||||
elif content_type.startswith("text/"):
|
||||
kwargs["details"] = response.text
|
||||
|
||||
try:
|
||||
cls = _code_map[response.status_code]
|
||||
except KeyError:
|
||||
if 500 <= response.status_code < 600:
|
||||
cls = HttpServerError
|
||||
elif 400 <= response.status_code < 500:
|
||||
cls = HTTPClientError
|
||||
else:
|
||||
cls = HttpError
|
||||
return cls(**kwargs)
|
||||
@@ -1,177 +1,177 @@
|
||||
# Copyright 2013 OpenStack Foundation
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
A fake server that "responds" to API methods with pre-canned responses.
|
||||
|
||||
All of these responses come from the spec, so if for some reason the spec's
|
||||
wrong the tests might raise AssertionError. I've indicated in comments the
|
||||
places where actual behavior differs from the spec.
|
||||
"""
|
||||
|
||||
# W0102: Dangerous default value %s as argument
|
||||
# pylint: disable=W0102
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
import six
|
||||
from six.moves.urllib import parse
|
||||
|
||||
from smaugclient.openstack.common.apiclient import client
|
||||
|
||||
|
||||
def assert_has_keys(dct, required=None, optional=None):
|
||||
if required is None:
|
||||
required = []
|
||||
if optional is None:
|
||||
optional = []
|
||||
for k in required:
|
||||
try:
|
||||
assert k in dct
|
||||
except AssertionError:
|
||||
extra_keys = set(dct.keys()).difference(set(required + optional))
|
||||
raise AssertionError("found unexpected keys: %s" %
|
||||
list(extra_keys))
|
||||
|
||||
|
||||
class TestResponse(requests.Response):
|
||||
"""Wrap requests.Response and provide a convenient initialization.
|
||||
"""
|
||||
|
||||
def __init__(self, data):
|
||||
super(TestResponse, self).__init__()
|
||||
self._content_consumed = True
|
||||
if isinstance(data, dict):
|
||||
self.status_code = data.get('status_code', 200)
|
||||
# Fake the text attribute to streamline Response creation
|
||||
text = data.get('text', "")
|
||||
if isinstance(text, (dict, list)):
|
||||
self._content = json.dumps(text)
|
||||
default_headers = {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
else:
|
||||
self._content = text
|
||||
default_headers = {}
|
||||
if six.PY3 and isinstance(self._content, six.string_types):
|
||||
self._content = self._content.encode('utf-8', 'strict')
|
||||
self.headers = data.get('headers') or default_headers
|
||||
else:
|
||||
self.status_code = data
|
||||
|
||||
def __eq__(self, other):
|
||||
return (self.status_code == other.status_code and
|
||||
self.headers == other.headers and
|
||||
self._content == other._content)
|
||||
|
||||
|
||||
class FakeHTTPClient(client.HTTPClient):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.callstack = []
|
||||
self.fixtures = kwargs.pop("fixtures", None) or {}
|
||||
if not args and not "auth_plugin" in kwargs:
|
||||
args = (None, )
|
||||
super(FakeHTTPClient, self).__init__(*args, **kwargs)
|
||||
|
||||
def assert_called(self, method, url, body=None, pos=-1):
|
||||
"""Assert than an API method was just called.
|
||||
"""
|
||||
expected = (method, url)
|
||||
called = self.callstack[pos][0:2]
|
||||
assert self.callstack, \
|
||||
"Expected %s %s but no calls were made." % expected
|
||||
|
||||
assert expected == called, 'Expected %s %s; got %s %s' % \
|
||||
(expected + called)
|
||||
|
||||
if body is not None:
|
||||
if self.callstack[pos][3] != body:
|
||||
raise AssertionError('%r != %r' %
|
||||
(self.callstack[pos][3], body))
|
||||
|
||||
def assert_called_anytime(self, method, url, body=None):
|
||||
"""Assert than an API method was called anytime in the test.
|
||||
"""
|
||||
expected = (method, url)
|
||||
|
||||
assert self.callstack, \
|
||||
"Expected %s %s but no calls were made." % expected
|
||||
|
||||
found = False
|
||||
entry = None
|
||||
for entry in self.callstack:
|
||||
if expected == entry[0:2]:
|
||||
found = True
|
||||
break
|
||||
|
||||
assert found, 'Expected %s %s; got %s' % \
|
||||
(method, url, self.callstack)
|
||||
if body is not None:
|
||||
assert entry[3] == body, "%s != %s" % (entry[3], body)
|
||||
|
||||
self.callstack = []
|
||||
|
||||
def clear_callstack(self):
|
||||
self.callstack = []
|
||||
|
||||
def authenticate(self):
|
||||
pass
|
||||
|
||||
def client_request(self, client, method, url, **kwargs):
|
||||
# Check that certain things are called correctly
|
||||
if method in ["GET", "DELETE"]:
|
||||
assert "json" not in kwargs
|
||||
|
||||
# Note the call
|
||||
self.callstack.append(
|
||||
(method,
|
||||
url,
|
||||
kwargs.get("headers") or {},
|
||||
kwargs.get("json") or kwargs.get("data")))
|
||||
try:
|
||||
fixture = self.fixtures[url][method]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
return TestResponse({"headers": fixture[0],
|
||||
"text": fixture[1]})
|
||||
|
||||
# Call the method
|
||||
args = parse.parse_qsl(parse.urlparse(url)[4])
|
||||
kwargs.update(args)
|
||||
munged_url = url.rsplit('?', 1)[0]
|
||||
munged_url = munged_url.strip('/').replace('/', '_').replace('.', '_')
|
||||
munged_url = munged_url.replace('-', '_')
|
||||
|
||||
callback = "%s_%s" % (method.lower(), munged_url)
|
||||
|
||||
if not hasattr(self, callback):
|
||||
raise AssertionError('Called unknown API method: %s %s, '
|
||||
'expected fakes method name: %s' %
|
||||
(method, url, callback))
|
||||
|
||||
resp = getattr(self, callback)(**kwargs)
|
||||
if len(resp) == 3:
|
||||
status, headers, body = resp
|
||||
else:
|
||||
status, body = resp
|
||||
headers = {}
|
||||
return TestResponse({
|
||||
"status_code": status,
|
||||
"text": body,
|
||||
"headers": headers,
|
||||
})
|
||||
# Copyright 2013 OpenStack Foundation
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
A fake server that "responds" to API methods with pre-canned responses.
|
||||
|
||||
All of these responses come from the spec, so if for some reason the spec's
|
||||
wrong the tests might raise AssertionError. I've indicated in comments the
|
||||
places where actual behavior differs from the spec.
|
||||
"""
|
||||
|
||||
# W0102: Dangerous default value %s as argument
|
||||
# pylint: disable=W0102
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
import six
|
||||
from six.moves.urllib import parse
|
||||
|
||||
from karborclient.common.apiclient import client
|
||||
|
||||
|
||||
def assert_has_keys(dct, required=None, optional=None):
|
||||
if required is None:
|
||||
required = []
|
||||
if optional is None:
|
||||
optional = []
|
||||
for k in required:
|
||||
try:
|
||||
assert k in dct
|
||||
except AssertionError:
|
||||
extra_keys = set(dct.keys()).difference(set(required + optional))
|
||||
raise AssertionError("found unexpected keys: %s" %
|
||||
list(extra_keys))
|
||||
|
||||
|
||||
class TestResponse(requests.Response):
|
||||
"""Wrap requests.Response and provide a convenient initialization."""
|
||||
|
||||
def __init__(self, data):
|
||||
super(TestResponse, self).__init__()
|
||||
self._content_consumed = True
|
||||
if isinstance(data, dict):
|
||||
self.status_code = data.get('status_code', 200)
|
||||
# Fake the text attribute to streamline Response creation
|
||||
text = data.get('text', "")
|
||||
if isinstance(text, (dict, list)):
|
||||
self._content = json.dumps(text)
|
||||
default_headers = {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
else:
|
||||
self._content = text
|
||||
default_headers = {}
|
||||
if six.PY3 and isinstance(self._content, six.string_types):
|
||||
self._content = self._content.encode('utf-8', 'strict')
|
||||
self.headers = data.get('headers') or default_headers
|
||||
else:
|
||||
self.status_code = data
|
||||
|
||||
def __eq__(self, other):
|
||||
return (self.status_code == other.status_code and
|
||||
self.headers == other.headers and
|
||||
self._content == other._content)
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self.__eq__(other)
|
||||
|
||||
|
||||
class FakeHTTPClient(client.HTTPClient):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.callstack = []
|
||||
self.fixtures = kwargs.pop("fixtures", None) or {}
|
||||
if not args and "auth_plugin" not in kwargs:
|
||||
args = (None, )
|
||||
super(FakeHTTPClient, self).__init__(*args, **kwargs)
|
||||
|
||||
def assert_called(self, method, url, body=None, pos=-1):
|
||||
"""Assert than an API method was just called."""
|
||||
expected = (method, url)
|
||||
called = self.callstack[pos][0:2]
|
||||
assert self.callstack, \
|
||||
"Expected %s %s but no calls were made." % expected
|
||||
|
||||
assert expected == called, 'Expected %s %s; got %s %s' % \
|
||||
(expected + called)
|
||||
|
||||
if body is not None:
|
||||
if self.callstack[pos][3] != body:
|
||||
raise AssertionError('%r != %r' %
|
||||
(self.callstack[pos][3], body))
|
||||
|
||||
def assert_called_anytime(self, method, url, body=None):
|
||||
"""Assert than an API method was called anytime in the test."""
|
||||
expected = (method, url)
|
||||
|
||||
assert self.callstack, \
|
||||
"Expected %s %s but no calls were made." % expected
|
||||
|
||||
found = False
|
||||
entry = None
|
||||
for entry in self.callstack:
|
||||
if expected == entry[0:2]:
|
||||
found = True
|
||||
break
|
||||
|
||||
assert found, 'Expected %s %s; got %s' % \
|
||||
(method, url, self.callstack)
|
||||
if body is not None:
|
||||
assert entry[3] == body, "%s != %s" % (entry[3], body)
|
||||
|
||||
self.callstack = []
|
||||
|
||||
def clear_callstack(self):
|
||||
self.callstack = []
|
||||
|
||||
def authenticate(self):
|
||||
pass
|
||||
|
||||
def client_request(self, client, method, url, **kwargs):
|
||||
# Check that certain things are called correctly
|
||||
if method in ["GET", "DELETE"]:
|
||||
assert "json" not in kwargs
|
||||
|
||||
# Note the call
|
||||
self.callstack.append(
|
||||
(method,
|
||||
url,
|
||||
kwargs.get("headers") or {},
|
||||
kwargs.get("json") or kwargs.get("data")))
|
||||
try:
|
||||
fixture = self.fixtures[url][method]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
return TestResponse({"headers": fixture[0],
|
||||
"text": fixture[1]})
|
||||
|
||||
# Call the method
|
||||
args = parse.parse_qsl(parse.urlparse(url)[4])
|
||||
kwargs.update(args)
|
||||
munged_url = url.rsplit('?', 1)[0]
|
||||
munged_url = munged_url.strip('/').replace('/', '_').replace('.', '_')
|
||||
munged_url = munged_url.replace('-', '_')
|
||||
|
||||
callback = "%s_%s" % (method.lower(), munged_url)
|
||||
|
||||
if not hasattr(self, callback):
|
||||
raise AssertionError('Called unknown API method: %s %s, '
|
||||
'expected fakes method name: %s' %
|
||||
(method, url, callback))
|
||||
|
||||
resp = getattr(self, callback)(**kwargs)
|
||||
if len(resp) == 3:
|
||||
status, headers, body = resp
|
||||
else:
|
||||
status, body = resp
|
||||
headers = {}
|
||||
return TestResponse({
|
||||
"status_code": status,
|
||||
"text": body,
|
||||
"headers": headers,
|
||||
})
|
||||
@@ -20,8 +20,9 @@ import copy
|
||||
import six
|
||||
from six.moves.urllib import parse
|
||||
|
||||
from smaugclient.common import http
|
||||
from smaugclient.openstack.common.apiclient import exceptions
|
||||
from karborclient.common.apiclient import exceptions
|
||||
from karborclient.common import http
|
||||
|
||||
|
||||
SORT_DIR_VALUES = ('asc', 'desc')
|
||||
SORT_KEY_VALUES = ('id', 'status', 'name', 'created_at')
|
||||
@@ -160,10 +161,9 @@ class Manager(object):
|
||||
if detailed:
|
||||
detail = "/detail"
|
||||
|
||||
return ("/v1/%(project_id)s/%(resource_type)s%(detail)s"
|
||||
return ("/%(resource_type)s%(detail)s"
|
||||
"%(query_string)s" %
|
||||
{"project_id": self.project_id,
|
||||
"resource_type": resource_type, "detail": detail,
|
||||
{"resource_type": resource_type, "detail": detail,
|
||||
"query_string": query_string})
|
||||
|
||||
def _format_sort_param(self, sort):
|
||||
@@ -331,6 +331,9 @@ class Resource(object):
|
||||
return False
|
||||
return self._info == other._info
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self.__eq__(other)
|
||||
|
||||
def is_loaded(self):
|
||||
return self._loaded
|
||||
|
||||
@@ -26,10 +26,12 @@ import requests
|
||||
import six
|
||||
from six.moves import urllib
|
||||
|
||||
from smaugclient.openstack.common.apiclient import exceptions as exc
|
||||
from karborclient.common.apiclient import exceptions as exc
|
||||
from karborclient.i18n import _LE
|
||||
from karborclient.i18n import _LW
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
USER_AGENT = 'python-smaugclient'
|
||||
USER_AGENT = 'python-karborclient'
|
||||
CHUNKSIZE = 1024 * 64 # 64kB
|
||||
|
||||
|
||||
@@ -48,7 +50,7 @@ def get_system_ca_file():
|
||||
if os.path.exists(ca):
|
||||
LOG.debug("Using ca file %s", ca)
|
||||
return ca
|
||||
LOG.warning("System ca file could not be found.")
|
||||
LOG.warning(_LW("System ca file could not be found."))
|
||||
|
||||
|
||||
class HTTPClient(object):
|
||||
@@ -246,7 +248,7 @@ class HTTPClient(object):
|
||||
if 'data' in kwargs:
|
||||
raise ValueError("Can't provide both 'data' and "
|
||||
"'body' to a request")
|
||||
LOG.warning("Use of 'body' is deprecated; use 'data' instead")
|
||||
LOG.warning(_LW("Use of 'body' is deprecated; use 'data' instead"))
|
||||
kwargs['data'] = kwargs.pop('body')
|
||||
if 'data' in kwargs:
|
||||
kwargs['data'] = jsonutils.dumps(kwargs['data'])
|
||||
@@ -258,7 +260,7 @@ class HTTPClient(object):
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
LOG.error('Could not decode response body as JSON')
|
||||
LOG.error(_LE('Could not decode response body as JSON'))
|
||||
else:
|
||||
body = None
|
||||
|
||||
@@ -269,7 +271,7 @@ class HTTPClient(object):
|
||||
if 'data' in kwargs:
|
||||
raise ValueError("Can't provide both 'data' and "
|
||||
"'body' to a request")
|
||||
LOG.warning("Use of 'body' is deprecated; use 'data' instead")
|
||||
LOG.warning(_LW("Use of 'body' is deprecated; use 'data' instead"))
|
||||
kwargs['data'] = kwargs.pop('body')
|
||||
# Chunking happens automatically if 'body' is a
|
||||
# file-like object
|
||||
@@ -299,7 +301,7 @@ class HTTPClient(object):
|
||||
|
||||
|
||||
class SessionClient(keystone_adapter.Adapter):
|
||||
"""Smaug specific keystoneclient Adapter.
|
||||
"""karbor specific keystoneclient Adapter.
|
||||
|
||||
"""
|
||||
|
||||
@@ -326,7 +328,7 @@ class SessionClient(keystone_adapter.Adapter):
|
||||
if 'data' in kwargs:
|
||||
raise ValueError("Can't provide both 'data' and "
|
||||
"'body' to a request")
|
||||
LOG.warning("Use of 'body' is deprecated; use 'data' instead")
|
||||
LOG.warning(_LW("Use of 'body' is deprecated; use 'data' instead"))
|
||||
kwargs['data'] = kwargs.pop('body')
|
||||
if 'data' in kwargs:
|
||||
kwargs['data'] = jsonutils.dumps(kwargs['data'])
|
||||
@@ -351,7 +353,7 @@ class SessionClient(keystone_adapter.Adapter):
|
||||
if 'data' in kwargs:
|
||||
raise ValueError("Can't provide both 'data' and "
|
||||
"'body' to a request")
|
||||
LOG.warning("Use of 'body' is deprecated; use 'data' instead")
|
||||
LOG.warning(_LW("Use of 'body' is deprecated; use 'data' instead"))
|
||||
kwargs['data'] = kwargs.pop('body')
|
||||
resp = keystone_adapter.Adapter.request(self,
|
||||
url,
|
||||
@@ -386,7 +388,7 @@ def _construct_http_client(*args, **kwargs):
|
||||
'service_type': service_type,
|
||||
'region_name': region_name,
|
||||
'service_name': service_name,
|
||||
'user_agent': 'python-smaugclient',
|
||||
'user_agent': 'python-karborclient',
|
||||
}
|
||||
parameters.update(kwargs)
|
||||
return SessionClient(**parameters)
|
||||
@@ -12,21 +12,18 @@
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import six
|
||||
import uuid
|
||||
|
||||
from oslo_log import log as logging
|
||||
from oslo_utils import encodeutils
|
||||
from oslo_utils import importutils
|
||||
|
||||
import prettytable
|
||||
|
||||
from smaugclient.openstack.common.apiclient import exceptions
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
from karborclient.common.apiclient import exceptions
|
||||
|
||||
|
||||
# Decorator for cli-args
|
||||
@@ -52,13 +49,6 @@ def env(*vars, **kwargs):
|
||||
return kwargs.get('default', '')
|
||||
|
||||
|
||||
def import_versioned_module(version, submodule=None):
|
||||
module = 'smaugclient.v%s' % version
|
||||
if submodule:
|
||||
module = '.'.join((module, submodule))
|
||||
return importutils.import_module(module)
|
||||
|
||||
|
||||
def _print(pt, order):
|
||||
if sys.version_info >= (3, 0):
|
||||
print(pt.get_string(sortby=order))
|
||||
@@ -115,7 +105,7 @@ def print_list(objs, fields, exclude_unavailable=False, formatters=None,
|
||||
fields.remove(f)
|
||||
|
||||
pt = prettytable.PrettyTable((f for f in fields), caching=False)
|
||||
pt.aligns = ['l' for f in fields]
|
||||
pt.align = 'l'
|
||||
for row in rows:
|
||||
pt.add_row(row)
|
||||
|
||||
@@ -126,17 +116,40 @@ def print_list(objs, fields, exclude_unavailable=False, formatters=None,
|
||||
_print(pt, order_by)
|
||||
|
||||
|
||||
def print_dict(d, property="Property"):
|
||||
def print_dict(d, property="Property", dict_format_list=None,
|
||||
json_format_list=None):
|
||||
pt = prettytable.PrettyTable([property, 'Value'], caching=False)
|
||||
pt.aligns = ['l', 'l']
|
||||
pt.align = 'l'
|
||||
for r in six.iteritems(d):
|
||||
r = list(r)
|
||||
if isinstance(r[1], six.string_types) and "\r" in r[1]:
|
||||
r[1] = r[1].replace("\r", " ")
|
||||
if dict_format_list is not None and r[0] in dict_format_list:
|
||||
r[1] = dict_prettyprint(r[1])
|
||||
if json_format_list is not None and r[0] in json_format_list:
|
||||
r[1] = json_prettyprint(r[1])
|
||||
pt.add_row(r)
|
||||
_print(pt, property)
|
||||
|
||||
|
||||
def dict_prettyprint(val):
|
||||
"""dict pretty print formatter.
|
||||
|
||||
:param val: dict.
|
||||
:return: formatted json string.
|
||||
"""
|
||||
return json.dumps(val, indent=2, sort_keys=True)
|
||||
|
||||
|
||||
def json_prettyprint(val):
|
||||
"""json pretty print formatter.
|
||||
|
||||
:param val: json string.
|
||||
:return: formatted json string.
|
||||
"""
|
||||
return val and json.dumps(json.loads(val), indent=2, sort_keys=True)
|
||||
|
||||
|
||||
def find_resource(manager, name_or_id, *args, **kwargs):
|
||||
"""Helper for the _find_* methods."""
|
||||
# first try to get entity as integer id
|
||||
@@ -1,34 +1,38 @@
|
||||
# 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.
|
||||
|
||||
"""oslo.i18n integration module.
|
||||
|
||||
See http://docs.openstack.org/developer/oslo.i18n/usage.html
|
||||
|
||||
"""
|
||||
|
||||
import oslo_i18n
|
||||
|
||||
_translators = oslo_i18n.TranslatorFactory(domain='smaugclient')
|
||||
|
||||
# The primary translation function using the well-known name "_"
|
||||
_ = _translators.primary
|
||||
|
||||
# Translators for log levels.
|
||||
#
|
||||
# The abbreviated names are meant to reflect the usual use of a short
|
||||
# name like '_'. The "L" is for "log" and the other letter comes from
|
||||
# the level.
|
||||
_LI = _translators.log_info
|
||||
_LW = _translators.log_warning
|
||||
_LE = _translators.log_error
|
||||
_LC = _translators.log_critical
|
||||
# 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.
|
||||
|
||||
"""oslo.i18n integration module.
|
||||
|
||||
See http://docs.openstack.org/developer/oslo.i18n/usage.html
|
||||
|
||||
"""
|
||||
|
||||
import oslo_i18n
|
||||
|
||||
_translators = oslo_i18n.TranslatorFactory(domain='karborclient')
|
||||
|
||||
# The primary translation function using the well-known name "_"
|
||||
_ = _translators.primary
|
||||
|
||||
# Translators for log levels.
|
||||
#
|
||||
# The abbreviated names are meant to reflect the usual use of a short
|
||||
# name like '_'. The "L" is for "log" and the other letter comes from
|
||||
# the level.
|
||||
_LI = _translators.log_info
|
||||
_LW = _translators.log_warning
|
||||
_LE = _translators.log_error
|
||||
_LC = _translators.log_critical
|
||||
|
||||
|
||||
def get_available_languages():
|
||||
return oslo_i18n.get_available_languages('karborclient')
|
||||
@@ -11,7 +11,7 @@
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
Command-line interface to the Smaug Project.
|
||||
Command-line interface to the karbor Project.
|
||||
"""
|
||||
|
||||
from __future__ import print_function
|
||||
@@ -28,18 +28,21 @@ from keystoneclient import session as ksession
|
||||
from oslo_log import handlers
|
||||
from oslo_log import log as logging
|
||||
from oslo_utils import encodeutils
|
||||
from oslo_utils import importutils
|
||||
|
||||
import six
|
||||
import six.moves.urllib.parse as urlparse
|
||||
|
||||
import smaugclient
|
||||
from smaugclient import client as smaug_client
|
||||
from smaugclient.common import utils
|
||||
from smaugclient.openstack.common.apiclient import exceptions as exc
|
||||
import karborclient
|
||||
from karborclient import client as karbor_client
|
||||
from karborclient.common.apiclient import exceptions as exc
|
||||
from karborclient.common import utils
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SmaugShell(object):
|
||||
class KarborShell(object):
|
||||
|
||||
def _append_global_identity_args(self, parser):
|
||||
# Register the CLI arguments that have moved to the session object.
|
||||
@@ -50,9 +53,9 @@ class SmaugShell(object):
|
||||
def get_base_parser(self):
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog='smaug',
|
||||
prog='karbor',
|
||||
description=__doc__.strip(),
|
||||
epilog='See "smaug help COMMAND" '
|
||||
epilog='See "karbor help COMMAND" '
|
||||
'for help on a specific command.',
|
||||
add_help=False,
|
||||
formatter_class=HelpFormatter,
|
||||
@@ -65,13 +68,13 @@ class SmaugShell(object):
|
||||
|
||||
parser.add_argument('--version',
|
||||
action='version',
|
||||
version=smaugclient.__version__,
|
||||
version=karborclient.__version__,
|
||||
help="Show program's version number and exit.")
|
||||
|
||||
parser.add_argument('-d', '--debug',
|
||||
default=bool(utils.env('SMAUGCLIENT_DEBUG')),
|
||||
default=bool(utils.env('KARBORCLIENT_DEBUG')),
|
||||
action='store_true',
|
||||
help='Defaults to env[SMAUGCLIENT_DEBUG].')
|
||||
help='Defaults to env[KARBORCLIENT_DEBUG].')
|
||||
|
||||
parser.add_argument('-v', '--verbose',
|
||||
default=False, action="store_true",
|
||||
@@ -117,14 +120,14 @@ class SmaugShell(object):
|
||||
action='store_true',
|
||||
help="Do not contact keystone for a token. "
|
||||
"Defaults to env[OS_NO_CLIENT_AUTH].")
|
||||
parser.add_argument('--smaug-url',
|
||||
default=utils.env('SMAUG_URL'),
|
||||
help='Defaults to env[SMAUG_URL].')
|
||||
parser.add_argument('--karbor-url',
|
||||
default=utils.env('KARBOR_URL'),
|
||||
help='Defaults to env[KARBOR_URL].')
|
||||
|
||||
parser.add_argument('--smaug-api-version',
|
||||
parser.add_argument('--karbor-api-version',
|
||||
default=utils.env(
|
||||
'SMAUG_API_VERSION', default='1'),
|
||||
help='Defaults to env[SMAUG_API_VERSION] '
|
||||
'KARBOR_API_VERSION', default='1'),
|
||||
help='Defaults to env[KARBOR_API_VERSION] '
|
||||
'or 1.')
|
||||
|
||||
parser.add_argument('--os-service-type',
|
||||
@@ -136,9 +139,9 @@ class SmaugShell(object):
|
||||
help='Defaults to env[OS_ENDPOINT_TYPE].')
|
||||
|
||||
parser.add_argument('--include-password',
|
||||
default=bool(utils.env('SMAUG_INCLUDE_PASSWORD')),
|
||||
default=bool(utils.env('KARBOR_INCLUDE_PASSWORD')),
|
||||
action='store_true',
|
||||
help='Send os-username and os-password to smaug.')
|
||||
help='Send os-username and os-password to karbor.')
|
||||
|
||||
self._append_global_identity_args(parser)
|
||||
|
||||
@@ -149,7 +152,9 @@ class SmaugShell(object):
|
||||
|
||||
self.subcommands = {}
|
||||
subparsers = parser.add_subparsers(metavar='<subcommand>')
|
||||
submodule = utils.import_versioned_module(version, 'shell')
|
||||
submodule = importutils.import_versioned_module(
|
||||
'karborclient', version, 'shell'
|
||||
)
|
||||
self._find_actions(subparsers, submodule)
|
||||
self._find_actions(subparsers, self)
|
||||
|
||||
@@ -289,7 +294,7 @@ class SmaugShell(object):
|
||||
self._setup_logging(options.debug)
|
||||
|
||||
# build available subcommands based on version
|
||||
api_version = options.smaug_api_version
|
||||
api_version = options.karbor_api_version
|
||||
subcommand_parser = self.get_subcommand_parser(api_version)
|
||||
self.parser = subcommand_parser
|
||||
|
||||
@@ -320,11 +325,11 @@ class SmaugShell(object):
|
||||
" env[OS_AUTH_TOKEN]")
|
||||
|
||||
if args.os_no_client_auth:
|
||||
if not args.smaug_url:
|
||||
if not args.karbor_url:
|
||||
raise exc.CommandError(
|
||||
"If you specify --os-no-client-auth"
|
||||
" you must also specify a Smaug API URL"
|
||||
" via either --smaug-url or env[SMAUG_URL]")
|
||||
" you must also specify a Karbor API URL"
|
||||
" via either --karbor-url or env[KARBOR_URL]")
|
||||
|
||||
else:
|
||||
# Tenant name or ID is needed to make keystoneclient retrieve a
|
||||
@@ -343,10 +348,10 @@ class SmaugShell(object):
|
||||
" either --os-auth-url or via"
|
||||
" env[OS_AUTH_URL]")
|
||||
|
||||
endpoint = args.smaug_url
|
||||
endpoint = args.karbor_url
|
||||
|
||||
if args.os_no_client_auth:
|
||||
# Authenticate through smaug, don't use session
|
||||
# Authenticate through karbor, don't use session
|
||||
kwargs = {
|
||||
'username': args.os_username,
|
||||
'password': args.os_password,
|
||||
@@ -380,13 +385,12 @@ class SmaugShell(object):
|
||||
project_domain_name=args.os_project_domain_name)
|
||||
|
||||
endpoint_type = args.os_endpoint_type or 'publicURL'
|
||||
service_type = args.os_service_type or 'application-catalog'
|
||||
service_type = args.os_service_type or 'data-protect'
|
||||
|
||||
if not endpoint:
|
||||
endpoint = keystone_auth.get_endpoint(
|
||||
keystone_session,
|
||||
service_type=service_type,
|
||||
region_name=args.os_region_name)
|
||||
endpoint = keystone_auth.get_endpoint(
|
||||
keystone_session,
|
||||
service_type=service_type,
|
||||
region_name=args.os_region_name)
|
||||
|
||||
kwargs = {
|
||||
'session': keystone_session,
|
||||
@@ -399,7 +403,7 @@ class SmaugShell(object):
|
||||
if args.api_timeout:
|
||||
kwargs['timeout'] = args.api_timeout
|
||||
|
||||
client = smaug_client.Client(api_version, endpoint, **kwargs)
|
||||
client = karbor_client.Client(api_version, endpoint, **kwargs)
|
||||
|
||||
args.func(client, args)
|
||||
|
||||
@@ -441,10 +445,10 @@ class HelpFormatter(argparse.HelpFormatter):
|
||||
|
||||
def main(args=sys.argv[1:]):
|
||||
try:
|
||||
SmaugShell().main(args)
|
||||
KarborShell().main(args)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print('... terminating smaug client', file=sys.stderr)
|
||||
print('... terminating karbor client', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
if '--debug' in args or '-d' in args:
|
||||
@@ -55,6 +55,9 @@ class TestResponse(requests.Response):
|
||||
def __eq__(self, other):
|
||||
return self.__dict__ == other.__dict__
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self.__eq__(other)
|
||||
|
||||
@property
|
||||
def text(self):
|
||||
return self._text
|
||||
@@ -16,12 +16,12 @@ import socket
|
||||
import mock
|
||||
import testtools
|
||||
|
||||
from smaugclient.common import http
|
||||
from smaugclient.openstack.common.apiclient import exceptions as exc
|
||||
from smaugclient.tests.unit import fakes
|
||||
from karborclient.common.apiclient import exceptions as exc
|
||||
from karborclient.common import http
|
||||
from karborclient.tests.unit import fakes
|
||||
|
||||
|
||||
@mock.patch('smaugclient.common.http.requests.request')
|
||||
@mock.patch('karborclient.common.http.requests.request')
|
||||
class HttpClientTest(testtools.TestCase):
|
||||
|
||||
# Patch os.environ to avoid required auth info.
|
||||
@@ -29,7 +29,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
super(HttpClientTest, self).setUp()
|
||||
|
||||
def test_http_raw_request(self, mock_request):
|
||||
headers = {'User-Agent': 'python-smaugclient'}
|
||||
headers = {'User-Agent': 'python-karborclient'}
|
||||
mock_request.return_value = \
|
||||
fakes.FakeHTTPResponse(
|
||||
200, 'OK',
|
||||
@@ -71,15 +71,15 @@ class HttpClientTest(testtools.TestCase):
|
||||
mock_request.assert_has_calls([
|
||||
mock.call('GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'User-Agent': 'python-smaugclient'}),
|
||||
headers={'User-Agent': 'python-karborclient'}),
|
||||
mock.call('GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'User-Agent': 'python-smaugclient',
|
||||
headers={'User-Agent': 'python-karborclient',
|
||||
'X-Auth-Key': 'pass',
|
||||
'X-Auth-User': 'user'}),
|
||||
mock.call('GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'User-Agent': 'python-smaugclient',
|
||||
headers={'User-Agent': 'python-karborclient',
|
||||
'X-Auth-Token': 'abcd1234'})
|
||||
])
|
||||
|
||||
@@ -101,7 +101,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
'GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'X-Region-Name': 'RegionOne',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_json_request(self, mock_request):
|
||||
# Record a 200
|
||||
@@ -119,7 +119,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
'GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_json_request_argument_passed_to_requests(self, mock_request):
|
||||
"""Check that we have sent the proper arguments to requests."""
|
||||
@@ -147,7 +147,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
data='"text"',
|
||||
headers={'Content-Type': 'application/json',
|
||||
'X-Auth-Url': 'http://AUTH_URL',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_json_request_w_req_body(self, mock_request):
|
||||
# Record a 200
|
||||
@@ -166,7 +166,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
data='"test-body"',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_json_request_non_json_resp_cont_type(self, mock_request):
|
||||
# Record a 200
|
||||
@@ -184,7 +184,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
'GET', 'http://example.com:8082', data='"test-data"',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_json_request_invalid_json(self, mock_request):
|
||||
# Record a 200
|
||||
@@ -202,7 +202,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
'GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_manual_redirect_delete(self, mock_request):
|
||||
mock_request.side_effect = [
|
||||
@@ -223,11 +223,11 @@ class HttpClientTest(testtools.TestCase):
|
||||
mock.call('DELETE', 'http://example.com:8082/foo',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'}),
|
||||
'User-Agent': 'python-karborclient'}),
|
||||
mock.call('DELETE', 'http://example.com:8082/foo/bar',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
])
|
||||
|
||||
def test_http_manual_redirect_post(self, mock_request):
|
||||
@@ -249,11 +249,11 @@ class HttpClientTest(testtools.TestCase):
|
||||
mock.call('POST', 'http://example.com:8082/foo',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'}),
|
||||
'User-Agent': 'python-karborclient'}),
|
||||
mock.call('POST', 'http://example.com:8082/foo/bar',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
])
|
||||
|
||||
def test_http_manual_redirect_put(self, mock_request):
|
||||
@@ -275,11 +275,11 @@ class HttpClientTest(testtools.TestCase):
|
||||
mock.call('PUT', 'http://example.com:8082/foo',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'}),
|
||||
'User-Agent': 'python-karborclient'}),
|
||||
mock.call('PUT', 'http://example.com:8082/foo/bar',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
])
|
||||
|
||||
def test_http_manual_redirect_prohibited(self, mock_request):
|
||||
@@ -295,7 +295,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
'DELETE', 'http://example.com:8082/foo',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_manual_redirect_error_without_location(self, mock_request):
|
||||
mock_request.return_value = \
|
||||
@@ -310,7 +310,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
'DELETE', 'http://example.com:8082/foo',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_json_request_redirect(self, mock_request):
|
||||
# Record the 302
|
||||
@@ -333,11 +333,11 @@ class HttpClientTest(testtools.TestCase):
|
||||
mock.call('GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'}),
|
||||
'User-Agent': 'python-karborclient'}),
|
||||
mock.call('GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
])
|
||||
|
||||
def test_http_404_json_request(self, mock_request):
|
||||
@@ -356,7 +356,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
'GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_http_300_json_request(self, mock_request):
|
||||
mock_request.return_value = \
|
||||
@@ -374,10 +374,10 @@ class HttpClientTest(testtools.TestCase):
|
||||
'GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'})
|
||||
'User-Agent': 'python-karborclient'})
|
||||
|
||||
def test_fake_json_request(self, mock_request):
|
||||
headers = {'User-Agent': 'python-smaugclient'}
|
||||
headers = {'User-Agent': 'python-karborclient'}
|
||||
mock_request.side_effect = [socket.gaierror]
|
||||
|
||||
client = http.HTTPClient('fake://example.com:8082')
|
||||
@@ -388,7 +388,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
headers=headers)
|
||||
|
||||
def test_http_request_socket_error(self, mock_request):
|
||||
headers = {'User-Agent': 'python-smaugclient'}
|
||||
headers = {'User-Agent': 'python-karborclient'}
|
||||
mock_request.side_effect = [socket.gaierror]
|
||||
|
||||
client = http.HTTPClient('http://example.com:8082')
|
||||
@@ -399,7 +399,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
headers=headers)
|
||||
|
||||
def test_http_request_socket_timeout(self, mock_request):
|
||||
headers = {'User-Agent': 'python-smaugclient'}
|
||||
headers = {'User-Agent': 'python-karborclient'}
|
||||
mock_request.side_effect = [socket.timeout]
|
||||
|
||||
client = http.HTTPClient('http://example.com:8082')
|
||||
@@ -424,7 +424,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
'GET', 'http://example.com:8082',
|
||||
allow_redirects=False,
|
||||
headers={'Content-Type': 'application/json',
|
||||
'User-Agent': 'python-smaugclient'},
|
||||
'User-Agent': 'python-karborclient'},
|
||||
timeout=float(123))
|
||||
|
||||
def test_get_system_ca_file(self, mock_request):
|
||||
@@ -445,7 +445,7 @@ class HttpClientTest(testtools.TestCase):
|
||||
client = http.HTTPClient('https://foo', cacert="NOWHERE")
|
||||
self.assertEqual("NOWHERE", client.verify_cert)
|
||||
|
||||
with mock.patch('smaugclient.common.http.get_system_ca_file') as gsf:
|
||||
with mock.patch('karborclient.common.http.get_system_ca_file') as gsf:
|
||||
gsf.return_value = "SOMEWHERE"
|
||||
client = http.HTTPClient('https://foo')
|
||||
self.assertEqual("SOMEWHERE", client.verify_cert)
|
||||
@@ -11,13 +11,13 @@
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
Tests for `smaugclient` module.
|
||||
Tests for `karborclient` module.
|
||||
"""
|
||||
|
||||
from smaugclient.tests.unit import base
|
||||
from karborclient.tests.unit import base
|
||||
|
||||
|
||||
class TestSmaugclient(base.TestCaseShell):
|
||||
class TestKarborclient(base.TestCaseShell):
|
||||
|
||||
def test_something(self):
|
||||
pass
|
||||
@@ -23,9 +23,9 @@ from oslo_log import log
|
||||
import six
|
||||
from testtools import matchers
|
||||
|
||||
from smaugclient.openstack.common.apiclient import exceptions
|
||||
import smaugclient.shell
|
||||
from smaugclient.tests.unit import base
|
||||
from karborclient.common.apiclient import exceptions
|
||||
import karborclient.shell
|
||||
from karborclient.tests.unit import base
|
||||
|
||||
|
||||
FAKE_ENV = {'OS_USERNAME': 'username',
|
||||
@@ -51,7 +51,7 @@ def _create_ver_list(versions):
|
||||
|
||||
class TestArgs(object):
|
||||
package_version = ''
|
||||
smaug_repo_url = 'http://127.0.0.1'
|
||||
karbor_repo_url = 'http://127.0.0.1'
|
||||
exists_action = ''
|
||||
is_public = False
|
||||
categories = []
|
||||
@@ -78,7 +78,7 @@ class ShellCommandTest(ShellTest):
|
||||
def get_auth_endpoint(bound_self, args):
|
||||
return ('test', {})
|
||||
self.useFixture(fixtures.MonkeyPatch(
|
||||
'smaugclient.shell.SmaugShell._get_endpoint_and_kwargs',
|
||||
'karborclient.shell.KarborShell._get_endpoint_and_kwargs',
|
||||
get_auth_endpoint))
|
||||
self.client = mock.MagicMock()
|
||||
|
||||
@@ -99,7 +99,7 @@ class ShellCommandTest(ShellTest):
|
||||
try:
|
||||
sys.stdout = six.StringIO()
|
||||
sys.stderr = six.StringIO()
|
||||
_shell = smaugclient.shell.SmaugShell()
|
||||
_shell = karborclient.shell.KarborShell()
|
||||
_shell.main(argstr.split())
|
||||
except SystemExit:
|
||||
exc_type, exc_value, exc_traceback = sys.exc_info()
|
||||
@@ -133,9 +133,9 @@ class ShellCommandTest(ShellTest):
|
||||
|
||||
def test_help(self):
|
||||
required = [
|
||||
'.*?^usage: smaug',
|
||||
'.*?^usage: karbor',
|
||||
'.*?^\s+plan-create\s+Create a plan.',
|
||||
'.*?^See "smaug help COMMAND" for help on a specific command',
|
||||
'.*?^See "karbor help COMMAND" for help on a specific command',
|
||||
]
|
||||
stdout, stderr = self.shell('help')
|
||||
for r in required:
|
||||
@@ -144,7 +144,7 @@ class ShellCommandTest(ShellTest):
|
||||
|
||||
def test_help_on_subcommand(self):
|
||||
required = [
|
||||
'.*?^usage: smaug plan-create',
|
||||
'.*?^usage: karbor plan-create',
|
||||
'.*?^Create a plan.',
|
||||
]
|
||||
stdout, stderr = self.shell('help plan-create')
|
||||
@@ -154,9 +154,9 @@ class ShellCommandTest(ShellTest):
|
||||
|
||||
def test_help_no_options(self):
|
||||
required = [
|
||||
'.*?^usage: smaug',
|
||||
'.*?^usage: karbor',
|
||||
'.*?^\s+plan-create\s+Create a plan',
|
||||
'.*?^See "smaug help COMMAND" for help on a specific command',
|
||||
'.*?^See "karbor help COMMAND" for help on a specific command',
|
||||
]
|
||||
stdout, stderr = self.shell('')
|
||||
for r in required:
|
||||
@@ -15,10 +15,10 @@ try:
|
||||
except ImportError:
|
||||
import urllib.parse as urlparse
|
||||
|
||||
from smaugclient.common import http as base_client
|
||||
from smaugclient.tests.unit import base
|
||||
from smaugclient.tests.unit import fakes
|
||||
from smaugclient.v1 import client
|
||||
from karborclient.common import http as base_client
|
||||
from karborclient.tests.unit import base
|
||||
from karborclient.tests.unit import fakes
|
||||
from karborclient.v1 import client
|
||||
|
||||
|
||||
REQUEST_ID = 'req-test-request-id'
|
||||
@@ -12,8 +12,8 @@
|
||||
|
||||
import mock
|
||||
|
||||
from smaugclient.tests.unit import base
|
||||
from smaugclient.tests.unit.v1 import fakes
|
||||
from karborclient.tests.unit import base
|
||||
from karborclient.tests.unit.v1 import fakes
|
||||
|
||||
cs = fakes.FakeClient()
|
||||
mock_request_return = ({}, {'checkpoint': {}})
|
||||
@@ -24,75 +24,69 @@ FAKE_PLAN_ID = "3330f8b1-975d-4621-a872-fa9afb43cb6c"
|
||||
|
||||
class CheckpointsTest(base.TestCaseShell):
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_checkpoints(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.checkpoints.list(provider_id=FAKE_PROVIDER_ID)
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/providers/{provider_id}/checkpoints'.format(
|
||||
project_id=fakes.PROJECT_ID,
|
||||
'/providers/{provider_id}/checkpoints'.format(
|
||||
provider_id=FAKE_PROVIDER_ID), headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_get_checkpoint(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.checkpoints.get(FAKE_PROVIDER_ID, '1')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/providers/{provider_id}/checkpoints/1'.format(
|
||||
project_id=fakes.PROJECT_ID,
|
||||
'/providers/{provider_id}/checkpoints/1'.format(
|
||||
provider_id=FAKE_PROVIDER_ID), headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.raw_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.raw_request')
|
||||
def test_delete_checkpoint(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.checkpoints.delete(FAKE_PROVIDER_ID, '1')
|
||||
mock_request.assert_called_with(
|
||||
'DELETE',
|
||||
'/v1/{project_id}/providers/{provider_id}/checkpoints/1'.format(
|
||||
project_id=fakes.PROJECT_ID,
|
||||
'/providers/{provider_id}/checkpoints/1'.format(
|
||||
provider_id=FAKE_PROVIDER_ID), headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_checkpoints_with_marker_limit(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.checkpoints.list(provider_id=FAKE_PROVIDER_ID,
|
||||
marker=1234, limit=2)
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/providers/{provider_id}/'
|
||||
'/providers/{provider_id}/'
|
||||
'checkpoints?limit=2&marker=1234'.format(
|
||||
provider_id=FAKE_PROVIDER_ID,
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
provider_id=FAKE_PROVIDER_ID), headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_checkpoints_with_sort_key_dir(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.checkpoints.list(provider_id=FAKE_PROVIDER_ID,
|
||||
sort_key='id', sort_dir='asc')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/providers/{provider_id}/'
|
||||
'/providers/{provider_id}/'
|
||||
'checkpoints?sort_dir=asc&sort_key=id'.format(
|
||||
provider_id=FAKE_PROVIDER_ID,
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
provider_id=FAKE_PROVIDER_ID), headers={})
|
||||
|
||||
def test_list_checkpoints_with_invalid_sort_key(self):
|
||||
self.assertRaises(ValueError,
|
||||
cs.checkpoints.list, FAKE_PROVIDER_ID,
|
||||
sort_key='invalid', sort_dir='asc')
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_create_checkpoint(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.checkpoints.create(FAKE_PROVIDER_ID, FAKE_PLAN_ID)
|
||||
mock_request.assert_called_with(
|
||||
'POST',
|
||||
'/v1/{project_id}/providers/{provider_id}/'
|
||||
'/providers/{provider_id}/'
|
||||
'checkpoints'.format(
|
||||
provider_id=FAKE_PROVIDER_ID,
|
||||
project_id=fakes.PROJECT_ID),
|
||||
provider_id=FAKE_PROVIDER_ID),
|
||||
data={
|
||||
'checkpoint': {'plan_id': FAKE_PLAN_ID}},
|
||||
'checkpoint': {'plan_id': FAKE_PLAN_ID, 'extra-info': None}},
|
||||
headers={})
|
||||
@@ -12,8 +12,8 @@
|
||||
|
||||
import mock
|
||||
|
||||
from smaugclient.tests.unit import base
|
||||
from smaugclient.tests.unit.v1 import fakes
|
||||
from karborclient.tests.unit import base
|
||||
from karborclient.tests.unit.v1 import fakes
|
||||
|
||||
cs = fakes.FakeClient()
|
||||
mock_request_return = ({}, {'plan': {'name': 'fake_name'}})
|
||||
@@ -21,75 +21,77 @@ mock_request_return = ({}, {'plan': {'name': 'fake_name'}})
|
||||
|
||||
class PlansTest(base.TestCaseShell):
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_plans_with_marker_limit(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.plans.list(marker=1234, limit=2)
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/plans?limit=2&marker=1234'.format(
|
||||
'/plans?limit=2&marker=1234'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_plans_with_sort_key_dir(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.plans.list(sort_key='id', sort_dir='asc')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/plans?'
|
||||
'/plans?'
|
||||
'sort_dir=asc&sort_key=id'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_plans_with_invalid_sort_key(self, mock_request):
|
||||
self.assertRaises(ValueError,
|
||||
cs.plans.list, sort_key='invalid', sort_dir='asc')
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_create_plan(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.plans.create('Plan name', 'provider_id', '')
|
||||
cs.plans.create('Plan name', 'provider_id', '', "", '')
|
||||
mock_request.assert_called_with(
|
||||
'POST',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/plans',
|
||||
'/plans',
|
||||
data={
|
||||
'plan': {'provider_id': 'provider_id',
|
||||
'name': 'Plan name',
|
||||
'resources': ''}},
|
||||
'resources': '',
|
||||
'parameters': '',
|
||||
'description': ''}},
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.raw_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.raw_request')
|
||||
def test_delete_plan(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.plans.delete('1')
|
||||
mock_request.assert_called_with(
|
||||
'DELETE',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/plans/1',
|
||||
'/plans/1',
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_create_update(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.plans.update('1', {'name': 'Test name.'})
|
||||
mock_request.assert_called_with(
|
||||
'PUT',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/plans/1',
|
||||
'/plans/1',
|
||||
data={'plan': {'name': 'Test name.'}}, headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_show_plan(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.plans.get('1')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/plans/1',
|
||||
'/plans/1',
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_show_plan_with_headers(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.plans.get('1', session_id='fake_session_id')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/plans/1',
|
||||
'/plans/1',
|
||||
headers={'X-Configuration-Session': 'fake_session_id'})
|
||||
@@ -12,64 +12,70 @@
|
||||
|
||||
import mock
|
||||
|
||||
from smaugclient.tests.unit import base
|
||||
from smaugclient.tests.unit.v1 import fakes
|
||||
from karborclient.tests.unit import base
|
||||
from karborclient.tests.unit.v1 import fakes
|
||||
|
||||
cs = fakes.FakeClient()
|
||||
mock_request_return = ({}, {'protectable_type': {}})
|
||||
mock_instances_request_return = ({}, {'instances': {}})
|
||||
mock_instance_request_return = ({}, {'instance': {}})
|
||||
|
||||
|
||||
class ProtectablesTest(base.TestCaseShell):
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_protectables(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.protectables.list()
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/protectables'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/protectables', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_get_protectables(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.protectables.get('OS::Cinder::Volume')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/protectables/OS::Cinder::Volume'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/protectables/OS::Cinder::Volume', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_get_protectables_instance(self, mock_request):
|
||||
mock_request.return_value = mock_instance_request_return
|
||||
cs.protectables.get_instance('OS::Cinder::Volume', '1')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/protectables/OS::Cinder::Volume/'
|
||||
'instances/1', headers={})
|
||||
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_protectables_instances(self, mock_request):
|
||||
mock_request.return_value = mock_instances_request_return
|
||||
cs.protectables.list_instances('OS::Cinder::Volume')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/protectables/OS::Cinder::Volume/'
|
||||
'instances'.format(project_id=fakes.PROJECT_ID), headers={})
|
||||
'/protectables/OS::Cinder::Volume/'
|
||||
'instances', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_protectables_instances_with_marker_limit(self, mock_request):
|
||||
mock_request.return_value = mock_instances_request_return
|
||||
cs.protectables.list_instances('OS::Cinder::Volume',
|
||||
marker=1234, limit=2)
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/protectables/OS::Cinder::Volume/'
|
||||
'instances?limit=2&marker=1234'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/protectables/OS::Cinder::Volume/'
|
||||
'instances?limit=2&marker=1234', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_protectables_instances_with_sort_key_dir(self, mock_request):
|
||||
mock_request.return_value = mock_instances_request_return
|
||||
cs.protectables.list_instances('OS::Cinder::Volume',
|
||||
sort_key='id', sort_dir='asc')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/protectables/OS::Cinder::Volume/'
|
||||
'instances?sort_dir=asc&sort_key=id'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/protectables/OS::Cinder::Volume/'
|
||||
'instances?sort_dir=asc&sort_key=id', headers={})
|
||||
|
||||
def test_list_protectables_instances_with_invalid_sort_key(self):
|
||||
self.assertRaises(ValueError,
|
||||
@@ -12,8 +12,8 @@
|
||||
|
||||
import mock
|
||||
|
||||
from smaugclient.tests.unit import base
|
||||
from smaugclient.tests.unit.v1 import fakes
|
||||
from karborclient.tests.unit import base
|
||||
from karborclient.tests.unit.v1 import fakes
|
||||
|
||||
cs = fakes.FakeClient()
|
||||
mock_request_return = ({}, {'provider': {}})
|
||||
@@ -21,43 +21,39 @@ mock_request_return = ({}, {'provider': {}})
|
||||
|
||||
class ProvidersTest(base.TestCaseShell):
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_get_providers(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.providers.get('2220f8b1-975d-4621-a872-fa9afb43cb6c')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/providers/'
|
||||
'2220f8b1-975d-4621-a872-fa9afb43cb6c'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/providers/'
|
||||
'2220f8b1-975d-4621-a872-fa9afb43cb6c', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_providers(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.providers.list()
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/providers'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/providers', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_providers_with_marker_limit(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.providers.list(marker=1234, limit=2)
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/providers?limit=2&marker=1234'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/providers?limit=2&marker=1234', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_providers_with_sort_key_dir(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.providers.list(sort_key='id', sort_dir='asc')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/providers?'
|
||||
'sort_dir=asc&sort_key=id'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/providers?'
|
||||
'sort_dir=asc&sort_key=id', headers={})
|
||||
|
||||
def test_list_providers_with_invalid_sort_key(self):
|
||||
self.assertRaises(ValueError,
|
||||
@@ -12,8 +12,8 @@
|
||||
|
||||
import mock
|
||||
|
||||
from smaugclient.tests.unit import base
|
||||
from smaugclient.tests.unit.v1 import fakes
|
||||
from karborclient.tests.unit import base
|
||||
from karborclient.tests.unit.v1 import fakes
|
||||
|
||||
cs = fakes.FakeClient()
|
||||
mock_request_return = ({}, {'restore': {}})
|
||||
@@ -21,63 +21,65 @@ mock_request_return = ({}, {'restore': {}})
|
||||
|
||||
class RestoresTest(base.TestCaseShell):
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_restores_with_marker_limit(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.restores.list(marker=1234, limit=2)
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/restores?limit=2&marker=1234'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/restores?limit=2&marker=1234', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_restores_with_sort_key_dir(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.restores.list(sort_key='id', sort_dir='asc')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/restores?'
|
||||
'sort_dir=asc&sort_key=id'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/restores?'
|
||||
'sort_dir=asc&sort_key=id', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_plans_with_invalid_sort_key(self, mock_request):
|
||||
self.assertRaises(ValueError,
|
||||
cs.restores.list, sort_key='invalid', sort_dir='asc')
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_create_restore(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.restores.create('586cc6ce-e286-40bd-b2b5-dd32694d9944',
|
||||
'2220f8b1-975d-4621-a872-fa9afb43cb6c',
|
||||
'192.168.1.2:35357/v2.0',
|
||||
'{"username": "admin"}')
|
||||
'{}',
|
||||
'{"type": "password", "username": "admin", '
|
||||
'"password": "test"}')
|
||||
mock_request.assert_called_with(
|
||||
'POST',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/restores',
|
||||
'/restores',
|
||||
data={
|
||||
'restore':
|
||||
{
|
||||
'checkpoint_id': '2220f8b1-975d-4621-a872-fa9afb43cb6c',
|
||||
'parameters': '{"username": "admin"}',
|
||||
'parameters': '{}',
|
||||
'provider_id': '586cc6ce-e286-40bd-b2b5-dd32694d9944',
|
||||
'restore_target': '192.168.1.2:35357/v2.0'
|
||||
'restore_target': '192.168.1.2:35357/v2.0',
|
||||
'restore_auth': '{"type": "password", "username": '
|
||||
'"admin", "password": "test"}'
|
||||
}}, headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_show_restore(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.restores.get('1')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/restores/1',
|
||||
'/restores/1',
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_show_restore_with_headers(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.restores.get('1', session_id='fake_session_id')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/restores/1',
|
||||
'/restores/1',
|
||||
headers={'X-Configuration-Session': 'fake_session_id'})
|
||||
@@ -12,8 +12,8 @@
|
||||
|
||||
import mock
|
||||
|
||||
from smaugclient.tests.unit import base
|
||||
from smaugclient.tests.unit.v1 import fakes
|
||||
from karborclient.tests.unit import base
|
||||
from karborclient.tests.unit.v1 import fakes
|
||||
|
||||
cs = fakes.FakeClient()
|
||||
mock_request_return = ({}, {'scheduled_operation': {'name': 'fake_name'}})
|
||||
@@ -21,33 +21,31 @@ mock_request_return = ({}, {'scheduled_operation': {'name': 'fake_name'}})
|
||||
|
||||
class ScheduledOperationsTest(base.TestCaseShell):
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_scheduled_operations_with_marker_limit(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.scheduled_operations.list(marker=1234, limit=2)
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/scheduled_operations?limit=2&marker=1234'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/scheduled_operations?limit=2&marker=1234', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list__scheduled_operations_with_sort_key_dir(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.scheduled_operations.list(sort_key='id', sort_dir='asc')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/scheduled_operations?'
|
||||
'sort_dir=asc&sort_key=id'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/scheduled_operations?'
|
||||
'sort_dir=asc&sort_key=id', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_scheduled_operations_with_invalid_sort_key(self,
|
||||
mock_request):
|
||||
self.assertRaises(ValueError,
|
||||
cs.scheduled_operations.list, sort_key='invalid',
|
||||
sort_dir='asc')
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_create_scheduled_operation(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.scheduled_operations.create(
|
||||
@@ -56,7 +54,7 @@ class ScheduledOperationsTest(base.TestCaseShell):
|
||||
'operation_definition')
|
||||
mock_request.assert_called_with(
|
||||
'POST',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/scheduled_operations',
|
||||
'/scheduled_operations',
|
||||
data={
|
||||
'scheduled_operation': {
|
||||
'name': 'name',
|
||||
@@ -65,29 +63,29 @@ class ScheduledOperationsTest(base.TestCaseShell):
|
||||
'operation_definition': 'operation_definition'}},
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.raw_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.raw_request')
|
||||
def test_delete_scheduled_operation(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.scheduled_operations.delete('1')
|
||||
mock_request.assert_called_with(
|
||||
'DELETE',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/scheduled_operations/1',
|
||||
'/scheduled_operations/1',
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_show_scheduled_operation(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.scheduled_operations.get('1')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/scheduled_operations/1',
|
||||
'/scheduled_operations/1',
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_show_scheduled_operation_with_headers(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.scheduled_operations.get('1', session_id='fake_session_id')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/scheduled_operations/1',
|
||||
'/scheduled_operations/1',
|
||||
headers={'X-Configuration-Session': 'fake_session_id'})
|
||||
@@ -12,8 +12,8 @@
|
||||
|
||||
import mock
|
||||
|
||||
from smaugclient.tests.unit import base
|
||||
from smaugclient.tests.unit.v1 import fakes
|
||||
from karborclient.tests.unit import base
|
||||
from karborclient.tests.unit.v1 import fakes
|
||||
|
||||
cs = fakes.FakeClient()
|
||||
mock_request_return = ({}, {'trigger_info': {'name': 'fake_name'}})
|
||||
@@ -21,66 +21,79 @@ mock_request_return = ({}, {'trigger_info': {'name': 'fake_name'}})
|
||||
|
||||
class TriggersTest(base.TestCaseShell):
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_triggers_with_marker_limit(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.triggers.list(marker=1234, limit=2)
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/triggers?limit=2&marker=1234'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/triggers?limit=2&marker=1234', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_triggers_with_sort_key_dir(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.triggers.list(sort_key='id', sort_dir='asc')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/{project_id}/triggers?'
|
||||
'sort_dir=asc&sort_key=id'.format(
|
||||
project_id=fakes.PROJECT_ID), headers={})
|
||||
'/triggers?'
|
||||
'sort_dir=asc&sort_key=id', headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_list_triggers_with_invalid_sort_key(self, mock_request):
|
||||
self.assertRaises(ValueError,
|
||||
cs.triggers.list, sort_key='invalid', sort_dir='asc')
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_create_trigger(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.triggers.create('name', 'time', 'properties')
|
||||
mock_request.assert_called_with(
|
||||
'POST',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/triggers',
|
||||
'/triggers',
|
||||
data={
|
||||
'trigger_info': {'name': 'name',
|
||||
'type': 'time',
|
||||
'properties': 'properties'}},
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.raw_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.raw_request')
|
||||
def test_delete_trigger(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.triggers.delete('1')
|
||||
mock_request.assert_called_with(
|
||||
'DELETE',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/triggers/1',
|
||||
'/triggers/1',
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
def test_show_plan(self, mock_request):
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_show_trigger(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.triggers.get('1')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/triggers/1',
|
||||
'/triggers/1',
|
||||
headers={})
|
||||
|
||||
@mock.patch('smaugclient.common.http.HTTPClient.json_request')
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_show_trigger_with_headers(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
cs.triggers.get('1', session_id='fake_session_id')
|
||||
mock_request.assert_called_with(
|
||||
'GET',
|
||||
'/v1/efc6a88b-9096-4bb6-8634-cda182a6e12a/triggers/1',
|
||||
'/triggers/1',
|
||||
headers={'X-Configuration-Session': 'fake_session_id'})
|
||||
|
||||
@mock.patch('karborclient.common.http.HTTPClient.json_request')
|
||||
def test_update_trigger(self, mock_request):
|
||||
mock_request.return_value = mock_request_return
|
||||
trigger_id = '123'
|
||||
data = {"name": "My Trigger",
|
||||
"properties": {"pattern": "0 10 * * *", "format": "crontab"}}
|
||||
body = {"trigger_info": data}
|
||||
cs.triggers.update(trigger_id, data)
|
||||
mock_request.assert_called_with(
|
||||
'PUT',
|
||||
'/triggers/123',
|
||||
data=body,
|
||||
headers={}
|
||||
)
|
||||
@@ -12,31 +12,40 @@
|
||||
|
||||
from six.moves.urllib import parse
|
||||
|
||||
from smaugclient.common import base
|
||||
from karborclient.common import base
|
||||
|
||||
|
||||
class Checkpoint(base.Resource):
|
||||
def __repr__(self):
|
||||
return "<Checkpoint %s>" % self._info
|
||||
|
||||
def data(self, **kwargs):
|
||||
return self.manager.data(self, **kwargs)
|
||||
def get(self):
|
||||
self.set_loaded(True)
|
||||
if not hasattr(self.manager, 'get'):
|
||||
return
|
||||
plan = self.protection_plan
|
||||
if plan is not None:
|
||||
provider_id = plan.get("provider_id", None)
|
||||
new = self.manager.get(provider_id, self.id)
|
||||
if new:
|
||||
self._add_details(new._info)
|
||||
else:
|
||||
return
|
||||
|
||||
|
||||
class CheckpointManager(base.ManagerWithFind):
|
||||
resource_class = Checkpoint
|
||||
|
||||
def create(self, provider_id, plan_id):
|
||||
body = {'checkpoint': {'plan_id': plan_id}}
|
||||
url = "/v1/{project_id}/providers/{provider_id}/" \
|
||||
"checkpoints" .format(project_id=self.project_id,
|
||||
provider_id=provider_id)
|
||||
return self._create(url, body, 'checkpoint', return_raw=True)
|
||||
def create(self, provider_id, plan_id, checkpoint_extra_info=None):
|
||||
body = {'checkpoint': {'plan_id': plan_id,
|
||||
'extra-info': checkpoint_extra_info}}
|
||||
url = "/providers/{provider_id}/" \
|
||||
"checkpoints" .format(provider_id=provider_id)
|
||||
return self._create(url, body, 'checkpoint')
|
||||
|
||||
def delete(self, provider_id, checkpoint_id):
|
||||
path = '/v1/{project_id}/providers/{provider_id}/checkpoints/' \
|
||||
'{checkpoint_id}'.format(project_id=self.project_id,
|
||||
provider_id=provider_id,
|
||||
path = '/providers/{provider_id}/checkpoints/' \
|
||||
'{checkpoint_id}'.format(provider_id=provider_id,
|
||||
checkpoint_id=checkpoint_id)
|
||||
return self._delete(path)
|
||||
|
||||
@@ -45,9 +54,8 @@ class CheckpointManager(base.ManagerWithFind):
|
||||
headers = {'X-Configuration-Session': session_id}
|
||||
else:
|
||||
headers = {}
|
||||
url = '/v1/{project_id}/providers/{provider_id}/checkpoints/' \
|
||||
'{checkpoint_id}'.format(project_id=self.project_id,
|
||||
provider_id=provider_id,
|
||||
url = '/providers/{provider_id}/checkpoints/' \
|
||||
'{checkpoint_id}'.format(provider_id=provider_id,
|
||||
checkpoint_id=checkpoint_id)
|
||||
return self._get(url, response_key="checkpoint", headers=headers)
|
||||
|
||||
@@ -111,8 +119,7 @@ class CheckpointManager(base.ManagerWithFind):
|
||||
params = sorted(query_params.items(), key=lambda x: x[0])
|
||||
query_string = "?%s" % parse.urlencode(params)
|
||||
|
||||
return ("/v1/%(project_id)s/providers/%(provider_id)s"
|
||||
return ("/providers/%(provider_id)s"
|
||||
"/checkpoints%(query_string)s" %
|
||||
{"project_id": self.project_id,
|
||||
"provider_id": provider_id,
|
||||
{"provider_id": provider_id,
|
||||
"query_string": query_string})
|
||||
@@ -12,18 +12,18 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from smaugclient.common import http
|
||||
from smaugclient.v1 import checkpoints
|
||||
from smaugclient.v1 import plans
|
||||
from smaugclient.v1 import protectables
|
||||
from smaugclient.v1 import providers
|
||||
from smaugclient.v1 import restores
|
||||
from smaugclient.v1 import scheduled_operations
|
||||
from smaugclient.v1 import triggers
|
||||
from karborclient.common import http
|
||||
from karborclient.v1 import checkpoints
|
||||
from karborclient.v1 import plans
|
||||
from karborclient.v1 import protectables
|
||||
from karborclient.v1 import providers
|
||||
from karborclient.v1 import restores
|
||||
from karborclient.v1 import scheduled_operations
|
||||
from karborclient.v1 import triggers
|
||||
|
||||
|
||||
class Client(object):
|
||||
"""Client for the Smaug v1 API.
|
||||
"""Client for the karbor v1 API.
|
||||
|
||||
:param string endpoint: A user-supplied endpoint URL for the service.
|
||||
:param string token: Token for authentication.
|
||||
@@ -32,7 +32,7 @@ class Client(object):
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize a new client for the Smaug v1 API."""
|
||||
"""Initialize a new client for the karbor v1 API."""
|
||||
self.http_client = http._construct_http_client(*args, **kwargs)
|
||||
self.plans = plans.PlanManager(self.http_client)
|
||||
self.restores = restores.RestoreManager(self.http_client)
|
||||
@@ -10,41 +10,38 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from smaugclient.common import base
|
||||
from karborclient.common import base
|
||||
|
||||
|
||||
class Plan(base.Resource):
|
||||
def __repr__(self):
|
||||
return "<Plan %s>" % self._info
|
||||
|
||||
def data(self, **kwargs):
|
||||
return self.manager.data(self, **kwargs)
|
||||
|
||||
|
||||
class PlanManager(base.ManagerWithFind):
|
||||
resource_class = Plan
|
||||
|
||||
def create(self, name, provider_id, resources):
|
||||
def create(self, name, provider_id, resources, parameters,
|
||||
description=None):
|
||||
body = {'plan': {'name': name,
|
||||
'description': description,
|
||||
'provider_id': provider_id,
|
||||
'resources': resources,
|
||||
'parameters': parameters
|
||||
}}
|
||||
url = "/v1/{project_id}/plans" .format(
|
||||
project_id=self.project_id)
|
||||
return self._create(url, body, 'plan', return_raw=True)
|
||||
url = "/plans"
|
||||
return self._create(url, body, 'plan')
|
||||
|
||||
def update(self, plan_id, data):
|
||||
|
||||
body = {"plan": data}
|
||||
|
||||
return self._update('/v1/{project_id}/plans/{plan_id}'
|
||||
.format(project_id=self.project_id,
|
||||
plan_id=plan_id),
|
||||
return self._update('/plans/{plan_id}'
|
||||
.format(plan_id=plan_id),
|
||||
body, "plan")
|
||||
|
||||
def delete(self, plan_id):
|
||||
path = '/v1/{project_id}/plans/{plan_id}'.format(
|
||||
project_id=self.project_id,
|
||||
path = '/plans/{plan_id}'.format(
|
||||
plan_id=plan_id)
|
||||
return self._delete(path)
|
||||
|
||||
@@ -53,8 +50,7 @@ class PlanManager(base.ManagerWithFind):
|
||||
headers = {'X-Configuration-Session': session_id}
|
||||
else:
|
||||
headers = {}
|
||||
url = "/v1/{project_id}/plans/{plan_id}".format(
|
||||
project_id=self.project_id,
|
||||
url = "/plans/{plan_id}".format(
|
||||
plan_id=plan_id)
|
||||
return self._get(url, response_key="plan", headers=headers)
|
||||
|
||||
@@ -12,15 +12,17 @@
|
||||
|
||||
from six.moves.urllib import parse
|
||||
|
||||
from smaugclient.common import base
|
||||
from karborclient.common import base
|
||||
|
||||
|
||||
class Protectable(base.Resource):
|
||||
def __repr__(self):
|
||||
return "<Protectable %s>" % self._info
|
||||
|
||||
def data(self, **kwargs):
|
||||
return self.manager.data(self, **kwargs)
|
||||
|
||||
class Instances(base.Resource):
|
||||
def __repr__(self):
|
||||
return "<Instances %s>" % self._info
|
||||
|
||||
|
||||
class ProtectableManager(base.ManagerWithFind):
|
||||
@@ -31,14 +33,12 @@ class ProtectableManager(base.ManagerWithFind):
|
||||
headers = {'X-Configuration-Session': session_id}
|
||||
else:
|
||||
headers = {}
|
||||
url = "/v1/{project_id}/protectables/{protectable_type}".format(
|
||||
project_id=self.project_id,
|
||||
url = "/protectables/{protectable_type}".format(
|
||||
protectable_type=protectable_type)
|
||||
return self._get(url, response_key="protectable_type", headers=headers)
|
||||
|
||||
def list(self):
|
||||
url = "/v1/{project_id}/protectables".format(
|
||||
project_id=self.project_id)
|
||||
url = "/protectables"
|
||||
protectables = self._list(url, 'protectable_type', return_raw=True)
|
||||
|
||||
protectables_list = []
|
||||
@@ -61,7 +61,7 @@ class ProtectableManager(base.ManagerWithFind):
|
||||
:param sort_dir: Sort direction, should be 'desc' or 'asc'; deprecated
|
||||
in kilo
|
||||
:param sort: Sort information
|
||||
:rtype: list of :class:`Protectable`
|
||||
:rtype: list of :class:`Instances`
|
||||
"""
|
||||
|
||||
url = self._build_instances_list_url(
|
||||
@@ -69,7 +69,30 @@ class ProtectableManager(base.ManagerWithFind):
|
||||
search_opts=search_opts, marker=marker,
|
||||
limit=limit, sort_key=sort_key,
|
||||
sort_dir=sort_dir, sort=sort)
|
||||
return self._list(url, 'instances')
|
||||
return self._list(url, response_key='instances', obj_class=Instances)
|
||||
|
||||
def get_instance(self, type, id, search_opts=None, session_id=None):
|
||||
if session_id:
|
||||
headers = {'X-Configuration-Session': session_id}
|
||||
else:
|
||||
headers = {}
|
||||
|
||||
if search_opts is None:
|
||||
search_opts = {}
|
||||
query_params = {}
|
||||
for key, val in search_opts.items():
|
||||
if val:
|
||||
query_params[key] = val
|
||||
query_string = ""
|
||||
if query_params:
|
||||
params = sorted(query_params.items(), key=lambda x: x[0])
|
||||
query_string = "?%s" % parse.urlencode(params)
|
||||
|
||||
url = ("/protectables/{protectable_type}/instances/"
|
||||
"{protectable_id}{query_string}").format(
|
||||
protectable_type=type, protectable_id=id,
|
||||
query_string=query_string)
|
||||
return self._get(url, response_key="instance", headers=headers)
|
||||
|
||||
def _build_instances_list_url(self, protectable_type,
|
||||
search_opts=None, marker=None, limit=None,
|
||||
@@ -108,8 +131,7 @@ class ProtectableManager(base.ManagerWithFind):
|
||||
params = sorted(query_params.items(), key=lambda x: x[0])
|
||||
query_string = "?%s" % parse.urlencode(params)
|
||||
|
||||
return ("/v1/%(project_id)s/protectables/%(protectable_type)s"
|
||||
return ("/protectables/%(protectable_type)s"
|
||||
"/instances%(query_string)s" %
|
||||
{"project_id": self.project_id,
|
||||
"protectable_type": protectable_type,
|
||||
{"protectable_type": protectable_type,
|
||||
"query_string": query_string})
|
||||
@@ -10,16 +10,13 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from smaugclient.common import base
|
||||
from karborclient.common import base
|
||||
|
||||
|
||||
class Provider(base.Resource):
|
||||
def __repr__(self):
|
||||
return "<Provider %s>" % self._info
|
||||
|
||||
def data(self, **kwargs):
|
||||
return self.manager.data(self, **kwargs)
|
||||
|
||||
|
||||
class ProviderManager(base.ManagerWithFind):
|
||||
resource_class = Provider
|
||||
@@ -29,8 +26,7 @@ class ProviderManager(base.ManagerWithFind):
|
||||
headers = {'X-Configuration-Session': session_id}
|
||||
else:
|
||||
headers = {}
|
||||
url = "/v1/{project_id}/providers/{provider_id}".format(
|
||||
project_id=self.project_id,
|
||||
url = "/providers/{provider_id}".format(
|
||||
provider_id=provider_id)
|
||||
return self._get(url, response_key="provider", headers=headers)
|
||||
|
||||
@@ -10,44 +10,37 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from smaugclient.common import base
|
||||
from karborclient.common import base
|
||||
|
||||
|
||||
class Restore(base.Resource):
|
||||
def __repr__(self):
|
||||
return "<Restore %s>" % self._info
|
||||
|
||||
def data(self, **kwargs):
|
||||
return self.manager.data(self, **kwargs)
|
||||
|
||||
|
||||
class RestoreManager(base.ManagerWithFind):
|
||||
resource_class = Restore
|
||||
|
||||
def create(self, provider_id, checkpoint_id, restore_target, parameters):
|
||||
body = {'restore': {'provider_id': provider_id,
|
||||
'checkpoint_id': checkpoint_id,
|
||||
'restore_target': restore_target,
|
||||
'parameters': parameters,
|
||||
}
|
||||
}
|
||||
url = "/v1/{project_id}/restores" .format(
|
||||
project_id=self.project_id)
|
||||
return self._create(url, body, 'restore', return_raw=True)
|
||||
|
||||
def delete(self, restore_id):
|
||||
path = '/v1/{project_id}/restores/{restore_id}'.format(
|
||||
project_id=self.project_id,
|
||||
restore_id=restore_id)
|
||||
return self._delete(path)
|
||||
def create(self, provider_id, checkpoint_id, restore_target, parameters,
|
||||
restore_auth):
|
||||
body = {
|
||||
'restore': {
|
||||
'provider_id': provider_id,
|
||||
'checkpoint_id': checkpoint_id,
|
||||
'restore_target': restore_target,
|
||||
'restore_auth': restore_auth,
|
||||
'parameters': parameters,
|
||||
}
|
||||
}
|
||||
url = "/restores"
|
||||
return self._create(url, body, 'restore')
|
||||
|
||||
def get(self, restore_id, session_id=None):
|
||||
if session_id:
|
||||
headers = {'X-Configuration-Session': session_id}
|
||||
else:
|
||||
headers = {}
|
||||
url = "/v1/{project_id}/restores/{restore_id}".format(
|
||||
project_id=self.project_id,
|
||||
url = "/restores/{restore_id}".format(
|
||||
restore_id=restore_id)
|
||||
return self._get(url, response_key="restore", headers=headers)
|
||||
|
||||
@@ -10,16 +10,13 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from smaugclient.common import base
|
||||
from karborclient.common import base
|
||||
|
||||
|
||||
class ScheduledOperation(base.Resource):
|
||||
def __repr__(self):
|
||||
return "<ScheduledOperation %s>" % self._info
|
||||
|
||||
def data(self, **kwargs):
|
||||
return self.manager.data(self, **kwargs)
|
||||
|
||||
|
||||
class ScheduledOperationManager(base.ManagerWithFind):
|
||||
resource_class = ScheduledOperation
|
||||
@@ -31,14 +28,12 @@ class ScheduledOperationManager(base.ManagerWithFind):
|
||||
'operation_definition':
|
||||
operation_definition,
|
||||
}}
|
||||
url = "/v1/{project_id}/scheduled_operations" .format(
|
||||
project_id=self.project_id)
|
||||
return self._create(url, body, 'scheduled_operation', return_raw=True)
|
||||
url = "/scheduled_operations"
|
||||
return self._create(url, body, 'scheduled_operation')
|
||||
|
||||
def delete(self, scheduled_operation_id):
|
||||
path = '/v1/{project_id}/scheduled_operations/{scheduled_operation_id}'.\
|
||||
format(project_id=self.project_id,
|
||||
scheduled_operation_id=scheduled_operation_id)
|
||||
path = '/scheduled_operations/{scheduled_operation_id}'.\
|
||||
format(scheduled_operation_id=scheduled_operation_id)
|
||||
return self._delete(path)
|
||||
|
||||
def get(self, scheduled_operation_id, session_id=None):
|
||||
@@ -46,9 +41,8 @@ class ScheduledOperationManager(base.ManagerWithFind):
|
||||
headers = {'X-Configuration-Session': session_id}
|
||||
else:
|
||||
headers = {}
|
||||
url = "/v1/{project_id}/scheduled_operations/{scheduled_operation_id}".\
|
||||
format(project_id=self.project_id,
|
||||
scheduled_operation_id=scheduled_operation_id)
|
||||
url = "/scheduled_operations/{scheduled_operation_id}".\
|
||||
format(scheduled_operation_id=scheduled_operation_id)
|
||||
return self._get(url, response_key="scheduled_operation",
|
||||
headers=headers)
|
||||
|
||||
@@ -11,13 +11,16 @@
|
||||
# under the License.
|
||||
|
||||
import argparse
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from datetime import datetime
|
||||
from oslo_serialization import jsonutils
|
||||
from oslo_utils import uuidutils
|
||||
from smaugclient.common import base
|
||||
from smaugclient.common import utils
|
||||
from smaugclient.openstack.common.apiclient import exceptions
|
||||
|
||||
from karborclient.common.apiclient import exceptions
|
||||
from karborclient.common import base
|
||||
from karborclient.common import utils
|
||||
|
||||
|
||||
@utils.arg('--all-tenants',
|
||||
@@ -37,6 +40,10 @@ from smaugclient.openstack.common.apiclient import exceptions
|
||||
metavar='<name>',
|
||||
default=None,
|
||||
help='Filters results by a name. Default=None.')
|
||||
@utils.arg('--description',
|
||||
metavar='<description>',
|
||||
default=None,
|
||||
help='Filters results by a description. Default=None.')
|
||||
@utils.arg('--status',
|
||||
metavar='<status>',
|
||||
default=None,
|
||||
@@ -81,6 +88,7 @@ def do_plan_list(cs, args):
|
||||
'all_tenants': all_tenants,
|
||||
'project_id': args.tenant,
|
||||
'name': args.name,
|
||||
'description': args.description,
|
||||
'status': args.status,
|
||||
}
|
||||
|
||||
@@ -93,7 +101,7 @@ def do_plan_list(cs, args):
|
||||
limit=args.limit, sort_key=args.sort_key,
|
||||
sort_dir=args.sort_dir, sort=args.sort)
|
||||
|
||||
key_list = ['Id', 'Name', 'Provider id', 'Status']
|
||||
key_list = ['Id', 'Name', 'Description', 'Provider id', 'Status']
|
||||
|
||||
if args.sort_key or args.sort_dir or args.sort:
|
||||
sortby_index = None
|
||||
@@ -110,14 +118,36 @@ def do_plan_list(cs, args):
|
||||
metavar='<provider_id>',
|
||||
help='ID of provider.')
|
||||
@utils.arg('resources',
|
||||
metavar='<id=type,id=type>',
|
||||
metavar='<id=type=name,id=type=name>',
|
||||
help='Resource in list must be a dict when creating'
|
||||
' a plan.The keys of resource are id and type.')
|
||||
@utils.arg('--parameters-json',
|
||||
type=str,
|
||||
dest='parameters_json',
|
||||
metavar='<parameters>',
|
||||
default=None,
|
||||
help='Plan parameters in json format.')
|
||||
@utils.arg('--parameters',
|
||||
action='append',
|
||||
metavar='resource_type=<type>[,resource_id=<id>,key=val,...]',
|
||||
default=[],
|
||||
help='Plan parameters, may be specified multiple times. '
|
||||
'resource_type: type of resource to apply parameters. '
|
||||
'resource_id: limit the parameters to a specific resource. '
|
||||
'Other keys and values: according to provider\'s protect schema.'
|
||||
)
|
||||
@utils.arg('--description',
|
||||
metavar='<description>',
|
||||
help='The description of a plan.')
|
||||
def do_plan_create(cs, args):
|
||||
"""Create a plan."""
|
||||
plan_resources = _extract_resources(args)
|
||||
plan = cs.plans.create(args.name, args.provider_id, plan_resources)
|
||||
utils.print_dict(plan)
|
||||
_check_resources(cs, plan_resources)
|
||||
plan_parameters = _extract_parameters(args)
|
||||
plan = cs.plans.create(args.name, args.provider_id, plan_resources,
|
||||
plan_parameters, description=args.description)
|
||||
dict_format_list = {"resources", "parameters"}
|
||||
utils.print_dict(plan.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
@utils.arg('plan',
|
||||
@@ -126,7 +156,8 @@ def do_plan_create(cs, args):
|
||||
def do_plan_show(cs, args):
|
||||
"""Shows plan details."""
|
||||
plan = cs.plans.get(args.plan)
|
||||
utils.print_dict(plan.to_dict())
|
||||
dict_format_list = {"resources", "parameters"}
|
||||
utils.print_dict(plan.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
@utils.arg('plan',
|
||||
@@ -153,7 +184,7 @@ def do_plan_delete(cs, args):
|
||||
help="Id of plan to update.")
|
||||
@utils.arg("--name", metavar="<name>",
|
||||
help="A name to which the plan will be renamed.")
|
||||
@utils.arg("--resources", metavar="<id=type,id=type>",
|
||||
@utils.arg("--resources", metavar="<id=type=name,id=type=name>",
|
||||
help="Resources to which the plan will be updated.")
|
||||
@utils.arg("--status", metavar="<suspended|started>",
|
||||
help="status to which the plan will be updated.")
|
||||
@@ -181,32 +212,66 @@ def _extract_resources(args):
|
||||
for data in args.resources.split(','):
|
||||
resource = {}
|
||||
if '=' in data:
|
||||
(resource_id, resource_type) = data.split('=', 1)
|
||||
(resource_id, resource_type, resource_name) = data.split('=', 2)
|
||||
else:
|
||||
raise exceptions.CommandError(
|
||||
"Unable to parse parameter resources.")
|
||||
|
||||
resource["id"] = resource_id
|
||||
resource["type"] = resource_type
|
||||
resource["name"] = resource_name
|
||||
resources.append(resource)
|
||||
|
||||
return resources
|
||||
|
||||
|
||||
def _check_resources(cs, resources):
|
||||
# check the resource whether it is available
|
||||
for resource in resources:
|
||||
try:
|
||||
instance = cs.protectables.get_instance(
|
||||
resource["type"], resource["id"])
|
||||
except exceptions.NotFound:
|
||||
raise exceptions.CommandError(
|
||||
"The resource: %s can not be found." % resource["id"])
|
||||
else:
|
||||
if instance is None:
|
||||
raise exceptions.CommandError(
|
||||
"The resource: %s is invalid." % resource["id"])
|
||||
|
||||
|
||||
@utils.arg('provider_id',
|
||||
metavar='<provider_id>',
|
||||
help='Provider id.')
|
||||
@utils.arg('checkpoint_id',
|
||||
metavar='<checkpoint_id>',
|
||||
help='Checkpoint id.')
|
||||
@utils.arg('restore_target',
|
||||
@utils.arg('--restore_target',
|
||||
metavar='<restore_target>',
|
||||
help='Restore target.')
|
||||
@utils.arg('--parameters',
|
||||
type=str,
|
||||
nargs='*',
|
||||
metavar='<key=value>',
|
||||
@utils.arg('--restore_username',
|
||||
metavar='<restore_username>',
|
||||
default=None,
|
||||
help='The parameters of a restore target.')
|
||||
help='Username to restore target.')
|
||||
@utils.arg('--restore_password',
|
||||
metavar='<restore_password>',
|
||||
default=None,
|
||||
help='Password to restore target.')
|
||||
@utils.arg('--parameters-json',
|
||||
type=str,
|
||||
dest='parameters_json',
|
||||
metavar='<parameters>',
|
||||
default=None,
|
||||
help='Restore parameters in json format.')
|
||||
@utils.arg('--parameters',
|
||||
action='append',
|
||||
metavar='resource_type=<type>[,resource_id=<id>,key=val,...]',
|
||||
default=[],
|
||||
help='Restore parameters, may be specified multiple times. '
|
||||
'resource_type: type of resource to apply parameters. '
|
||||
'resource_id: limit the parameters to a specific resource. '
|
||||
'Other keys and values: according to provider\'s restore schema.'
|
||||
)
|
||||
def do_restore_create(cs, args):
|
||||
"""Create a restore."""
|
||||
if not uuidutils.is_uuid_like(args.provider_id):
|
||||
@@ -217,27 +282,65 @@ def do_restore_create(cs, args):
|
||||
raise exceptions.CommandError(
|
||||
"Invalid checkpoint id provided.")
|
||||
|
||||
if args.parameters is not None:
|
||||
restore_parameters = _extract_parameters(args)
|
||||
else:
|
||||
raise exceptions.CommandError(
|
||||
"checkpoint_id must be provided.")
|
||||
restore_parameters = _extract_parameters(args)
|
||||
restore_auth = None
|
||||
if args.restore_target is not None:
|
||||
if args.restore_username is None:
|
||||
raise exceptions.CommandError(
|
||||
"Must specify username for restore_target.")
|
||||
if args.restore_password is None:
|
||||
raise exceptions.CommandError(
|
||||
"Must specify password for restore_target.")
|
||||
restore_auth = {
|
||||
'type': 'password',
|
||||
'username': args.restore_username,
|
||||
'password': args.restore_password,
|
||||
}
|
||||
restore = cs.restores.create(args.provider_id, args.checkpoint_id,
|
||||
args.restore_target, restore_parameters)
|
||||
utils.print_dict(restore)
|
||||
args.restore_target, restore_parameters,
|
||||
restore_auth)
|
||||
dict_format_list = {"parameters"}
|
||||
utils.print_dict(restore.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
def _extract_parameters(args):
|
||||
parameters = {}
|
||||
for data in args.parameters:
|
||||
# unset doesn't require a val, so we have the if/else
|
||||
if '=' in data:
|
||||
(key, value) = data.split('=', 1)
|
||||
else:
|
||||
key = data
|
||||
value = None
|
||||
if all((args.parameters, args.parameters_json)):
|
||||
raise exceptions.CommandError(
|
||||
"Must provide parameters or parameters-json, not both")
|
||||
if not any((args.parameters, args.parameters_json)):
|
||||
return {}
|
||||
|
||||
if args.parameters_json:
|
||||
return jsonutils.loads(args.parameters_json)
|
||||
parameters = {}
|
||||
for resource_params in args.parameters:
|
||||
resource_type = None
|
||||
resource_id = None
|
||||
parameter = {}
|
||||
for param_kv in resource_params.split(','):
|
||||
try:
|
||||
key, value = param_kv.split('=')
|
||||
except Exception:
|
||||
raise exceptions.CommandError(
|
||||
'parameters must be in the form: key1=val1,key2=val2,...'
|
||||
)
|
||||
if key == "resource_type":
|
||||
resource_type = value
|
||||
if key == "resource_id":
|
||||
if not uuidutils.is_uuid_like(value):
|
||||
raise exceptions.CommandError('resource_id must be a uuid')
|
||||
resource_id = value
|
||||
parameters[key] = value
|
||||
if resource_type is None:
|
||||
raise exceptions.CommandError(
|
||||
'Must specify resource_type for parameters'
|
||||
)
|
||||
if resource_id is None:
|
||||
resource_key = resource_type
|
||||
else:
|
||||
resource_key = "%s#%s" % (resource_type, resource_id)
|
||||
parameters[resource_key] = parameter
|
||||
|
||||
parameters[key] = value
|
||||
return parameters
|
||||
|
||||
|
||||
@@ -316,8 +419,10 @@ def do_restore_list(cs, args):
|
||||
sortby_index = None
|
||||
else:
|
||||
sortby_index = 0
|
||||
formatters = {"Parameters": lambda obj: json.dumps(
|
||||
obj.parameters, indent=2, sort_keys=True)}
|
||||
utils.print_list(restores, key_list, exclude_unavailable=True,
|
||||
sortby_index=sortby_index)
|
||||
sortby_index=sortby_index, formatters=formatters)
|
||||
|
||||
|
||||
@utils.arg('restore',
|
||||
@@ -326,7 +431,8 @@ def do_restore_list(cs, args):
|
||||
def do_restore_show(cs, args):
|
||||
"""Shows restore details."""
|
||||
restore = cs.restores.get(args.restore)
|
||||
utils.print_dict(restore.to_dict())
|
||||
dict_format_list = {"parameters"}
|
||||
utils.print_dict(restore.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
def do_protectable_list(cs, args):
|
||||
@@ -348,6 +454,32 @@ def do_protectable_show(cs, args):
|
||||
utils.print_dict(protectable.to_dict())
|
||||
|
||||
|
||||
@utils.arg('protectable_type',
|
||||
metavar='<protectable_type>',
|
||||
help='Protectable type.')
|
||||
@utils.arg('protectable_id',
|
||||
metavar='<protectable_id>',
|
||||
help='Protectable instance id.')
|
||||
@utils.arg('--parameters',
|
||||
type=str,
|
||||
nargs='*',
|
||||
metavar='<key=value>',
|
||||
default=None,
|
||||
help='Show a instance by parameters key and value pair. '
|
||||
'Default=None.')
|
||||
def do_protectable_show_instance(cs, args):
|
||||
"""Shows instance details."""
|
||||
search_opts = {
|
||||
'parameters': (_extract_instances_parameters(args)
|
||||
if args.parameters else None),
|
||||
}
|
||||
instance = cs.protectables.get_instance(args.protectable_type,
|
||||
args.protectable_id,
|
||||
search_opts=search_opts)
|
||||
dict_format_list = {"dependent_resources"}
|
||||
utils.print_dict(instance.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
@utils.arg('protectable_type',
|
||||
metavar='<protectable_type>',
|
||||
help='Type of protectable.')
|
||||
@@ -380,11 +512,20 @@ def do_protectable_show(cs, args):
|
||||
'form of <key>[:<asc|desc>]. '
|
||||
'Valid keys: %s. '
|
||||
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
|
||||
@utils.arg('--parameters',
|
||||
type=str,
|
||||
nargs='*',
|
||||
metavar='<key=value>',
|
||||
default=None,
|
||||
help='List instances by parameters key and value pair. '
|
||||
'Default=None.')
|
||||
def do_protectable_list_instances(cs, args):
|
||||
"""Lists all protectable instances."""
|
||||
|
||||
search_opts = {
|
||||
'type': args.type,
|
||||
'parameters': (_extract_instances_parameters(args)
|
||||
if args.parameters else None),
|
||||
}
|
||||
|
||||
if args.sort and (args.sort_key or args.sort_dir):
|
||||
@@ -404,8 +545,24 @@ def do_protectable_list_instances(cs, args):
|
||||
sortby_index = None
|
||||
else:
|
||||
sortby_index = 0
|
||||
|
||||
formatters = {"Dependent resources": lambda obj: json.dumps(
|
||||
obj.dependent_resources, indent=2, sort_keys=True)}
|
||||
utils.print_list(instances, key_list, exclude_unavailable=True,
|
||||
sortby_index=sortby_index)
|
||||
sortby_index=sortby_index, formatters=formatters)
|
||||
|
||||
|
||||
def _extract_instances_parameters(args):
|
||||
parameters = {}
|
||||
for parameter in args.parameters:
|
||||
if '=' in parameter:
|
||||
(key, value) = parameter.split('=', 1)
|
||||
else:
|
||||
key = parameter
|
||||
value = None
|
||||
|
||||
parameters[key] = value
|
||||
return parameters
|
||||
|
||||
|
||||
@utils.arg('provider_id',
|
||||
@@ -414,7 +571,8 @@ def do_protectable_list_instances(cs, args):
|
||||
def do_provider_show(cs, args):
|
||||
"""Shows provider details."""
|
||||
provider = cs.providers.get(args.provider_id)
|
||||
utils.print_dict(provider.to_dict())
|
||||
dict_format_list = {"extended_info_schema"}
|
||||
utils.print_dict(provider.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
@utils.arg('--name',
|
||||
@@ -467,7 +625,7 @@ def do_provider_list(cs, args):
|
||||
limit=args.limit, sort_key=args.sort_key,
|
||||
sort_dir=args.sort_dir, sort=args.sort)
|
||||
|
||||
key_list = ['Id', 'Name', 'Description', 'Extended_info_schema']
|
||||
key_list = ['Id', 'Name', 'Description']
|
||||
|
||||
if args.sort_key or args.sort_dir or args.sort:
|
||||
sortby_index = None
|
||||
@@ -483,19 +641,57 @@ def do_provider_list(cs, args):
|
||||
@utils.arg('plan_id',
|
||||
metavar='<plan_id>',
|
||||
help='ID of plan.')
|
||||
@utils.arg('--extra_info',
|
||||
type=str,
|
||||
nargs='*',
|
||||
metavar='<key=value>',
|
||||
default=None,
|
||||
help='The extra info of a checkpoint.')
|
||||
def do_checkpoint_create(cs, args):
|
||||
"""Create a checkpoint."""
|
||||
checkpoint = cs.checkpoints.create(args.provider_id, args.plan_id)
|
||||
utils.print_dict(checkpoint)
|
||||
|
||||
checkpoint_extra_info = None
|
||||
if args.extra_info is not None:
|
||||
checkpoint_extra_info = _extract_extra_info(args)
|
||||
checkpoint = cs.checkpoints.create(args.provider_id, args.plan_id,
|
||||
checkpoint_extra_info)
|
||||
dict_format_list = {"protection_plan"}
|
||||
json_format_list = {"resource_graph"}
|
||||
utils.print_dict(checkpoint.to_dict(), dict_format_list=dict_format_list,
|
||||
json_format_list=json_format_list)
|
||||
|
||||
|
||||
def _extract_extra_info(args):
|
||||
checkpoint_extra_info = {}
|
||||
for data in args.extra_info:
|
||||
# unset doesn't require a val, so we have the if/else
|
||||
if '=' in data:
|
||||
(key, value) = data.split('=', 1)
|
||||
else:
|
||||
key = data
|
||||
value = None
|
||||
|
||||
checkpoint_extra_info[key] = value
|
||||
return checkpoint_extra_info
|
||||
|
||||
|
||||
@utils.arg('provider_id',
|
||||
metavar='<provider_id>',
|
||||
help='ID of provider.')
|
||||
@utils.arg('--status',
|
||||
metavar='<status>',
|
||||
@utils.arg('--plan_id',
|
||||
metavar='<plan_id>',
|
||||
default=None,
|
||||
help='Filters results by a status. Default=None.')
|
||||
help='Filters results by a plan_id. Default=None.')
|
||||
@utils.arg('--start_date',
|
||||
type=str,
|
||||
metavar='<start_date>',
|
||||
default=None,
|
||||
help='Filters results by a start_date("Y-m-d"). Default=None.')
|
||||
@utils.arg('--end_date',
|
||||
type=str,
|
||||
metavar='<end_date>',
|
||||
default=None,
|
||||
help='Filters results by a end_date("Y-m-d"). Default=None.')
|
||||
@utils.arg('--project_id',
|
||||
metavar='<project_id>',
|
||||
default=None,
|
||||
@@ -527,9 +723,30 @@ def do_checkpoint_create(cs, args):
|
||||
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
|
||||
def do_checkpoint_list(cs, args):
|
||||
"""Lists all checkpoints."""
|
||||
if args.plan_id is not None:
|
||||
if not uuidutils.is_uuid_like(args.plan_id):
|
||||
raise exceptions.CommandError('The plan_id must be a uuid')
|
||||
|
||||
if args.start_date:
|
||||
try:
|
||||
datetime.strptime(
|
||||
args.start_date, "%Y-%m-%d")
|
||||
except (ValueError, SyntaxError):
|
||||
raise exceptions.CommandError(
|
||||
"The format of start_date should be %Y-%m-%d")
|
||||
|
||||
if args.end_date:
|
||||
try:
|
||||
datetime.strptime(
|
||||
args.end_date, "%Y-%m-%d")
|
||||
except (ValueError, SyntaxError):
|
||||
raise exceptions.CommandError(
|
||||
"The format of end_date should be %Y-%m-%d")
|
||||
|
||||
search_opts = {
|
||||
'status': args.status,
|
||||
'plan_id': args.plan_id,
|
||||
'start_date': args.start_date,
|
||||
'end_date': args.end_date,
|
||||
'project_id': args.project_id,
|
||||
}
|
||||
|
||||
@@ -543,14 +760,17 @@ def do_checkpoint_list(cs, args):
|
||||
marker=args.marker, limit=args.limit, sort_key=args.sort_key,
|
||||
sort_dir=args.sort_dir, sort=args.sort)
|
||||
|
||||
key_list = ['Id', 'Project id', 'Status', 'Protection plan']
|
||||
key_list = ['Id', 'Project id', 'Status', 'Protection plan', 'Metadata',
|
||||
'Created at']
|
||||
|
||||
if args.sort_key or args.sort_dir or args.sort:
|
||||
sortby_index = None
|
||||
else:
|
||||
sortby_index = 0
|
||||
formatters = {"Protection plan": lambda obj: json.dumps(
|
||||
obj.protection_plan, indent=2, sort_keys=True)}
|
||||
utils.print_list(checkpoints, key_list, exclude_unavailable=True,
|
||||
sortby_index=sortby_index)
|
||||
sortby_index=sortby_index, formatters=formatters)
|
||||
|
||||
|
||||
@utils.arg('provider_id',
|
||||
@@ -562,7 +782,10 @@ def do_checkpoint_list(cs, args):
|
||||
def do_checkpoint_show(cs, args):
|
||||
"""Shows checkpoint details."""
|
||||
checkpoint = cs.checkpoints.get(args.provider_id, args.checkpoint_id)
|
||||
utils.print_dict(checkpoint.to_dict())
|
||||
dict_format_list = {"protection_plan"}
|
||||
json_format_list = {"resource_graph"}
|
||||
utils.print_dict(checkpoint.to_dict(), dict_format_list=dict_format_list,
|
||||
json_format_list=json_format_list)
|
||||
|
||||
|
||||
@utils.arg('provider_id',
|
||||
@@ -579,7 +802,7 @@ def do_checkpoint_delete(cs, args):
|
||||
try:
|
||||
checkpoint = cs.checkpoints.get(args.provider_id,
|
||||
checkpoint_id)
|
||||
cs.checkpoints.delete(checkpoint.provider_id, checkpoint.id)
|
||||
cs.checkpoints.delete(args.provider_id, checkpoint.id)
|
||||
except exceptions.NotFound:
|
||||
failure_count += 1
|
||||
print("Failed to delete '{0}'; checkpoint not found".
|
||||
@@ -673,8 +896,11 @@ def do_trigger_list(cs, args):
|
||||
sortby_index = None
|
||||
else:
|
||||
sortby_index = 0
|
||||
|
||||
formatters = {"Properties": lambda obj: json.dumps(
|
||||
obj.properties, indent=2, sort_keys=True)}
|
||||
utils.print_list(triggers, key_list, exclude_unavailable=True,
|
||||
sortby_index=sortby_index)
|
||||
sortby_index=sortby_index, formatters=formatters)
|
||||
|
||||
|
||||
@utils.arg('name',
|
||||
@@ -684,18 +910,21 @@ def do_trigger_list(cs, args):
|
||||
metavar='<type>',
|
||||
help='Type of trigger.')
|
||||
@utils.arg('properties',
|
||||
metavar='<key=value;key=value>',
|
||||
metavar='<key=value,key=value>',
|
||||
help='Properties of trigger.')
|
||||
def do_trigger_create(cs, args):
|
||||
"""Create a trigger."""
|
||||
trigger_properties = _extract_properties(args)
|
||||
trigger = cs.triggers.create(args.name, args.type, trigger_properties)
|
||||
utils.print_dict(trigger)
|
||||
dict_format_list = {"properties"}
|
||||
utils.print_dict(trigger.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
def _extract_properties(args):
|
||||
properties = {}
|
||||
for data in args.properties.split(':'):
|
||||
if args.properties is None:
|
||||
return properties
|
||||
for data in args.properties.split(','):
|
||||
if '=' in data:
|
||||
(resource_key, resource_value) = data.split('=', 1)
|
||||
else:
|
||||
@@ -706,13 +935,31 @@ def _extract_properties(args):
|
||||
return properties
|
||||
|
||||
|
||||
@utils.arg("trigger_id", metavar="<TRIGGER ID>",
|
||||
help="Id of trigger to update.")
|
||||
@utils.arg("--name", metavar="<name>",
|
||||
help="A new name to which the trigger will be renamed.")
|
||||
@utils.arg("--properties", metavar="<key=value,key=value>",
|
||||
help="Properties of trigger which will be updated.")
|
||||
def do_trigger_update(cs, args):
|
||||
"""Update a trigger."""
|
||||
trigger_info = {}
|
||||
trigger_properties = _extract_properties(args)
|
||||
trigger_info['name'] = args.name
|
||||
trigger_info['properties'] = trigger_properties
|
||||
trigger = cs.triggers.update(args.trigger_id, trigger_info)
|
||||
dict_format_list = {"properties"}
|
||||
utils.print_dict(trigger.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
@utils.arg('trigger',
|
||||
metavar='<trigger>',
|
||||
help='ID of trigger.')
|
||||
def do_trigger_show(cs, args):
|
||||
"""Shows trigger details."""
|
||||
trigger = cs.triggers.get(args.trigger)
|
||||
utils.print_dict(trigger.to_dict())
|
||||
dict_format_list = {"properties"}
|
||||
utils.print_dict(trigger.to_dict(), dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
@utils.arg('trigger',
|
||||
@@ -760,6 +1007,10 @@ def do_trigger_delete(cs, args):
|
||||
metavar='<trigger_id>',
|
||||
default=None,
|
||||
help='Filters results by a trigger id. Default=None.')
|
||||
@utils.arg('--operation_definition',
|
||||
metavar='<operation_definition>',
|
||||
default=None,
|
||||
help='Filters results by the operation_definition. Default=None.')
|
||||
@utils.arg('--marker',
|
||||
metavar='<marker>',
|
||||
default=None,
|
||||
@@ -800,8 +1051,9 @@ def do_scheduledoperation_list(cs, args):
|
||||
'all_tenants': all_tenants,
|
||||
'project_id': args.tenant,
|
||||
'name': args.name,
|
||||
'operation_type': args.type,
|
||||
'operation_type': args.operation_type,
|
||||
'trigger_id': args.trigger_id,
|
||||
'operation_definition': args.operation_definition,
|
||||
}
|
||||
|
||||
if args.sort and (args.sort_key or args.sort_dir):
|
||||
@@ -834,21 +1086,23 @@ def do_scheduledoperation_list(cs, args):
|
||||
metavar='<trigger_id>',
|
||||
help='Trigger id of scheduled operation.')
|
||||
@utils.arg('operation_definition',
|
||||
metavar='<key=value;key=value>',
|
||||
metavar='<key=value,key=value>',
|
||||
help='Operation definition of scheduled operation.')
|
||||
def do_scheduledoperation_create(cs, args):
|
||||
"""Create a scheduled operation."""
|
||||
operation_definition = _extract_operation_definition(args)
|
||||
scheduledoperation = cs.scheduledoperations.create(args.name,
|
||||
args.operation_type,
|
||||
args.trigger_id,
|
||||
operation_definition)
|
||||
utils.print_dict(scheduledoperation)
|
||||
scheduledoperation = cs.scheduled_operations.create(args.name,
|
||||
args.operation_type,
|
||||
args.trigger_id,
|
||||
operation_definition)
|
||||
dict_format_list = {"operation_definition"}
|
||||
utils.print_dict(scheduledoperation.to_dict(),
|
||||
dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
def _extract_operation_definition(args):
|
||||
operation_definition = {}
|
||||
for data in args.operation_definition.split(':'):
|
||||
for data in args.operation_definition.split(','):
|
||||
if '=' in data:
|
||||
(resource_key, resource_value) = data.split('=', 1)
|
||||
else:
|
||||
@@ -864,8 +1118,10 @@ def _extract_operation_definition(args):
|
||||
help='ID of scheduled operation.')
|
||||
def do_scheduledoperation_show(cs, args):
|
||||
"""Shows scheduledoperation details."""
|
||||
scheduledoperation = cs.scheduledoperations.get(args.scheduledoperation)
|
||||
utils.print_dict(scheduledoperation.to_dict())
|
||||
scheduledoperation = cs.scheduled_operations.get(args.scheduledoperation)
|
||||
dict_format_list = {"operation_definition"}
|
||||
utils.print_dict(scheduledoperation.to_dict(),
|
||||
dict_format_list=dict_format_list)
|
||||
|
||||
|
||||
@utils.arg('scheduledoperation',
|
||||
@@ -877,9 +1133,9 @@ def do_scheduledoperation_delete(cs, args):
|
||||
failure_count = 0
|
||||
for scheduledoperation_id in args.scheduledoperation:
|
||||
try:
|
||||
scheduledoperation = utils.find_resource(cs.scheduledoperations,
|
||||
scheduledoperation = utils.find_resource(cs.scheduled_operations,
|
||||
scheduledoperation_id)
|
||||
cs.scheduledoperations.delete(scheduledoperation.id)
|
||||
cs.scheduled_operations.delete(scheduledoperation.id)
|
||||
except exceptions.NotFound:
|
||||
failure_count += 1
|
||||
print("Failed to delete '{0}'; scheduledoperation not found".
|
||||
@@ -10,16 +10,13 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from smaugclient.common import base
|
||||
from karborclient.common import base
|
||||
|
||||
|
||||
class Trigger(base.Resource):
|
||||
def __repr__(self):
|
||||
return "<Trigger %s>" % self._info
|
||||
|
||||
def data(self, **kwargs):
|
||||
return self.manager.data(self, **kwargs)
|
||||
|
||||
|
||||
class TriggerManager(base.ManagerWithFind):
|
||||
resource_class = Trigger
|
||||
@@ -29,13 +26,11 @@ class TriggerManager(base.ManagerWithFind):
|
||||
'type': type,
|
||||
'properties': properties,
|
||||
}}
|
||||
url = "/v1/{project_id}/triggers" .format(
|
||||
project_id=self.project_id)
|
||||
return self._create(url, body, 'trigger_info', return_raw=True)
|
||||
url = "/triggers"
|
||||
return self._create(url, body, 'trigger_info')
|
||||
|
||||
def delete(self, trigger_id):
|
||||
path = '/v1/{project_id}/triggers/{trigger_id}'.format(
|
||||
project_id=self.project_id,
|
||||
path = '/triggers/{trigger_id}'.format(
|
||||
trigger_id=trigger_id)
|
||||
return self._delete(path)
|
||||
|
||||
@@ -44,11 +39,18 @@ class TriggerManager(base.ManagerWithFind):
|
||||
headers = {'X-Configuration-Session': session_id}
|
||||
else:
|
||||
headers = {}
|
||||
url = "/v1/{project_id}/triggers/{trigger_id}".format(
|
||||
project_id=self.project_id,
|
||||
url = "/triggers/{trigger_id}".format(
|
||||
trigger_id=trigger_id)
|
||||
return self._get(url, response_key="trigger_info", headers=headers)
|
||||
|
||||
def update(self, trigger_id, data):
|
||||
|
||||
body = {"trigger_info": data}
|
||||
|
||||
return self._update('/triggers/{trigger_id}'
|
||||
.format(trigger_id=trigger_id),
|
||||
body, "trigger_info")
|
||||
|
||||
def list(self, detailed=False, search_opts=None, marker=None, limit=None,
|
||||
sort_key=None, sort_dir=None, sort=None):
|
||||
"""Lists all triggers."""
|
||||
@@ -13,4 +13,4 @@
|
||||
|
||||
from pbr import version
|
||||
|
||||
version_info = version.VersionInfo('python-smaugclient')
|
||||
version_info = version.VersionInfo('python-karborclient')
|
||||
@@ -1,8 +0,0 @@
|
||||
[DEFAULT]
|
||||
|
||||
# The list of modules to copy from openstack-common
|
||||
module=apiclient.exceptions
|
||||
module=apiclient
|
||||
|
||||
# The base module to hold the copy of openstack.common
|
||||
base=smaugclient
|
||||
@@ -1,13 +1,13 @@
|
||||
# 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.
|
||||
pbr>=1.6 # Apache-2.0
|
||||
PrettyTable<0.8,>=0.7 # BSD
|
||||
python-keystoneclient!=1.8.0,!=2.1.0,>=1.6.0 # Apache-2.0
|
||||
requests!=2.9.0,>=2.8.1 # Apache-2.0
|
||||
pbr>=1.8 # Apache-2.0
|
||||
PrettyTable<0.8,>=0.7.1 # BSD
|
||||
python-keystoneclient>=3.8.0 # Apache-2.0
|
||||
requests!=2.12.2,>=2.10.0 # Apache-2.0
|
||||
simplejson>=2.2.0 # MIT
|
||||
Babel>=1.3 # BSD
|
||||
Babel>=2.3.4 # BSD
|
||||
six>=1.9.0 # MIT
|
||||
oslo.utils>=3.5.0 # Apache-2.0
|
||||
oslo.log>=1.14.0 # Apache-2.0
|
||||
oslo.utils>=3.18.0 # Apache-2.0
|
||||
oslo.log>=3.11.0 # Apache-2.0
|
||||
oslo.i18n>=2.1.0 # Apache-2.0
|
||||
|
||||
13
setup.cfg
13
setup.cfg
@@ -1,12 +1,11 @@
|
||||
[metadata]
|
||||
name = python-smaugclient
|
||||
version = 0.0.1
|
||||
summary = Python client library for Smaug API
|
||||
name = python-karborclient
|
||||
summary = Python client library for Karbor API
|
||||
description-file =
|
||||
README.rst
|
||||
author = OpenStack
|
||||
author-email = openstack-dev@lists.openstack.org
|
||||
home-page = http://www.openstack.org/
|
||||
home-page = http://docs.openstack.org/developer/karbor/
|
||||
classifier =
|
||||
Environment :: OpenStack
|
||||
Intended Audience :: Information Technology
|
||||
@@ -17,8 +16,8 @@ classifier =
|
||||
Programming Language :: Python :: 2
|
||||
Programming Language :: Python :: 2.7
|
||||
Programming Language :: Python :: 3
|
||||
Programming Language :: Python :: 3.3
|
||||
Programming Language :: Python :: 3.4
|
||||
Programming Language :: Python :: 3.5
|
||||
|
||||
[global]
|
||||
setup-hooks =
|
||||
@@ -26,11 +25,11 @@ setup-hooks =
|
||||
|
||||
[files]
|
||||
packages =
|
||||
smaugclient
|
||||
karborclient
|
||||
|
||||
[entry_points]
|
||||
console_scripts =
|
||||
smaug = smaugclient.shell:main
|
||||
karbor = karborclient.shell:main
|
||||
|
||||
[build_sphinx]
|
||||
source-dir = doc/source
|
||||
|
||||
@@ -1,17 +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 six
|
||||
|
||||
|
||||
six.add_move(six.MovedModule('mox', 'mox', 'mox3.mox'))
|
||||
@@ -2,14 +2,14 @@
|
||||
# of appearance. Changing the order has an impact on the overall integration
|
||||
# process, which may cause wedges in the gate later.
|
||||
|
||||
hacking>=0.10.2,<0.11 # Apache-2.0
|
||||
hacking<0.11,>=0.10.2 # Apache-2.0
|
||||
|
||||
coverage>=3.6 # Apache-2.0
|
||||
discover # BSD
|
||||
python-subunit>=0.0.18 # Apache-2.0/BSD
|
||||
sphinx>=1.1.2,!=1.2.0,!=1.3b1,<1.3 # BSD
|
||||
oslosphinx>=2.5.0,!=3.4.0 # Apache-2.0
|
||||
coverage>=4.0 # Apache-2.0
|
||||
python-subunit>=0.0.18 # Apache-2.0/BSD
|
||||
docutils!=0.13.1,>=0.11 # OSI-Approved Open Source, Public Domain
|
||||
sphinx!=1.3b1,<1.4,>=1.2.1 # BSD
|
||||
oslosphinx>=4.7.0 # Apache-2.0
|
||||
oslotest>=1.10.0 # Apache-2.0
|
||||
testrepository>=0.0.18 # Apache-2.0/BSD
|
||||
testscenarios>=0.4 # Apache-2.0/BSD
|
||||
testtools>=1.4.0 # MIT
|
||||
testrepository>=0.0.18 # Apache-2.0/BSD
|
||||
testscenarios>=0.4 # Apache-2.0/BSD
|
||||
testtools>=1.4.0 # MIT
|
||||
|
||||
30
tools/tox_install.sh
Executable file
30
tools/tox_install.sh
Executable file
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Client constraint file contains this client version pin that is in conflict
|
||||
# with installing the client from source. We should remove the version pin in
|
||||
# the constraints file before applying it for from-source installation.
|
||||
|
||||
CONSTRAINTS_FILE="$1"
|
||||
shift 1
|
||||
|
||||
set -e
|
||||
|
||||
# NOTE(tonyb): Place this in the tox enviroment's log dir so it will get
|
||||
# published to logs.openstack.org for easy debugging.
|
||||
localfile="$VIRTUAL_ENV/log/upper-constraints.txt"
|
||||
|
||||
if [[ "$CONSTRAINTS_FILE" != http* ]]; then
|
||||
CONSTRAINTS_FILE="file://$CONSTRAINTS_FILE"
|
||||
fi
|
||||
# NOTE(tonyb): need to add curl to bindep.txt if the project supports bindep
|
||||
curl "$CONSTRAINTS_FILE" --insecure --progress-bar --output "$localfile"
|
||||
|
||||
pip install -c"$localfile" openstack-requirements
|
||||
|
||||
# This is the main purpose of the script: Allow local installation of
|
||||
# the current repo. It is listed in constraints file and thus any
|
||||
# install will be constrained and we need to unconstrain it.
|
||||
edit-constraints "$localfile" -- "$CLIENT_NAME"
|
||||
|
||||
pip install -c"$localfile" -U "$@"
|
||||
exit $?
|
||||
14
tox.ini
14
tox.ini
@@ -1,13 +1,16 @@
|
||||
[tox]
|
||||
minversion = 1.6
|
||||
envlist = py34,py27,pypy,pep8
|
||||
minversion = 2.0
|
||||
envlist = py35,py34,py27,pypy,pep8
|
||||
skipsdist = True
|
||||
|
||||
[testenv]
|
||||
usedevelop = True
|
||||
install_command = pip install -U {opts} {packages}
|
||||
install_command = {toxinidir}/tools/tox_install.sh {env:UPPER_CONSTRAINTS_FILE:https://git.openstack.org/cgit/openstack/requirements/plain/upper-constraints.txt} {opts} {packages}
|
||||
setenv =
|
||||
VIRTUAL_ENV={envdir}
|
||||
BRANCH_NAME=master
|
||||
CLIENT_NAME=python-karborclient
|
||||
PYTHONWARNINGS=default::DeprecationWarning
|
||||
deps = -r{toxinidir}/requirements.txt
|
||||
-r{toxinidir}/test-requirements.txt
|
||||
commands = python setup.py test --slowest --testr-args='{posargs}'
|
||||
@@ -20,7 +23,8 @@ commands = {posargs}
|
||||
|
||||
[testenv:functional]
|
||||
setenv =
|
||||
OS_TEST_PATH = ./smaugclient/tests/functional
|
||||
{[testenv]setenv}
|
||||
OS_TEST_PATH = ./karborclient/tests/functional
|
||||
passenv = OS_*
|
||||
[testenv:cover]
|
||||
commands = python setup.py test --coverage --testr-args='{posargs}'
|
||||
@@ -37,4 +41,4 @@ commands = oslo_debug_helper {posargs}
|
||||
show-source = True
|
||||
ignore = E123,E125
|
||||
builtins = _
|
||||
exclude=.venv,.git,.tox,dist,doc,*openstack/common*,*lib/python*,*egg,tools
|
||||
exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,tools
|
||||
|
||||
Reference in New Issue
Block a user