Merge "Clean up properties (metadata) formatting"

This commit is contained in:
Jenkins 2013-07-23 15:25:26 +00:00 committed by Gerrit Code Review
commit f175d12247
4 changed files with 155 additions and 79 deletions
openstackclient
common
compute/v2
volume/v1

@ -1,4 +1,4 @@
# Copyright 2012-2013 OpenStack, LLC. # Copyright 2012-2013 OpenStack Foundation
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # 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 # not use this file except in compliance with the License. You may obtain
@ -73,6 +73,20 @@ def find_resource(manager, name_or_id):
raise raise
def format_dict(data):
"""Return a formatted string of key value pairs
:param data: a dict
:param format: optional formatting hints
:rtype: a string formatted to key='value'
"""
output = ""
for s in data:
output = output + s + "='" + data[s] + "', "
return output[:-2]
def get_item_properties(item, fields, mixed_case_fields=[], formatters={}): def get_item_properties(item, fields, mixed_case_fields=[], formatters={}):
"""Return a tuple containing the item properties. """Return a tuple containing the item properties.
@ -85,14 +99,14 @@ def get_item_properties(item, fields, mixed_case_fields=[], formatters={}):
row = [] row = []
for field in fields: for field in fields:
if field in formatters: if field in mixed_case_fields:
row.append(formatters[field](item)) field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
data = getattr(item, field_name, '')
if field in formatters:
row.append(formatters[field](data))
else: else:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
data = getattr(item, field_name, '')
row.append(data) row.append(data)
return tuple(row) return tuple(row)

