Replace nova client create keypair with shade. 25/59125/1
authorShobhi Jain <shobhi.jain@intel.com>
Tue, 27 Mar 2018 13:28:08 +0000 (14:28 +0100)
committerEmma Foley <emma.l.foley@intel.com>
Wed, 27 Jun 2018 16:08:57 +0000 (17:08 +0100)
Function create_keypair now uses shade client instead
of nova client.

JIRA: YARDSTICK-1088

Change-Id: I060580504d6969c5ba859ed4494082feb998d37d
Signed-off-by: Shobhi Jain <shobhi.jain@intel.com>
(cherry pick from commit c1ab98526209a761a0565afa7ccd552ba9ac7ade)

yardstick/benchmark/scenarios/lib/create_keypair.py
yardstick/common/exceptions.py
yardstick/common/openstack_utils.py
yardstick/tests/unit/benchmark/scenarios/lib/test_create_keypair.py
yardstick/tests/unit/common/test_openstack_utils.py

index f5b1fff..ee9bc44 100644 (file)
@@ -6,15 +6,11 @@
 # which accompanies this distribution, and is available at
 # http://www.apache.org/licenses/LICENSE-2.0
 ##############################################################################
-
-from __future__ import print_function
-from __future__ import absolute_import
-
 import logging
-import paramiko
 
 from yardstick.benchmark.scenarios import base
-import yardstick.common.openstack_utils as op_utils
+from yardstick.common import openstack_utils
+from yardstick.common import exceptions
 
 LOG = logging.getLogger(__name__)
 
@@ -27,10 +23,11 @@ class CreateKeypair(base.Scenario):
     def __init__(self, scenario_cfg, context_cfg):
         self.scenario_cfg = scenario_cfg
         self.context_cfg = context_cfg
-        self.options = self.scenario_cfg['options']
+        self.options = self.scenario_cfg["options"]
 
-        self.key_name = self.options.get("key_name", "yardstick_key")
-        self.key_filename = self.options.get("key_path", "/tmp/yardstick_key")
+        self.name = self.options["key_name"]
+        self.public_key = self.options.get("public_key")
+        self.shade_client = openstack_utils.get_shade_client()
 
         self.setup_done = False
 
@@ -45,27 +42,17 @@ class CreateKeypair(base.Scenario):
         if not self.setup_done:
             self.setup()
 
-        rsa_key = paramiko.RSAKey.generate(bits=2048, progress_func=None)
-        rsa_key.write_private_key_file(self.key_filename)
-        LOG.info("Writing key_file %s ...", self.key_filename)
-        with open(self.key_filename + ".pub", "w") as pubkey_file:
-            pubkey_file.write(
-                "%s %s\n" % (rsa_key.get_name(), rsa_key.get_base64()))
-        del rsa_key
-
-        keypair = op_utils.create_keypair(self.key_name,
-                                          self.key_filename + ".pub")
+        keypair = openstack_utils.create_keypair(
+            self.shade_client, self.name, public_key=self.public_key)
 
-        if keypair:
-            result.update({"keypair_create": 1})
-            LOG.info("Create keypair successful!")
-        else:
+        if not keypair:
             result.update({"keypair_create": 0})
-            LOG.info("Create keypair failed!")
-        try:
-            keys = self.scenario_cfg.get('output', '').split()
-        except KeyError:
-            pass
-        else:
-            values = [keypair.id]
-            return self._push_to_outputs(keys, values)
+            LOG.error("Create keypair failed!")
+            raise exceptions.ScenarioCreateKeypairError
+
+        result.update({"keypair_create": 1})
+        LOG.info("Create keypair successful!")
+        keys = self.scenario_cfg.get("output", '').split()
+        keypair_id = keypair["id"]
+        values = [keypair_id]
+        return self._push_to_outputs(keys, values)
index fa92179..aa71845 100644 (file)
@@ -226,6 +226,10 @@ class ScenarioDeleteServerError(YardstickException):
     message = 'Delete Server Scenario failed'
 
 
+class ScenarioCreateKeypairError(YardstickException):
+    message = 'Nova Create Keypair Scenario failed'
+
+
 class ApiServerError(YardstickException):
     message = 'An unkown exception happened to Api Server!'
 
index d469929..e79c988 100644 (file)
@@ -162,14 +162,19 @@ def get_shade_client():
 # *********************************************
 #   NOVA
 # *********************************************
-def create_keypair(name, key_path=None):    # pragma: no cover
+def create_keypair(shade_client, name, public_key=None):
+    """Create a new keypair.
+
+    :param name: Name of the keypair being created.
+    :param public_key: Public key for the new keypair.
+
+    :return: Created keypair.
+    """
     try:
