From 818c94875221f606ed56f276c1cbd320a9106754 Mon Sep 17 00:00:00 2001
From: Dean Troyer <dtroyer@gmail.com>
Date: Thu, 18 Jul 2013 11:10:34 -0500
Subject: [PATCH] Clean up properties (metadata) formatting

* Reformat default dict output to key='value' using utils.format_dict()
* Changes utils.get_item_properties() to pass the specific field to
  the formatter function rather than the entire resource object, this
  allows the formatter to handle multiple attributes.
* Updates server, volume, volume type commands

Change-Id: I90eebf6b84ae200532f09cd925f371598ea54a64
---
 openstackclient/common/utils.py      | 30 +++++++---
 openstackclient/compute/v2/server.py | 76 +++++++++++++++++++-------
 openstackclient/volume/v1/type.py    | 46 ++++++++--------
 openstackclient/volume/v1/volume.py  | 82 ++++++++++++++++++----------
 4 files changed, 155 insertions(+), 79 deletions(-)

diff --git a/openstackclient/common/utils.py b/openstackclient/common/utils.py
index 06542887e2..2f2f5718f5 100644
--- a/openstackclient/common/utils.py
+++ b/openstackclient/common/utils.py
@@ -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
 #   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
 
 
+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={}):
     """Return a tuple containing the item properties.
 
@@ -85,14 +99,14 @@ def get_item_properties(item, fields, mixed_case_fields=[], formatters={}):
     row = []
 
     for field in fields:
-        if field in formatters:
-            row.append(formatters[field](item))
+        if field in mixed_case_fields:
+            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:
-            if field in mixed_case_fields:
-                field_name = field.replace(' ', '_')
-            else:
-                field_name = field.lower().replace(' ', '_')
-            data = getattr(item, field_name, '')
             row.append(data)
     return tuple(row)
 
diff --git a/openstackclient/compute/v2/server.py b/openstackclient/compute/v2/server.py
index e78144b084..a8c86a2e66 100644
--- a/openstackclient/compute/v2/server.py
+++ b/openstackclient/compute/v2/server.py
@@ -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
 #   not use this file except in compliance with the License. You may obtain
@@ -13,7 +13,7 @@
 #   under the License.
 #
 
-"""Server action implementations"""
+"""Compute v2 Server action implementations"""
 
 import logging
 import os
@@ -25,17 +25,18 @@ from cliff import show
 
 from novaclient.v1_1 import servers
 from openstackclient.common import exceptions
+from openstackclient.common import parseractions
 from openstackclient.common import utils
 
 
-def _format_servers_list_networks(server):
-    """Return a string containing the networks a server is attached to.
+def _format_servers_list_networks(networks):
+    """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
     """
     output = []
-    for (network, addresses) in server.networks.items():
+    for (network, addresses) in networks.items():
         if not addresses:
             continue
         addresses_csv = ', '.join(addresses)
@@ -73,7 +74,12 @@ def _prep_server_detail(compute_client, server):
 
     # NOTE(dtroyer): novaclient splits these into separate entries...
     # 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
     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):
-    """Create server command"""
+    """Create a new server"""
 
     log = logging.getLogger(__name__ + '.CreateServer')
 
@@ -150,9 +156,8 @@ class CreateServer(show.ShowOne):
         parser.add_argument(
             '--property',
             metavar='<key=value>',
-            action='append',
-            default=[],
-            help='Property to store for this server '
+            action=parseractions.KeyValueAction,
+            help='Set a property on this server '
                  '(repeat for multiple values)')
         parser.add_argument(
             '--file',
@@ -228,8 +233,6 @@ class CreateServer(show.ShowOne):
 
         boot_args = [parsed_args.server_name, image, flavor]
 
-        meta = dict(v.split('=', 1) for v in parsed_args.property)
-
         files = {}
         for f in parsed_args.file:
             dst, src = f.split('=', 1)
@@ -288,7 +291,7 @@ class CreateServer(show.ShowOne):
             config_drive = parsed_args.config_drive
 
         boot_kwargs = dict(
-            meta=meta,
+            meta=parsed_args.property,
             files=files,
             reservation_id=None,
             min_count=parsed_args.min,
@@ -337,7 +340,7 @@ class DeleteServer(command.Command):
 
 
 class ListServer(lister.Lister):
-    """List server command"""
+    """List servers"""
 
     log = logging.getLogger(__name__ + '.ListServer')
 
@@ -385,6 +388,11 @@ class ListServer(lister.Lister):
             action='store_true',
             default=bool(int(os.environ.get("ALL_TENANTS", 0))),
             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
 
     def take_action(self, parsed_args):
@@ -403,13 +411,43 @@ class ListServer(lister.Lister):
             'all_tenants': parsed_args.all_tenants,
         }
         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)
