
Functionality is supported both for the Python client: host = craton.hosts.get(item_id=8) host.variables.update(x='foo', y={'a': 47, 'b': True}, z='baz') host.variables.delete("foo", "bar", "baz") As well as for the CLI: craton host-vars-get 1 craton host-vars-set 3 x=true y=47 z=foo/bar w=3.14159 cat <<EOF | craton host-vars-set 13 { "glance_default_store": "not-so-swift", "neutron_l2_population": false, "make_stuff_up": true, "some/namespaced/variable": {"a": 1, "b": 2} } EOF craton --format json host-vars-get 13 | jq -C craton host-vars-delete 13 make_stuff_up craton host-vars-set 13 x= y=42 # deletes x This patch implements the basis for supporting this in other resources as well, however we only address hosts here as an initial implementation. We will fast-follow with support in other resources. Partial-Bug: 1659110 Change-Id: Id30188937518d7103d6f943cf1d038b039dc30cc
264 lines
9.1 KiB
Python
264 lines
9.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
|
# not use this file except in compliance with the License. You may obtain
|
|
# a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
|
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
|
# License for the specific language governing permissions and limitations
|
|
# under the License.
|
|
"""Client for CRUD operations."""
|
|
import copy
|
|
|
|
from oslo_utils import strutils
|
|
|
|
|
|
class CRUDClient(object):
|
|
"""Class that handles the basic create, read, upload, delete workflow."""
|
|
|
|
key = ""
|
|
base_path = None
|
|
resource_class = None
|
|
|
|
def __init__(self, session, url, **extra_request_kwargs):
|
|
"""Initialize our Client with a session and base url."""
|
|
self.session = session
|
|
self.url = url.rstrip('/')
|
|
self.extra_request_kwargs = extra_request_kwargs
|
|
|
|
def build_url(self, path_arguments=None):
|
|
"""Build a complete URL from the url, base_path, and arguments.
|
|
|
|
A CRUDClient is constructed with the base URL, e.g.
|
|
|
|
.. code-block:: python
|
|
|
|
RegionManager(url='https://10.1.1.0:8080/v1', ...)
|
|
|
|
The child class of the CRUDClient may set the ``base_path``, e.g.,
|
|
|
|
.. code-block:: python
|
|
|
|
base_path = '/regions'
|
|
|
|
And its ``key``, e.g.,
|
|
|
|
.. code-block:: python
|
|
|
|
key = 'region'
|
|
|
|
And based on the ``path_arguments`` parameter we will construct a
|
|
complete URL. For example, if someone calls:
|
|
|
|
.. code-block:: python
|
|
|
|
self.build_url(path_arguments={'region_id': 1})
|
|
|
|
with the hypothetical values above, we would return
|
|
|
|
https://10.1.1.0:8080/v1/regions/1
|
|
|
|
Users can also override ``base_path`` in ``path_arguments``.
|
|
"""
|
|
if path_arguments is None:
|
|
path_arguments = {}
|
|
|
|
base_path = path_arguments.pop('base_path', None) or self.base_path
|
|
item_id = path_arguments.pop('{0}_id'.format(self.key), None)
|
|
|
|
url = self.url + base_path
|
|
|
|
if item_id is not None:
|
|
url += '/{0}'.format(item_id)
|
|
|
|
return url
|
|
|
|
def merge_request_arguments(self, request_kwargs, skip_merge):
|
|
"""Merge the extra request arguments into the per-request args."""
|
|
if skip_merge:
|
|
return
|
|
|
|
keys = set(self.extra_request_kwargs.keys())
|
|
missing_keys = keys.difference(request_kwargs.keys())
|
|
for key in missing_keys:
|
|
request_kwargs[key] = self.extra_request_kwargs[key]
|
|
|
|
def create(self, skip_merge=False, **kwargs):
|
|
"""Create a new item based on the keyword arguments provided."""
|
|
self.merge_request_arguments(kwargs, skip_merge)
|
|
url = self.build_url(path_arguments=kwargs)
|
|
response = self.session.post(url, json=kwargs)
|
|
return self.resource_class(self, response.json(), loaded=True)
|
|
|
|
def get(self, item_id=None, skip_merge=True, **kwargs):
|
|
"""Retrieve the item based on the keyword arguments provided."""
|
|
self.merge_request_arguments(kwargs, skip_merge)
|
|
kwargs.setdefault(self.key + '_id', item_id)
|
|
url = self.build_url(path_arguments=kwargs)
|
|
response = self.session.get(url)
|
|
return self.resource_class(self, response.json(), loaded=True)
|
|
|
|
def list(self, skip_merge=False, **kwargs):
|
|
"""Generate the items from this endpoint."""
|
|
autopaginate = kwargs.pop('autopaginate', True)
|
|
nested = kwargs.pop('nested', False)
|
|
self.merge_request_arguments(kwargs, skip_merge)
|
|
url = self.build_url(path_arguments=kwargs)
|
|
|
|
response_generator = self.session.paginate(
|
|
url,
|
|
autopaginate=autopaginate,
|
|
items_key=(self.key + 's'),
|
|
nested=nested,
|
|
params=kwargs,
|
|
)
|
|
for response, items in response_generator:
|
|
for item in items:
|
|
yield self.resource_class(self, item, loaded=True)
|
|
|
|
def update(self, item_id=None, skip_merge=True, **kwargs):
|
|
"""Update the item based on the keyword arguments provided."""
|
|
self.merge_request_arguments(kwargs, skip_merge)
|
|
kwargs.setdefault(self.key + '_id', item_id)
|
|
url = self.build_url(path_arguments=kwargs)
|
|
response = self.session.put(url, json=kwargs)
|
|
return self.resource_class(self, response.json(), loaded=True)
|
|
|
|
def delete(self, item_id=None, skip_merge=True, json=None, **kwargs):
|
|
"""Delete the item based on the keyword arguments provided."""
|
|
self.merge_request_arguments(kwargs, skip_merge)
|
|
kwargs.setdefault(self.key + '_id', item_id)
|
|
url = self.build_url(path_arguments=kwargs)
|
|
response = self.session.delete(url, params=kwargs, json=json)
|
|
if 200 <= response.status_code < 300:
|
|
return True
|
|
return False
|
|
|
|
def __repr__(self):
|
|
"""Return string representation of a Variable."""
|
|
return '%(class)s(%(session)s, %(url)s, %(extra_request_kwargs)s)' % \
|
|
{
|
|
"class": self.__class__.__name__,
|
|
"session": self.session,
|
|
"url": self.url,
|
|
"extra_request_kwargs": self.extra_request_kwargs,
|
|
}
|
|
|
|
|
|
# NOTE(sigmavirus24): Credit for this Resource object goes to the
|
|
# keystoneclient developers and contributors.
|
|
class Resource(object):
|
|
"""Base class for OpenStack resources (tenant, user, etc.).
|
|
|
|
This is pretty much just a bag for attributes.
|
|
"""
|
|
|
|
HUMAN_ID = False
|
|
NAME_ATTR = 'name'
|
|
subresource_managers = {}
|
|
|
|
def __init__(self, manager, info, loaded=False):
|
|
"""Populate and bind to a manager.
|
|
|
|
:param manager: BaseManager object
|
|
:param info: dictionary representing resource attributes
|
|
:param loaded: prevent lazy-loading if set to True
|
|
"""
|
|
self.manager = manager
|
|
self._info = info
|
|
self._add_details(info)
|
|
self._loaded = loaded
|
|
|
|
session = self.manager.session
|
|
subresource_base_url = self.manager.build_url(
|
|
{"{0}_id".format(self.manager.key): self.id}
|
|
)
|
|
for attribute, cls in self.subresource_managers.items():
|
|
setattr(self, attribute,
|
|
cls(session, subresource_base_url,
|
|
**self.manager.extra_request_kwargs))
|
|
|
|
def __repr__(self):
|
|
"""Return string representation of resource attributes."""
|
|
reprkeys = sorted(k
|
|
for k in self.__dict__.keys()
|
|
if k[0] != '_' and k != 'manager')
|
|
info = ", ".join("%s=%s" % (k, getattr(self, k)) for k in reprkeys)
|
|
return "<%s %s>" % (self.__class__.__name__, info)
|
|
|
|
@property
|
|
def human_id(self):
|
|
"""Human-readable ID which can be used for bash completion."""
|
|
if self.HUMAN_ID:
|
|
name = getattr(self, self.NAME_ATTR, None)
|
|
if name is not None:
|
|
return strutils.to_slug(name)
|
|
return None
|
|
|
|
def _add_details(self, info):
|
|
for (k, v) in info.items():
|
|
try:
|
|
setattr(self, k, v)
|
|
self._info[k] = v
|
|
except AttributeError: # nosec(cjschaef): we already defined the
|
|
# attribute on the class
|
|
pass
|
|
|
|
def __getattr__(self, k):
|
|
"""Checking attrbiute existence."""
|
|
if k not in self.__dict__:
|
|
# NOTE(bcwaldon): disallow lazy-loading if already loaded once
|
|
if not self.is_loaded():
|
|
self.get()
|
|
return self.__getattr__(k)
|
|
|
|
raise AttributeError(k)
|
|
else:
|
|
return self.__dict__[k]
|
|
|
|
def get(self):
|
|
"""Support for lazy loading details.
|
|
|
|
Some clients, such as novaclient have the option to lazy load the
|
|
details, details which can be loaded with this function.
|
|
"""
|
|
# set_loaded() first ... so if we have to bail, we know we tried.
|
|
self.set_loaded(True)
|
|
if not hasattr(self.manager, 'get'):
|
|
return
|
|
|
|
new = self.manager.get(self.id)
|
|
if new:
|
|
self._add_details(new._info)
|
|
self._add_details(
|
|
{'x_request_id': self.manager.client.last_request_id})
|
|
|
|
def __eq__(self, other):
|
|
"""Define equality for resources."""
|
|
if not isinstance(other, Resource):
|
|
return NotImplemented
|
|
# two resources of different types are not equal
|
|
if not isinstance(other, self.__class__):
|
|
return False
|
|
return self._info == other._info
|
|
|
|
def is_loaded(self):
|
|
"""Check if the resource has been loaded."""
|
|
return self._loaded
|
|
|
|
def set_loaded(self, val):
|
|
"""Set whether the resource has been loaded or not."""
|
|
self._loaded = val
|
|
|
|
def to_dict(self):
|
|
"""Return the resource as a dictionary."""
|
|
return copy.deepcopy(self._info)
|
|
|
|
def delete(self):
|
|
"""Delete the resource from the service."""
|
|
return self.manager.delete(self.id)
|