-# Copyright (c) 2016 Cable Television Laboratories, Inc. ("CableLabs")
+# Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
# and others. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
-import os
-from Crypto.PublicKey import RSA
+import os
+from neutronclient.common.utils import str2bool
from novaclient.exceptions import NotFound
+from snaps import file_utils
+from snaps.openstack.openstack_creator import OpenStackComputeObject
from snaps.openstack.utils import nova_utils
__author__ = 'spisarski'
logger = logging.getLogger('OpenStackKeypair')
-class OpenStackKeypair:
+class OpenStackKeypair(OpenStackComputeObject):
"""
- Class responsible for creating a keypair in OpenStack
+ Class responsible for managing a keypair in OpenStack
"""
def __init__(self, os_creds, keypair_settings):
:param os_creds: The credentials to connect with OpenStack
:param keypair_settings: The settings used to create a keypair
"""
- self.__os_creds = os_creds
+ super(self.__class__, self).__init__(os_creds)
+
self.keypair_settings = keypair_settings
- self.__nova = nova_utils.nova_client(os_creds)
+ self.__delete_keys_on_clean = True
# Attributes instantiated on create()
self.__keypair = None
- def create(self, cleanup=False):
+ def initialize(self):
"""
- Responsible for creating the keypair object.
- :param cleanup: Denotes whether or not this is being called for cleanup or not
+ Loads the existing OpenStack Keypair
+ :return: The Keypair domain object or None
"""
- logger.info('Creating keypair %s...' % self.keypair_settings.name)
+ super(self.__class__, self).initialize()
try:
- self.__keypair = nova_utils.get_keypair_by_name(self.__nova, self.keypair_settings.name)
+ self.__keypair = nova_utils.get_keypair_by_name(
+ self._nova, self.keypair_settings.name)
+ return self.__keypair
+ except Exception as e:
+ logger.warn('Cannot load existing keypair - %s', e)
+
+ def create(self):
+ """
+ Responsible for creating the keypair object.
+ :return: The Keypair domain object or None
+ """
+ self.initialize()
+
+ if not self.__keypair:
+ logger.info('Creating keypair %s...' % self.keypair_settings.name)
+
+ if self.keypair_settings.public_filepath and os.path.isfile(
+ self.keypair_settings.public_filepath):
+ logger.info("Uploading existing keypair")
+ self.__keypair = nova_utils.upload_keypair_file(
+ self._nova, self.keypair_settings.name,
+ self.keypair_settings.public_filepath)
- if not self.__keypair and not cleanup:
- if self.keypair_settings.public_filepath and os.path.isfile(self.keypair_settings.public_filepath):
- logger.info("Uploading existing keypair")
- self.__keypair = nova_utils.upload_keypair_file(self.__nova, self.keypair_settings.name,
- self.keypair_settings.public_filepath)
+ if self.keypair_settings.delete_on_clean is not None:
+ delete_on_clean = self.keypair_settings.delete_on_clean
+ self.__delete_keys_on_clean = delete_on_clean
else:
- logger.info("Creating new keypair")
- # TODO - Make this value configurable
- keys = RSA.generate(1024)
- self.__keypair = nova_utils.upload_keypair(self.__nova, self.keypair_settings.name,
- keys.publickey().exportKey('OpenSSH'))
- nova_utils.save_keys_to_files(keys, self.keypair_settings.public_filepath,
- self.keypair_settings.private_filepath)
+ self.__delete_keys_on_clean = False
+ else:
+ logger.info("Creating new keypair")
+ keys = nova_utils.create_keys(self.keypair_settings.key_size)
+ self.__keypair = nova_utils.upload_keypair(
+ self._nova, self.keypair_settings.name,
+ nova_utils.public_key_openssh(keys))
+ file_utils.save_keys_to_files(
+ keys, self.keypair_settings.public_filepath,
+ self.keypair_settings.private_filepath)
+
+ if self.keypair_settings.delete_on_clean is not None:
+ delete_on_clean = self.keypair_settings.delete_on_clean
+ self.__delete_keys_on_clean = delete_on_clean
+ else:
+ self.__delete_keys_on_clean = True
+ elif self.__keypair and not os.path.isfile(
+ self.keypair_settings.private_filepath):
+ logger.warn("The public key already exist in OpenStack \
+ but the private key file is not found ..")
- return self.__keypair
- except Exception as e:
- logger.error('Unexpected error creating keypair named - ' + self.keypair_settings.name)
- self.clean()
- raise Exception(e.message)
+ return self.__keypair
def clean(self):
"""
"""
if self.__keypair:
try:
- nova_utils.delete_keypair(self.__nova, self.__keypair)
+ nova_utils.delete_keypair(self._nova, self.__keypair)
except NotFound:
pass
self.__keypair = None
+ if self.__delete_keys_on_clean:
+ if (self.keypair_settings.public_filepath and
+ file_utils.file_exists(
+ self.keypair_settings.public_filepath)):
+ expanded_path = os.path.expanduser(
+ self.keypair_settings.public_filepath)
+ os.chmod(expanded_path, 0o755)
+ os.remove(expanded_path)
+ logger.info('Deleted public key file [%s]', expanded_path)
+ if (self.keypair_settings.private_filepath and
+ file_utils.file_exists(
+ self.keypair_settings.private_filepath)):
+ expanded_path = os.path.expanduser(
+ self.keypair_settings.private_filepath)
+ os.chmod(expanded_path, 0o755)
+ os.remove(expanded_path)
+ logger.info('Deleted private key file [%s]', expanded_path)
+
def get_keypair(self):
"""
Returns the OpenStack keypair object
Class representing a keypair configuration
"""
- def __init__(self, config=None, name=None, public_filepath=None, private_filepath=None):
+ def __init__(self, **kwargs):
"""
Constructor - all parameters are optional
- :param config: Should be a dict object containing the configuration settings using the attribute names below
- as each member's the key and overrides any of the other parameters.
:param name: The keypair name.
- :param public_filepath: The path to/from the filesystem where the public key file is or will be stored
- :param private_filepath: The path where the generated private key file will be stored
+ :param public_filepath: The path to/from the filesystem where the
+ public key file is or will be stored
+ :param private_filepath: The path where the generated private key file
+ will be stored
+ :param key_size: The number of bytes for the key size when it needs to
+ be generated (Must be >=512 default 1024)
+ :param delete_on_clean: when True, the key files will be deleted when
+ OpenStackKeypair#clean() is called
:return:
"""
- if config:
- self.name = config.get('name')
- self.public_filepath = config.get('public_filepath')
- self.private_filepath = config.get('private_filepath')
+ self.name = kwargs.get('name')
+ self.public_filepath = kwargs.get('public_filepath')
+ self.private_filepath = kwargs.get('private_filepath')
+ self.key_size = int(kwargs.get('key_size', 1024))
+
+ if kwargs.get('delete_on_clean') is not None:
+ if isinstance(kwargs.get('delete_on_clean'), bool):
+ self.delete_on_clean = kwargs.get('delete_on_clean')
+ else:
+ self.delete_on_clean = str2bool(kwargs.get('delete_on_clean'))
else:
- self.name = name
- self.public_filepath = public_filepath
- self.private_filepath = private_filepath
+ self.delete_on_clean = None
if not self.name:
- raise Exception('The attributes name, public_filepath, and private_filepath are required')
+ raise KeypairSettingsError('Name is a required attribute')
+
+ if self.key_size < 512:
+ raise KeypairSettingsError('key_size must be >=512')
+
+
+class KeypairSettingsError(Exception):
+ """
+ Exception to be thrown when keypair settings are incorrect
+ """