-        return (columns,
+        return (column_headers,
                 (utils.get_item_properties(
                     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))
 
 
diff --git a/openstackclient/volume/v1/type.py b/openstackclient/volume/v1/type.py
index dab21d9911..0d9fdb39de 100644
--- a/openstackclient/volume/v1/type.py
+++ b/openstackclient/volume/v1/type.py
@@ -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
 #   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):
-    """Create volume type command"""
+    """Create new volume type"""
 
     log = logging.getLogger(__name__ + '.CreateVolumeType')
 
@@ -37,6 +37,13 @@ class CreateVolumeType(show.ShowOne):
             metavar='<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
 
     def take_action(self, parsed_args):
@@ -45,6 +52,13 @@ class CreateVolumeType(show.ShowOne):
         volume_type = volume_client.volume_types.create(
             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.update(volume_type._info)
@@ -52,7 +66,7 @@ class CreateVolumeType(show.ShowOne):
 
 
 class DeleteVolumeType(command.Command):
-    """Delete volume type command"""
+    """Delete volume type"""
 
     log = logging.getLogger(__name__ + '.DeleteVolumeType')
 
@@ -75,7 +89,7 @@ class DeleteVolumeType(command.Command):
 
 
 class ListVolumeType(lister.Lister):
-    """List volume type command"""
+    """List volume types"""
 
     log = logging.getLogger(__name__ + '.ListVolumeType')
 
@@ -92,18 +106,20 @@ class ListVolumeType(lister.Lister):
         self.log.debug('take_action(%s)' % parsed_args)
         if parsed_args.long:
             columns = ('ID', 'Name', 'Extra Specs')
+            column_headers = ('ID', 'Name', 'Properties')
         else:
             columns = ('ID', 'Name')
+            column_headers = columns
         data = self.app.client_manager.volume.volume_types.list()
-        return (columns,
+        return (column_headers,
                 (utils.get_item_properties(
                     s, columns,
-                    formatters={'Extra Specs': _format_type_list_extra_specs},
+                    formatters={'Extra Specs': utils.format_dict},
                 ) for s in data))
 
 
 class SetVolumeType(command.Command):
-    """Set volume type command"""
+    """Set volume type property"""
 
     log = logging.getLogger(__name__ + '.SetVolumeType')
 
@@ -136,7 +152,7 @@ class SetVolumeType(command.Command):
 
 
 class UnsetVolumeType(command.Command):
-    """Unset volume type command"""
+    """Unset volume type property"""
 
     log = logging.getLogger(__name__ + '.UnsetVolumeType')
 
@@ -173,17 +189,3 @@ class UnsetVolumeType(command.Command):
         else:
             self.app.log.error("No changes requested\n")
         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
diff --git a/openstackclient/volume/v1/volume.py b/openstackclient/volume/v1/volume.py
index f1e421f488..b74fe45249 100644
--- a/openstackclient/volume/v1/volume.py
+++ b/openstackclient/volume/v1/volume.py
@@ -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
 #   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):
-    """Create volume command"""
+    """Create new volume"""
 
     log = logging.getLogger(__name__ + '.CreateVolume')
 
@@ -119,12 +119,16 @@ class CreateVolume(show.ShowOne):
             parsed_args.property,
             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()))
 
 
 class DeleteVolume(command.Command):
-    """Delete volume command"""
+    """Delete volume"""
 
     log = logging.getLogger(__name__ + '.DeleteVolume')
 
@@ -157,7 +161,7 @@ class DeleteVolume(command.Command):
 
 
 class ListVolume(lister.Lister):
-    """List volume command"""
+    """List volumes"""
 
     log = logging.getLogger(__name__ + '.ListVolume')
 
@@ -190,12 +194,42 @@ class ListVolume(lister.Lister):
     def take_action(self, 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:
-            columns = ('ID', 'Status', 'Display Name', 'Size',
-                       'Volume Type', 'Bootable', 'Attached to', 'Meta-data')
-
+            columns = (
+                '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 = {
             'all_tenants': parsed_args.all_tenants,
             'display_name': parsed_args.name,
@@ -205,15 +239,15 @@ class ListVolume(lister.Lister):
         volume_client = self.app.client_manager.volume
         data = volume_client.volumes.list(search_opts=search_opts)
 
-        return (columns,
+        return (column_headers,
                 (utils.get_item_properties(
                     s, columns,
-                    formatters={'Meta-data': _format_meta_data},
+                    formatters={'Metadata': utils.format_dict},
                 ) for s in data))
 
 
 class SetVolume(command.Command):
-    """Set volume command"""
+    """Set volume properties"""
 
     log = logging.getLogger(__name__ + '.SetVolume')
 
@@ -249,7 +283,6 @@ class SetVolume(command.Command):
         volume = utils.find_resource(volume_client.volumes, parsed_args.volume)
 
         if parsed_args.property:
-            print "property: %s" % parsed_args.property
             volume_client.volumes.set_metadata(volume.id, parsed_args.property)
 
         kwargs = {}
@@ -258,7 +291,6 @@ class SetVolume(command.Command):
         if parsed_args.description:
             kwargs['display_description'] = parsed_args.description
         if kwargs:
-            print "kwargs: %s" % kwargs
             volume_client.volumes.update(volume.id, **kwargs)
 
         if not kwargs and not parsed_args.property:
@@ -268,7 +300,7 @@ class SetVolume(command.Command):
 
 
 class ShowVolume(show.ShowOne):
-    """Show volume command"""
+    """Show specific volume"""
 
     log = logging.getLogger(__name__ + '.ShowVolume')
 
@@ -285,12 +317,16 @@ class ShowVolume(show.ShowOne):
         self.log.debug('take_action(%s)' % parsed_args)
         volume_client = self.app.client_manager.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()))
 
 
 class UnsetVolume(command.Command):
-    """Unset volume command"""
+    """Unset volume properties"""
 
     log = logging.getLogger(__name__ + '.UnsetVolume')
 
@@ -325,17 +361,3 @@ class UnsetVolume(command.Command):
         else:
             self.app.log.error("No changes requested\n")
         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