Fix for check_cinder_volume

- applied DRY principle on authentication
 - fixed confusing naming
 - removed conflicting parameters
 - switched to Cinder API V2+
 - compatibility with python-cinder-11.0.0

Change-Id: If8e7f5a39ddaa9c15e1acc9f4f1c2a695954bde4
This commit is contained in:
Martin Mágr 2017-11-06 13:21:27 +01:00
parent d63e150e8a
commit 3b131c626b
1 changed files with 39 additions and 86 deletions

View File

@ -67,16 +67,17 @@ def check_cinder_api():
utils.safe_run(_check_cinder_api) utils.safe_run(_check_cinder_api)
class Novautils(object): class CinderUtils(object):
DAEMON_DEFAULT_PORT = 8776 DAEMON_DEFAULT_PORT = 8776
def __init__(self, nova_client): def __init__(self, client, project):
self.nova_client = nova_client self.client = client
self.msgs = [] self.msgs = []
self.start = self.totimestamp() self.start = self.totimestamp()
self.notifications = ["volume_creation_time=%s" % self.start] self.notifications = ["volume_creation_time=%s" % self.start]
self.volume = None self.volume = None
self.connection_done = False self.connection_done = False
self.project = project
# python has no "toepoch" method: http://bugs.python.org/issue2736 # python has no "toepoch" method: http://bugs.python.org/issue2736
# now, after checking http://stackoverflow.com/a/16307378, # now, after checking http://stackoverflow.com/a/16307378,
@ -94,7 +95,8 @@ class Novautils(object):
if not self.connection_done or force: if not self.connection_done or force:
try: try:
# force a connection to the server # force a connection to the server
self.connection_done = self.nova_client.limits.get() self.connection_done = self.client.limits.get(
tenant_id=self.project)
except Exception as e: except Exception as e:
utils.critical("Cannot connect to cinder: %s" % e) utils.critical("Cannot connect to cinder: %s" % e)
@ -118,7 +120,7 @@ class Novautils(object):
catalog_url = None catalog_url = None
try: try:
catalog_url = urlparse.urlparse( catalog_url = urlparse.urlparse(
self.nova_client.client.management_url) self.client.client.management_url)
except Exception as e: except Exception as e:
utils.unknown("unknown error parsing the catalog url : %s" % e) utils.unknown("unknown error parsing the catalog url : %s" % e)
@ -136,11 +138,11 @@ class Novautils(object):
catalog_url.params, catalog_url.params,
catalog_url.query, catalog_url.query,
catalog_url.fragment]) catalog_url.fragment])
self.nova_client.client.management_url = url self.client.client.management_url = url
def check_existing_volume(self, volume_name, delete): def check_existing_volume(self, volume_name, delete):
count = 0 count = 0
for s in self.nova_client.volumes.list(): for s in self.client.volumes.list():
if s.display_name == volume_name: if s.display_name == volume_name:
if delete: if delete:
# asynchronous call, we do not check that it worked # asynchronous call, we do not check that it worked
@ -159,13 +161,12 @@ class Novautils(object):
def create_volume(self, volume_name, size, availability_zone, volume_type): def create_volume(self, volume_name, size, availability_zone, volume_type):
if not self.msgs: if not self.msgs:
try: try:
conf = {'display_name': volume_name, conf = {'name': volume_name, 'size': size}
'size': size}
if volume_type: if volume_type:
conf['volume_type'] = volume_type conf['volume_type'] = volume_type
if availability_zone: if availability_zone:
conf['availability_zone'] = availability_zone conf['availability_zone'] = availability_zone
self.volume = self.nova_client.volumes.create(**conf) self.volume = self.client.volumes.create(**conf)
except Exception as e: except Exception as e:
self.msgs.append("Cannot create the volume %s (%s)" self.msgs.append("Cannot create the volume %s (%s)"
% (volume_name, e)) % (volume_name, e))
@ -213,107 +214,59 @@ class Novautils(object):
def _check_cinder_volume(): def _check_cinder_volume():
parser = argparse.ArgumentParser( cinder = utils.Cinder()
description='Check an OpenStack Keystone server.')
parser.add_argument('--auth_url', metavar='URL', type=str,
default=os.getenv('OS_AUTH_URL'),
help='Keystone URL')
parser.add_argument('--username', metavar='username', type=str, cinder.add_argument('--endpoint_url', metavar='endpoint_url', type=str,
default=os.getenv('OS_USERNAME'),
help='username to use for authentication')
parser.add_argument('--password', metavar='password', type=str,
default=os.getenv('OS_PASSWORD'),
help='password to use for authentication')
parser.add_argument('--tenant', metavar='tenant', type=str,
default=os.getenv('OS_TENANT_NAME'),
help='tenant name to use for authentication')
parser.add_argument('--endpoint_url', metavar='endpoint_url', type=str,
help='Override the catalog endpoint.') help='Override the catalog endpoint.')
parser.add_argument('--endpoint_type', metavar='endpoint_type', type=str, cinder.add_argument('--force_delete', action='store_true',
default="publicURL", help='If matching volumes are found, delete '
help="""Endpoint type in the catalog request. """ 'them and add a notification in the '
"""Public by default.""") 'message instead of getting out in '
'critical state.')
parser.add_argument('--force_delete', action='store_true', cinder.add_argument('--volume_name', metavar='volume_name', type=str,
help="""If matching volumes are found, delete """
"""them and add a notification in the """
"""message instead of getting out in """
"""critical state.""")
parser.add_argument('--api_version', metavar='api_version', type=str,
default='1',
help='Version of the API to use. 1 by default.')
parser.add_argument('--timeout', metavar='timeout', type=int,
default=120,
help="""Max number of second to create/delete a """
"""volume (120 by default).""")
parser.add_argument('--volume_name', metavar='volume_name', type=str,
default="monitoring_test", default="monitoring_test",
help="""Name of the volume to create """ help='Name of the volume to create '
"""(monitoring_test by default)""") '(monitoring_test by default)')
parser.add_argument('--volume_size', metavar='volume_size', type=int, cinder.add_argument('--volume_size', metavar='volume_size', type=int,
default=1, default=1,
help='Size of the volume to create (1 GB by default)') help='Size of the volume to create (1 GB by default)')
parser.add_argument('--volume_type', metavar='volume_type', type=str, cinder.add_argument('--volume_type', metavar='volume_type', type=str,
default=None, default=None,
help='With multiple backends, choose the volume type.') help='With multiple backends, choose the volume type.')
parser.add_argument('--availability_zone', metavar='availability_zone', cinder.add_argument('--availability_zone', metavar='availability_zone',
type=str, type=str,
default=None, default=None,
help='Specify availability zone.') help='Specify availability zone.')
parser.add_argument('--verbose', action='count', options, args, client = cinder.setup()
help='Print requests on stderr.') project = (options.os_project_id if options.os_project_id else
options.os_project_name)
args = parser.parse_args() tenant = (options.os_tenant_id if options.os_tenant_id else
options.os_tenant_name)
# this shouldn't raise any exception as no connection is done when util = CinderUtils(client, tenant or project)
# creating the object. But It may change, so I catch everything.
try:
nova_client = Client(args.api_version,
username=args.username,
project_id=args.tenant,
api_key=args.password,
auth_url=args.auth_url,
endpoint_type=args.endpoint_type,
http_log_debug=args.verbose)
except Exception as e:
utils.critical("Error creating cinder communication object: %s" % e)
util = Novautils(nova_client)
if args.verbose:
ch = logging.StreamHandler()
nova_client.client._logger.setLevel(logging.DEBUG)
nova_client.client._logger.addHandler(ch)
# Initiate the first connection and catch error. # Initiate the first connection and catch error.
util.check_connection() util.check_connection()
if args.endpoint_url: if options.endpoint_url:
util.mangle_url(args.endpoint_url) util.mangle_url(options.endpoint_url)
# after mangling the url, the endpoint has changed. Check that # after mangling the url, the endpoint has changed. Check that
# it's valid. # it's valid.
util.check_connection(force=True) util.check_connection(force=True)
util.check_existing_volume(args.volume_name, args.force_delete) util.check_existing_volume(options.volume_name, options.force_delete)
util.create_volume(args.volume_name, util.create_volume(options.volume_name,
args.volume_size, options.volume_size,
args.availability_zone, options.availability_zone,
args.volume_type) options.volume_type)
util.volume_ready(args.timeout) util.volume_ready(options.timeout)
util.delete_volume() util.delete_volume()
util.volume_deleted(args.timeout) util.volume_deleted(options.timeout)
if util.msgs: if util.msgs:
utils.critical(", ".join(util.msgs)) utils.critical(", ".join(util.msgs))