-        with open(key_path) as fpubkey:
-            keypair = get_nova_client().keypairs.create(
-                name=name, public_key=fpubkey.read())
-            return keypair
-    except Exception:  # pylint: disable=broad-except
-        log.exception("Error [create_keypair(nova_client)]")
+        return shade_client.create_keypair(name, public_key=public_key)
+    except exc.OpenStackCloudException as o_exc:
+        log.error("Error [create_keypair(shade_client)]. "
+                  "Exception message, '%s'", o_exc.orig_message)
 
 
 def create_instance_and_wait_for_active(shade_client, name, image,
index 1c3d6ce..a7b683f 100644 (file)
@@ -6,22 +6,52 @@
 # which accompanies this distribution, and is available at
 # http://www.apache.org/licenses/LICENSE-2.0
 ##############################################################################
-
-import mock
+from oslo_utils import uuidutils
 import unittest
+import mock
 
+from yardstick.common import openstack_utils
+from yardstick.common import exceptions
 from yardstick.benchmark.scenarios.lib import create_keypair
 
 
 class CreateKeypairTestCase(unittest.TestCase):
-    @mock.patch.object(create_keypair, 'paramiko')
-    @mock.patch.object(create_keypair, 'op_utils')
-    def test_create_keypair(self, mock_op_utils, *args):
-        options = {
-            'key_name': 'yardstick_key',
-            'key_path': '/tmp/yardstick_key'
-        }
-        args = {"options": options}
-        obj = create_keypair.CreateKeypair(args, {})
-        obj.run({})
-        mock_op_utils.create_keypair.assert_called_once()
+
+    def setUp(self):
+
+        self._mock_create_keypair = mock.patch.object(
+            openstack_utils, 'create_keypair')
+        self.mock_create_keypair = (
+            self._mock_create_keypair.start())
+        self._mock_get_shade_client = mock.patch.object(
+            openstack_utils, 'get_shade_client')
+        self.mock_get_shade_client = self._mock_get_shade_client.start()
+        self._mock_log = mock.patch.object(create_keypair, 'LOG')
+        self.mock_log = self._mock_log.start()
+        self.args = {'options': {'key_name': 'yardstick_key'}}
+        self.result = {}
+
+        self.ckeypair_obj = create_keypair.CreateKeypair(self.args, mock.ANY)
+        self.addCleanup(self._stop_mock)
+
+    def _stop_mock(self):
+        self._mock_create_keypair.stop()
+        self._mock_get_shade_client.stop()
+        self._mock_log.stop()
+
+    def test_run(self):
+        _uuid = uuidutils.generate_uuid()
+        self.ckeypair_obj.scenario_cfg = {'output': 'id'}
+        self.mock_create_keypair.return_value = {
+            'name': 'key-name', 'type': 'ssh', 'id': _uuid}
+        output = self.ckeypair_obj.run(self.result)
+        self.assertDictEqual({'keypair_create': 1}, self.result)
+        self.assertDictEqual({'id': _uuid}, output)
+        self.mock_log.info.asset_called_once_with('Create keypair successful!')
+
+    def test_run_fail(self):
+        self.mock_create_keypair.return_value = None
+        with self.assertRaises(exceptions.ScenarioCreateKeypairError):
+            self.ckeypair_obj.run(self.result)
+        self.assertDictEqual({'keypair_create': 0}, self.result)
+        self.mock_log.error.assert_called_once_with('Create keypair failed!')
index de0f5c4..c0332c8 100644 (file)
@@ -393,3 +393,28 @@ class DeleteInstanceTestCase(unittest.TestCase):
                                                  'instance_name_id')
         mock_logger.error.assert_called_once()
         self.assertFalse(output)
+
+
+class CreateKeypairTestCase(unittest.TestCase):
+
+    def setUp(self):
+        self.mock_shade_client = mock.Mock()
+        self.name = 'key_name'
+
+    def test_create_keypair(self):
+        self.mock_shade_client.create_keypair.return_value = (
+            {'name': 'key-name', 'type': 'ssh'})
+        output = openstack_utils.create_keypair(
+            self.mock_shade_client, self.name)
+        self.assertEqual(
+            {'name': 'key-name', 'type': 'ssh'},
+            output)
+
+    @mock.patch.object(openstack_utils, 'log')
+    def test_create_keypair_fail(self, mock_logger):
+        self.mock_shade_client.create_keypair.side_effect = (
+            exc.OpenStackCloudException('error message'))
+        output = openstack_utils.create_keypair(
+            self.mock_shade_client, self.name)
+        mock_logger.error.assert_called_once()
+        self.assertIsNone(output)