Merge "Restricted dependency of the novaclient."
[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 import os
17
18 from novaclient.exceptions import NotFound
19
20 from snaps.openstack.utils import nova_utils
21
22 __author__ = 'spisarski'
23
24 logger = logging.getLogger('OpenStackKeypair')
25
26
27 class OpenStackKeypair:
28     """
29     Class responsible for creating a keypair in OpenStack
30     """
31
32     def __init__(self, os_creds, keypair_settings):
33         """
34         Constructor - all parameters are required
35         :param os_creds: The credentials to connect with OpenStack
36         :param keypair_settings: The settings used to create a keypair
37         """
38         self.__os_creds = os_creds
39         self.keypair_settings = keypair_settings
40         self.__nova = nova_utils.nova_client(os_creds)
41
42         # Attributes instantiated on create()
43         self.__keypair = None
44
45     def create(self, cleanup=False):
46         """
47         Responsible for creating the keypair object.
48         :param cleanup: Denotes whether or not this is being called for cleanup or not
49         """
50         logger.info('Creating keypair %s...' % self.keypair_settings.name)
51
52         self.__keypair = nova_utils.get_keypair_by_name(self.__nova, self.keypair_settings.name)
53
54         if not self.__keypair and not cleanup:
55             if self.keypair_settings.public_filepath and os.path.isfile(self.keypair_settings.public_filepath):
56                 logger.info("Uploading existing keypair")
57                 self.__keypair = nova_utils.upload_keypair_file(self.__nova, self.keypair_settings.name,
58                                                                 self.keypair_settings.public_filepath)
59             else:
60                 logger.info("Creating new keypair")
61                 # TODO - Make this value configurable
62                 keys = nova_utils.create_keys(1024)
63                 self.__keypair = nova_utils.upload_keypair(self.__nova, self.keypair_settings.name,
64                                                            nova_utils.public_key_openssh(keys))
65                 nova_utils.save_keys_to_files(keys, self.keypair_settings.public_filepath,
66                                               self.keypair_settings.private_filepath)
67
68         return self.__keypair
69
70     def clean(self):
71         """
72         Removes and deletes the keypair.
73         """
74         if self.__keypair:
75             try:
76                 nova_utils.delete_keypair(self.__nova, self.__keypair)
77             except NotFound:
78                 pass
79             self.__keypair = None
80
81     def get_keypair(self):
82         """
83         Returns the OpenStack keypair object
84         :return:
85         """
86         return self.__keypair
87
88
89 class KeypairSettings:
90     """
91     Class representing a keypair configuration
92     """
93
94     def __init__(self, config=None, name=None, public_filepath=None, private_filepath=None):
95         """
96         Constructor - all parameters are optional
97         :param config: Should be a dict object containing the configuration settings using the attribute names below
98                        as each member's the key and overrides any of the other parameters.
99         :param name: The keypair name.
100         :param public_filepath: The path to/from the filesystem where the public key file is or will be stored
101         :param private_filepath: The path where the generated private key file will be stored
102         :return:
103         """
104
105         if config:
106             self.name = config.get('name')
107             self.public_filepath = config.get('public_filepath')
108             self.private_filepath = config.get('private_filepath')
109         else:
110             self.name = name
111             self.public_filepath = public_filepath
112             self.private_filepath = private_filepath
113
114         if not self.name:
115             raise Exception('The attributes name, public_filepath, and private_filepath are required')