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