@ -1,4 +1,4 @@
# Copyright 2012-2013 OpenStack, LLC. # Copyright 2012-2013 OpenStack Foundation
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # 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 # not use this file except in compliance with the License. You may obtain
@ -13,7 +13,7 @@
# under the License. # under the License.
# #
"""Server action implementations""" """Compute v2 Server action implementations"""
import logging import logging
import os import os
@ -25,17 +25,18 @@ from cliff import show
from novaclient.v1_1 import servers from novaclient.v1_1 import servers
from openstackclient.common import exceptions from openstackclient.common import exceptions
from openstackclient.common import parseractions
from openstackclient.common import utils from openstackclient.common import utils
def _format_servers_list_networks(server): def _format_servers_list_networks(networks):
"""Return a string containing the networks a server is attached to. """Return a formatted string of a server's networks
:param server: a single Server resource :param server: a Server.networks field
:rtype: a string of formatted network addresses :rtype: a string of formatted network addresses
""" """
output = [] output = []
for (network, addresses) in server.networks.items(): for (network, addresses) in networks.items():
if not addresses: if not addresses:
continue continue
addresses_csv = ', '.join(addresses) addresses_csv = ', '.join(addresses)
@ -73,7 +74,12 @@ def _prep_server_detail(compute_client, server):
# NOTE(dtroyer): novaclient splits these into separate entries... # NOTE(dtroyer): novaclient splits these into separate entries...
# Format addresses in a useful way # Format addresses in a useful way
info['addresses'] = _format_servers_list_networks(server) info['addresses'] = _format_servers_list_networks(server.networks)
# Map 'metadata' field to 'properties'
info.update(
{'properties': utils.format_dict(info.pop('metadata'))}
)
# Remove values that are long and not too useful # Remove values that are long and not too useful
info.pop('links', None) info.pop('links', None)
@ -116,7 +122,7 @@ def _wait_for_status(poll_fn, obj_id, final_ok_states, poll_period=5,
class CreateServer(show.ShowOne): class CreateServer(show.ShowOne):
"""Create server command""" """Create a new server"""
log = logging.getLogger(__name__ + '.CreateServer') log = logging.getLogger(__name__ + '.CreateServer')
@ -150,9 +156,8 @@ class CreateServer(show.ShowOne):
parser.add_argument( parser.add_argument(
'--property', '--property',
metavar='<key=value>', metavar='<key=value>',
action='append', action=parseractions.KeyValueAction,
default=[], help='Set a property on this server '
help='Property to store for this server '
'(repeat for multiple values)') '(repeat for multiple values)')
parser.add_argument( parser.add_argument(
'--file', '--file',
@ -228,8 +233,6 @@ class CreateServer(show.ShowOne):
boot_args = [parsed_args.server_name, image, flavor] boot_args = [parsed_args.server_name, image, flavor]
meta = dict(v.split('=', 1) for v in parsed_args.property)
files = {} files = {}
for f in parsed_args.file: for f in parsed_args.file:
dst, src = f.split('=', 1) dst, src = f.split('=', 1)
@ -288,7 +291,7 @@ class CreateServer(show.ShowOne):
config_drive = parsed_args.config_drive config_drive = parsed_args.config_drive
boot_kwargs = dict( boot_kwargs = dict(
meta=meta, meta=parsed_args.property,
files=files, files=files,
reservation_id=None, reservation_id=None,
min_count=parsed_args.min, min_count=parsed_args.min,
@ -337,7 +340,7 @@ class DeleteServer(command.Command):
class ListServer(lister.Lister): class ListServer(lister.Lister):
"""List server command""" """List servers"""
log = logging.getLogger(__name__ + '.ListServer') log = logging.getLogger(__name__ + '.ListServer')
@ -385,6 +388,11 @@ class ListServer(lister.Lister):
action='store_true', action='store_true',
default=bool(int(os.environ.get("ALL_TENANTS", 0))), default=bool(int(os.environ.get("ALL_TENANTS", 0))),
help='display information from all tenants (admin only)') help='display information from all tenants (admin only)')
parser.add_argument(
'--long',
action='store_true',
default=False,
help='Additional fields are listed in output')
return parser return parser
def take_action(self, parsed_args): def take_action(self, parsed_args):
@ -403,13 +411,43 @@ class ListServer(lister.Lister):
'all_tenants': parsed_args.all_tenants, 'all_tenants': parsed_args.all_tenants,
} }
self.log.debug('search options: %s', search_opts) self.log.debug('search options: %s', search_opts)
# FIXME(dhellmann): Consider adding other columns
columns = ('ID', 'Name', 'Status', 'Networks') if parsed_args.long:
columns = (
'ID',
'Name',
'Status',
'Networks',
'OS-EXT-AZ:availability_zone',
'OS-EXT-SRV-ATTR:host',
'Metadata',
)
column_headers = (
'ID',
'Name',
'Status',
'Networks',
'Availability Zone',
'Host',
'Properties',
)
mixed_case_fields = [
'OS-EXT-AZ:availability_zone',
'OS-EXT-SRV-ATTR:host',
]
else:
columns = ('ID', 'Name', 'Status', 'Networks')
column_headers = columns
mixed_case_fields = []
data = compute_client.servers.list(search_opts=search_opts) data = compute_client.servers.list(search_opts=search_opts)
return (columns, return (column_headers,
(utils.get_item_properties( (utils.get_item_properties(
s, columns, s, columns,
formatters={'Networks': _format_servers_list_networks}, mixed_case_fields=mixed_case_fields,
formatters={
'Networks': _format_servers_list_networks,
'Metadata': utils.format_dict,
},
) for s in data)) ) for s in data))

@ -1,4 +1,4 @@
# Copyright 2012-2013 OpenStack, LLC. # Copyright 2012-2013 OpenStack Foundation
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # 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 # not use this file except in compliance with the License. You may obtain
@ -26,7 +26,7 @@ from openstackclient.common import utils
class CreateVolumeType(show.ShowOne): class CreateVolumeType(show.ShowOne):
"""Create volume type command""" """Create new volume type"""
log = logging.getLogger(__name__ + '.CreateVolumeType') log = logging.getLogger(__name__ + '.CreateVolumeType')
@ -37,6 +37,13 @@ class CreateVolumeType(show.ShowOne):
metavar='<name>', metavar='<name>',
help='New volume type name', help='New volume type name',
) )
parser.add_argument(
'--property',
metavar='<key=value>',
action=parseractions.KeyValueAction,
help='Property to add for this volume type '
'(repeat option to set multiple properties)',
)
return parser return parser
def take_action(self, parsed_args): def take_action(self, parsed_args):
@ -45,6 +52,13 @@ class CreateVolumeType(show.ShowOne):
volume_type = volume_client.volume_types.create( volume_type = volume_client.volume_types.create(
parsed_args.name parsed_args.name
) )
if parsed_args.property:
volume_type.set_keys(parsed_args.property)
# Map 'extra_specs' column to 'properties'
volume_type._info.update(
{'properties': utils.format_dict(
volume_type._info.pop('extra_specs'))}
)
info = {} info = {}
info.update(volume_type._info) info.update(volume_type._info)
@ -52,7 +66,7 @@ class CreateVolumeType(show.ShowOne):
class DeleteVolumeType(command.Command): class DeleteVolumeType(command.Command):
"""Delete volume type command""" """Delete volume type"""
log = logging.getLogger(__name__ + '.DeleteVolumeType') log = logging.getLogger(__name__ + '.DeleteVolumeType')
@ -75,7 +89,7 @@ class DeleteVolumeType(command.Command):
class ListVolumeType(lister.Lister): class ListVolumeType(lister.Lister):
"""List volume type command""" """List volume types"""
log = logging.getLogger(__name__ + '.ListVolumeType') log = logging.getLogger(__name__ + '.ListVolumeType')
@ -92,18 +106,20 @@ class ListVolumeType(lister.Lister):
self.log.debug('take_action(%s)' % parsed_args) self.log.debug('take_action(%s)' % parsed_args)
if parsed_args.long: if parsed_args.long:
columns = ('ID', 'Name', 'Extra Specs') columns = ('ID', 'Name', 'Extra Specs')
column_headers = ('ID', 'Name', 'Properties')
else: else:
columns = ('ID', 'Name') columns = ('ID', 'Name')
column_headers = columns
data = self.app.client_manager.volume.volume_types.list() data = self.app.client_manager.volume.volume_types.list()
return (columns, return (column_headers,
(utils.get_item_properties( (utils.get_item_properties(
s, columns, s, columns,
formatters={'Extra Specs': _format_type_list_extra_specs}, formatters={'Extra Specs': utils.format_dict},
) for s in data)) ) for s in data))
class SetVolumeType(command.Command): class SetVolumeType(command.Command):
"""Set volume type command""" """Set volume type property"""
log = logging.getLogger(__name__ + '.SetVolumeType') log = logging.getLogger(__name__ + '.SetVolumeType')
@ -136,7 +152,7 @@ class SetVolumeType(command.Command):
class UnsetVolumeType(command.Command): class UnsetVolumeType(command.Command):
"""Unset volume type command""" """Unset volume type property"""
log = logging.getLogger(__name__ + '.UnsetVolumeType') log = logging.getLogger(__name__ + '.UnsetVolumeType')
@ -173,17 +189,3 @@ class UnsetVolumeType(command.Command):
else: else:
self.app.log.error("No changes requested\n") self.app.log.error("No changes requested\n")
return return
def _format_type_list_extra_specs(vol_type):
"""Return a string containing the key value pairs
:param server: a single VolumeType resource
:rtype: a string formatted to key=value
"""
keys = vol_type.get_keys()
output = ""
for s in keys:
output = output + s + "=" + keys[s] + "; "
return output

