1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 # and others. All rights reserved.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
18 from neutronclient.common.utils import str2bool
19 from novaclient.exceptions import NotFound
21 from snaps import file_utils
22 from snaps.openstack.openstack_creator import OpenStackComputeObject
23 from snaps.openstack.utils import nova_utils
25 __author__ = 'spisarski'
27 logger = logging.getLogger('OpenStackKeypair')
30 class OpenStackKeypair(OpenStackComputeObject):
32 Class responsible for managing a keypair in OpenStack
35 def __init__(self, os_creds, keypair_settings):
37 Constructor - all parameters are required
38 :param os_creds: The credentials to connect with OpenStack
39 :param keypair_settings: The settings used to create a keypair
41 super(self.__class__, self).__init__(os_creds)
43 self.keypair_settings = keypair_settings
44 self.__delete_keys_on_clean = True
46 # Attributes instantiated on create()
51 Loads the existing OpenStack Keypair
52 :return: The Keypair domain object or None
54 super(self.__class__, self).initialize()
57 self.__keypair = nova_utils.get_keypair_by_name(
58 self._nova, self.keypair_settings.name)
60 except Exception as e:
61 logger.warn('Cannot load existing keypair - %s', e)
65 Responsible for creating the keypair object.
66 :return: The Keypair domain object or None
70 if not self.__keypair:
71 logger.info('Creating keypair %s...' % self.keypair_settings.name)
73 if self.keypair_settings.public_filepath and os.path.isfile(
74 self.keypair_settings.public_filepath):
75 logger.info("Uploading existing keypair")
76 self.__keypair = nova_utils.upload_keypair_file(
77 self._nova, self.keypair_settings.name,
78 self.keypair_settings.public_filepath)
80 if self.keypair_settings.delete_on_clean is not None:
81 delete_on_clean = self.keypair_settings.delete_on_clean
82 self.__delete_keys_on_clean = delete_on_clean
84 self.__delete_keys_on_clean = False
86 logger.info("Creating new keypair")
87 keys = nova_utils.create_keys(self.keypair_settings.key_size)
88 self.__keypair = nova_utils.upload_keypair(
89 self._nova, self.keypair_settings.name,
90 nova_utils.public_key_openssh(keys))
91 file_utils.save_keys_to_files(
92 keys, self.keypair_settings.public_filepath,
93 self.keypair_settings.private_filepath)
95 if self.keypair_settings.delete_on_clean is not None:
96 delete_on_clean = self.keypair_settings.delete_on_clean
97 self.__delete_keys_on_clean = delete_on_clean
99 self.__delete_keys_on_clean = True
100 elif self.__keypair and not os.path.isfile(
101 self.keypair_settings.private_filepath):
102 logger.warn("The public key already exist in OpenStack \
103 but the private key file is not found ..")
105 return self.__keypair
109 Removes and deletes the keypair.
113 nova_utils.delete_keypair(self._nova, self.__keypair)
116 self.__keypair = None
118 if self.__delete_keys_on_clean:
119 if (self.keypair_settings.public_filepath and
120 file_utils.file_exists(
121 self.keypair_settings.public_filepath)):
122 expanded_path = os.path.expanduser(
123 self.keypair_settings.public_filepath)
124 os.chmod(expanded_path, 0o755)
125 os.remove(expanded_path)
126 logger.info('Deleted public key file [%s]', expanded_path)
127 if (self.keypair_settings.private_filepath and
128 file_utils.file_exists(
129 self.keypair_settings.private_filepath)):
130 expanded_path = os.path.expanduser(
131 self.keypair_settings.private_filepath)
132 os.chmod(expanded_path, 0o755)
133 os.remove(expanded_path)
134 logger.info('Deleted private key file [%s]', expanded_path)
136 def get_keypair(self):
138 Returns the OpenStack keypair object
141 return self.__keypair
144 class KeypairSettings:
146 Class representing a keypair configuration
149 def __init__(self, **kwargs):
151 Constructor - all parameters are optional
152 :param name: The keypair name.
153 :param public_filepath: The path to/from the filesystem where the
154 public key file is or will be stored
155 :param private_filepath: The path where the generated private key file
157 :param key_size: The number of bytes for the key size when it needs to
158 be generated (Must be >=512 default 1024)
159 :param delete_on_clean: when True, the key files will be deleted when
160 OpenStackKeypair#clean() is called
164 self.name = kwargs.get('name')
165 self.public_filepath = kwargs.get('public_filepath')
166 self.private_filepath = kwargs.get('private_filepath')
167 self.key_size = int(kwargs.get('key_size', 1024))
169 if kwargs.get('delete_on_clean') is not None:
170 if isinstance(kwargs.get('delete_on_clean'), bool):
171 self.delete_on_clean = kwargs.get('delete_on_clean')
173 self.delete_on_clean = str2bool(kwargs.get('delete_on_clean'))
175 self.delete_on_clean = None
178 raise KeypairSettingsError('Name is a required attribute')
180 if self.key_size < 512:
181 raise KeypairSettingsError('key_size must be >=512')
184 class KeypairSettingsError(Exception):
186 Exception to be thrown when keypair settings are incorrect