From 07661de3aecf7792450e37fa32ec2cbd0bc4226c Mon Sep 17 00:00:00 2001
From: David Paterson <davpat2112@yahoo.com>
Date: Thu, 29 Oct 2015 20:15:04 -0700
Subject: [PATCH] Add cleanup to cliff-based cli framework

Also disable ability to run script in stand-alone mode so
users will use 'tempest cleanup' instead.

Change-Id: I2119acd402b0985d4a81c85501ce7265f782d37b
Implements: blueprint tempest-cli-improvements
---
 setup.cfg                      |  1 +
 tempest/cmd/cleanup.py         | 48 ++++++++++++++++++------------------------
 tempest/cmd/cleanup_service.py | 17 ++++++++-------
 3 files changed, 30 insertions(+), 36 deletions(-)
 mode change 100755 => 100644 tempest/cmd/cleanup.py

Index: tempest-7.0.0/setup.cfg
===================================================================
--- tempest-7.0.0.orig/setup.cfg
+++ tempest-7.0.0/setup.cfg
@@ -34,6 +34,7 @@ console_scripts =
 	tempest = tempest.cmd.main:main
 tempest.cm = 
 	init = tempest.cmd.init:TempestInit
+	cleanup = tempest.cmd.cleanup:TempestCleanup
 oslo.config.opts = 
 	tempest.config = tempest.config:list_opts
 