@ -1,4 +1,4 @@
# Copyright 2012-2013 OpenStack, LLC. # Copyright 2012-2013 OpenStack Foundation
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # 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 # not use this file except in compliance with the License. You may obtain
@ -26,7 +26,7 @@ from openstackclient.common import utils
class CreateVolume(show.ShowOne): class CreateVolume(show.ShowOne):
"""Create volume command""" """Create new volume"""
log = logging.getLogger(__name__ + '.CreateVolume') log = logging.getLogger(__name__ + '.CreateVolume')
@ -119,12 +119,16 @@ class CreateVolume(show.ShowOne):
parsed_args.property, parsed_args.property,
parsed_args.image parsed_args.image
) )
# Map 'metadata' column to 'properties'
volume._info.update(
{'properties': utils.format_dict(volume._info.pop('metadata'))}
)
return zip(*sorted(volume._info.iteritems())) return zip(*sorted(volume._info.iteritems()))
class DeleteVolume(command.Command): class DeleteVolume(command.Command):
"""Delete volume command""" """Delete volume"""
log = logging.getLogger(__name__ + '.DeleteVolume') log = logging.getLogger(__name__ + '.DeleteVolume')
@ -157,7 +161,7 @@ class DeleteVolume(command.Command):
class ListVolume(lister.Lister): class ListVolume(lister.Lister):
"""List volume command""" """List volumes"""
log = logging.getLogger(__name__ + '.ListVolume') log = logging.getLogger(__name__ + '.ListVolume')
@ -190,12 +194,42 @@ class ListVolume(lister.Lister):
def take_action(self, parsed_args): def take_action(self, parsed_args):
self.log.debug('take_action(%s)' % parsed_args) self.log.debug('take_action(%s)' % parsed_args)
columns = ('ID', 'Status', 'Display Name', 'Size',
'Volume Type', 'Bootable', 'Attached to')
if parsed_args.long: if parsed_args.long:
columns = ('ID', 'Status', 'Display Name', 'Size', columns = (
'Volume Type', 'Bootable', 'Attached to', 'Meta-data') 'ID',
'Display Name',
'Status',
'Size',
'Volume Type',
'Bootable',
'Attached to',
'Metadata',
)
column_headers = (
'ID',
'Display Name',
'Status',
'Size',
'Type',
'Bootable',
'Attached',
'Properties',
)
else:
columns = (
'ID',
'Display Name',
'Status',
'Size',
'Attached to',
)
column_headers = (
'ID',
'Display Name',
'Status',
'Size',
'Attached',
)
search_opts = { search_opts = {
'all_tenants': parsed_args.all_tenants, 'all_tenants': parsed_args.all_tenants,
'display_name': parsed_args.name, 'display_name': parsed_args.name,
@ -205,15 +239,15 @@ class ListVolume(lister.Lister):
volume_client = self.app.client_manager.volume volume_client = self.app.client_manager.volume
data = volume_client.volumes.list(search_opts=search_opts) data = volume_client.volumes.list(search_opts=search_opts)
return (columns, return (column_headers,
(utils.get_item_properties( (utils.get_item_properties(
s, columns, s, columns,
formatters={'Meta-data': _format_meta_data}, formatters={'Metadata': utils.format_dict},
) for s in data)) ) for s in data))
class SetVolume(command.Command): class SetVolume(command.Command):
"""Set volume command""" """Set volume properties"""
log = logging.getLogger(__name__ + '.SetVolume') log = logging.getLogger(__name__ + '.SetVolume')
@ -249,7 +283,6 @@ class SetVolume(command.Command):
volume = utils.find_resource(volume_client.volumes, parsed_args.volume) volume = utils.find_resource(volume_client.volumes, parsed_args.volume)
if parsed_args.property: if parsed_args.property:
print "property: %s" % parsed_args.property
volume_client.volumes.set_metadata(volume.id, parsed_args.property) volume_client.volumes.set_metadata(volume.id, parsed_args.property)
kwargs = {} kwargs = {}
@ -258,7 +291,6 @@ class SetVolume(command.Command):
if parsed_args.description: if parsed_args.description:
kwargs['display_description'] = parsed_args.description kwargs['display_description'] = parsed_args.description
if kwargs: if kwargs:
print "kwargs: %s" % kwargs
volume_client.volumes.update(volume.id, **kwargs) volume_client.volumes.update(volume.id, **kwargs)
if not kwargs and not parsed_args.property: if not kwargs and not parsed_args.property:
@ -268,7 +300,7 @@ class SetVolume(command.Command):
class ShowVolume(show.ShowOne): class ShowVolume(show.ShowOne):
"""Show volume command""" """Show specific volume"""
log = logging.getLogger(__name__ + '.ShowVolume') log = logging.getLogger(__name__ + '.ShowVolume')
@ -285,12 +317,16 @@ class ShowVolume(show.ShowOne):
self.log.debug('take_action(%s)' % parsed_args) self.log.debug('take_action(%s)' % parsed_args)
volume_client = self.app.client_manager.volume volume_client = self.app.client_manager.volume
volume = utils.find_resource(volume_client.volumes, parsed_args.volume) volume = utils.find_resource(volume_client.volumes, parsed_args.volume)
# Map 'metadata' column to 'properties'
volume._info.update(
{'properties': utils.format_dict(volume._info.pop('metadata'))}
)
return zip(*sorted(volume._info.iteritems())) return zip(*sorted(volume._info.iteritems()))
class UnsetVolume(command.Command): class UnsetVolume(command.Command):
"""Unset volume command""" """Unset volume properties"""
log = logging.getLogger(__name__ + '.UnsetVolume') log = logging.getLogger(__name__ + '.UnsetVolume')
@ -325,17 +361,3 @@ class UnsetVolume(command.Command):
else: else:
self.app.log.error("No changes requested\n") self.app.log.error("No changes requested\n")
return return
def _format_meta_data(volume):
"""Return a string containing the key value pairs
:param server: a single volume resource
:rtype: a string formatted to key=value
"""
keys = volume.metadata
output = ""
for s in keys:
output = output + s + "=" + keys[s] + "; "
return output