Refactoring of KeypairSettings to extend KeypairConfig
[snaps.git] / snaps / openstack / create_keypairs.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
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:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
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.
15 import logging
16
17 import os
18 from novaclient.exceptions import NotFound
19
20 from snaps import file_utils
21 from snaps.config.keypair import KeypairConfig
22 from snaps.openstack.openstack_creator import OpenStackComputeObject
23 from snaps.openstack.utils import nova_utils
24
25 __author__ = 'spisarski'
26
27 logger = logging.getLogger('OpenStackKeypair')
28
29
30 class OpenStackKeypair(OpenStackComputeObject):
31     """
32     Class responsible for managing a keypair in OpenStack
33     """
34
35     def __init__(self, os_creds, keypair_settings):
36         """
37         Constructor - all parameters are required
38         :param os_creds: The credentials to connect with OpenStack
39         :param keypair_settings: a KeypairConfig object
40         """
41         super(self.__class__, self).__init__(os_creds)
42
43         self.keypair_settings = keypair_settings
44         self.__delete_keys_on_clean = True
45
46         # Attributes instantiated on create()
47         self.__keypair = None
48
49     def initialize(self):
50         """
51         Loads the existing OpenStack Keypair
52         :return: The Keypair domain object or None
53         """
54         super(self.__class__, self).initialize()
55
56         try:
57             self.__keypair = nova_utils.get_keypair_by_name(
58                 self._nova, self.keypair_settings.name)
59             return self.__keypair
60         except Exception as e:
61             logger.warn('Cannot load existing keypair - %s', e)
62
63     def create(self):
64         """
65         Responsible for creating the keypair object.
66         :return: The Keypair domain object or None
67         """
68         self.initialize()
69
70         if not self.__keypair:
71             logger.info('Creating keypair %s...' % self.keypair_settings.name)
72
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)
79
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
83                 else:
84                     self.__delete_keys_on_clean = False
85             else:
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)
94
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
98                 else:
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 ..")
104
105         return self.__keypair
106
107     def clean(self):
108         """
109         Removes and deletes the keypair.
110         """
111         if self.__keypair:
112             try:
113                 nova_utils.delete_keypair(self._nova, self.__keypair)
114             except NotFound:
115                 pass
116             self.__keypair = None
117
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)
135
136     def get_keypair(self):
137         """
138         Returns the OpenStack keypair object
139         :return:
140         """
141         return self.__keypair
142
143
144 class KeypairSettings(KeypairConfig):
145     """
146     Class representing a keypair configuration
147     """
148
149     def __init__(self, **kwargs):
150         from warnings import warn
151         warn('Use snaps.config.keypair.KeypairConfig instead',
152              DeprecationWarning)
153         super(self.__class__, self).__init__(**kwargs)