Index: tempest-7.0.0/tempest/cmd/cleanup.py
===================================================================
--- tempest-7.0.0.orig/tempest/cmd/cleanup.py
+++ tempest-7.0.0/tempest/cmd/cleanup.py
@@ -50,9 +50,9 @@ deleted and the admin user specified in
 
 Please run with **--help** to see full list of options.
 """
-import argparse
 import sys
 
+from cliff import command
 from oslo_log import log as logging
 from oslo_serialization import jsonutils as json
 
@@ -67,13 +67,17 @@ LOG = logging.getLogger(__name__)
 CONF = config.CONF
 
 
-class Cleanup(object):
+class TempestCleanup(command.Command):
 
-    def __init__(self):
+    def __init__(self, app, cmd):
+        super(TempestCleanup, self).__init__(app, cmd)
+
+    def take_action(self, parsed_args):
+        cleanup_service.init_conf()
+        self.options = parsed_args
         self.admin_mgr = clients.AdminManager()
         self.dry_run_data = {}
         self.json_data = {}
-        self._init_options()
 
         self.admin_id = ""
         self.admin_role_id = ""
@@ -86,9 +90,7 @@ class Cleanup(object):
         self.tenant_services = cleanup_service.get_tenant_cleanup_services()
         self.global_services = cleanup_service.get_global_cleanup_services()
 
-    def run(self):
-        opts = self.options
-        if opts.init_saved_state:
+        if parsed_args.init_saved_state:
             self._init_state()
             return
 
@@ -157,8 +159,8 @@ class Cleanup(object):
             tenant_data = dry_run_data["_tenants_to_clean"][tenant_id] = {}
             tenant_data['name'] = tenant_name
 
-        kwargs = {"username": CONF.identity.admin_username,
-                  "password": CONF.identity.admin_password,
+        kwargs = {"username": CONF.auth.admin_username,
+                  "password": CONF.auth.admin_password,
                   "tenant_name": tenant['name']}
         mgr = clients.Manager(credentials=cred_provider.get_credentials(
             **kwargs))
@@ -175,22 +177,21 @@ class Cleanup(object):
     def _init_admin_ids(self):
         id_cl = self.admin_mgr.identity_client
 
-        tenant = id_cl.get_tenant_by_name(CONF.identity.admin_tenant_name)
+        tenant = id_cl.get_tenant_by_name(CONF.auth.admin_tenant_name)
         self.admin_tenant_id = tenant['id']
 
         user = id_cl.get_user_by_username(self.admin_tenant_id,
-                                          CONF.identity.admin_username)
+                                          CONF.auth.admin_username)
         self.admin_id = user['id']
 
-        roles = id_cl.list_roles()
+        roles = id_cl.list_roles()['roles']
         for role in roles:
             if role['name'] == CONF.identity.admin_role:
                 self.admin_role_id = role['id']
                 break
 
-    def _init_options(self):
-        parser = argparse.ArgumentParser(
-            description='Cleanup after tempest run')
+    def get_parser(self, prog_name):
+        parser = super(TempestCleanup, self).get_parser(prog_name)
         parser.add_argument('--init-saved-state', action="store_true",
                             dest='init_saved_state', default=False,
                             help="Creates JSON file: " + SAVED_STATE_JSON +
@@ -211,13 +212,15 @@ class Cleanup(object):
                             help="Generate JSON file:" + DRY_RUN_JSON +
                             ", that reports the objects that would have "
                             "been deleted had a full cleanup been run.")
+        return parser
 
-        self.options = parser.parse_args()
+    def get_description(self):
+        return 'Cleanup after tempest run'
 
     def _add_admin(self, tenant_id):
         id_cl = self.admin_mgr.identity_client
         needs_role = True
-        roles = id_cl.list_user_roles(tenant_id, self.admin_id)
+        roles = id_cl.list_user_roles(tenant_id, self.admin_id)['roles']
         for role in roles:
             if role['id'] == self.admin_role_id:
                 needs_role = False
@@ -282,14 +285,3 @@ class Cleanup(object):
         except Exception as ex:
             LOG.exception("Exception parsing saved state json : %s" % ex)
             sys.exit(ex)
-
-
-def main():
-    cleanup_service.init_conf()
-    cleanup = Cleanup()
-    cleanup.run()
-    LOG.info('Cleanup finished!')
-    return 0
-
-if __name__ == "__main__":
-    sys.exit(main())
Index: tempest-7.0.0/tempest/cmd/cleanup_service.py
===================================================================
--- tempest-7.0.0.orig/tempest/cmd/cleanup_service.py
+++ tempest-7.0.0/tempest/cmd/cleanup_service.py
@@ -69,10 +69,10 @@ def init_conf():
     CONF_PRIV_NETWORK_NAME = CONF.compute.fixed_network_name
     CONF_PUB_NETWORK = CONF.network.public_network_id
     CONF_PUB_ROUTER = CONF.network.public_router_id
-    CONF_TENANTS = [CONF.identity.admin_tenant_name,
+    CONF_TENANTS = [CONF.auth.admin_tenant_name,
                     CONF.identity.tenant_name,
                     CONF.identity.alt_tenant_name]
-    CONF_USERS = [CONF.identity.admin_username, CONF.identity.username,
+    CONF_USERS = [CONF.auth.admin_username, CONF.identity.username,
                   CONF.identity.alt_username]
 
     if IS_NEUTRON:
@@ -147,7 +147,7 @@ class SnapshotService(BaseService):
 
     def list(self):
         client = self.client
-        snaps = client.list_snapshots()
+        snaps = client.list_snapshots()['snapshots']
         LOG.debug("List count, %s Snapshots" % len(snaps))
         return snaps
 
@@ -169,6 +169,7 @@ class ServerService(BaseService):
     def __init__(self, manager, **kwargs):
         super(ServerService, self).__init__(kwargs)
         self.client = manager.servers_client
+        self.server_groups_client = manager.server_groups_client
 
     def list(self):
         client = self.client
@@ -194,7 +195,7 @@ class ServerService(BaseService):
 class ServerGroupService(ServerService):
 
     def list(self):
-        client = self.client
+        client = self.server_groups_client
         sgs = client.list_server_groups()['server_groups']
         LOG.debug("List count, %s Server Groups" % len(sgs))
         return sgs
@@ -812,7 +813,7 @@ class UserService(IdentityService):
 
     def list(self):
         client = self.client
-        users = client.get_users()
+        users = client.get_users()['users']
 
         if not self.is_save_state:
             users = [user for user in users if user['id']
@@ -824,7 +825,7 @@ class UserService(IdentityService):
 
         elif not self.is_save_state:  # Never delete admin user
             users = [user for user in users if user['name'] !=
-                     CONF.identity.admin_username]
+                     CONF.auth.admin_username]
 
         LOG.debug("List count, %s Users after reconcile" % len(users))
         return users
@@ -854,7 +855,7 @@ class RoleService(IdentityService):
     def list(self):
         client = self.client
         try:
-            roles = client.list_roles()
+            roles = client.list_roles()['roles']
             # reconcile roles with saved state and never list admin role
             if not self.is_save_state:
                 roles = [role for role in roles if
@@ -895,7 +896,7 @@ class TenantService(IdentityService):
         if not self.is_save_state:
             tenants = [tenant for tenant in tenants if (tenant['id']
                        not in self.saved_state_json['tenants'].keys()
-                       and tenant['name'] != CONF.identity.admin_tenant_name)]
+                       and tenant['name'] != CONF.auth.admin_tenant_name)]
 
         if self.is_preserve:
             tenants = [tenant for tenant in tenants if tenant['name']
