Created new class NeutronException.
[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 from snaps.openstack.utils import nova_utils
20
21 __author__ = 'spisarski'
22
23 logger = logging.getLogger('OpenStackKeypair')
24
25
26 class OpenStackKeypair:
27     """
28     Class responsible for creating a keypair in OpenStack
29     """
30
31     def __init__(self, os_creds, keypair_settings):
32         """
33         Constructor - all parameters are required
34         :param os_creds: The credentials to connect with OpenStack
35         :param keypair_settings: The settings used to create a keypair
36         """
37         self.__nova = None
38         self.__os_creds = os_creds
39         self.keypair_settings = keypair_settings
40         self.__nova = nova_utils.nova_client(os_creds)
41         self.__delete_keys_on_clean = True
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
50                         or not
51         """
52         self.__nova = nova_utils.nova_client(self.__os_creds)
53
54         logger.info('Creating keypair %s...' % self.keypair_settings.name)
55
56         self.__keypair = nova_utils.get_keypair_by_name(
57             self.__nova, self.keypair_settings.name)
58
59         if not self.__keypair and not cleanup:
60             if self.keypair_settings.public_filepath and os.path.isfile(
61                     self.keypair_settings.public_filepath):
62                 logger.info("Uploading existing keypair")
63                 self.__keypair = nova_utils.upload_keypair_file(
64                     self.__nova, self.keypair_settings.name,
65                     self.keypair_settings.public_filepath)
66                 self.__delete_keys_on_clean = False
67             else:
68                 logger.info("Creating new keypair")
69                 # TODO - Make this value configurable
70                 keys = nova_utils.create_keys(1024)
71                 self.__keypair = nova_utils.upload_keypair(
72                     self.__nova, self.keypair_settings.name,
73                     nova_utils.public_key_openssh(keys))
74                 nova_utils.save_keys_to_files(
75                     keys, self.keypair_settings.public_filepath,
76                     self.keypair_settings.private_filepath)
77                 self.__delete_keys_on_clean = True
78         elif self.__keypair and not os.path.isfile(
79                 self.keypair_settings.private_filepath):
80             logger.warn("The public key already exist in OpenStack \
81                         but the private key file is not found ..")
82
83         return self.__keypair
84
85     def clean(self):
86         """
87         Removes and deletes the keypair.
88         """
89         if self.__keypair:
90             try:
91                 nova_utils.delete_keypair(self.__nova, self.__keypair)
92             except NotFound:
93                 pass
94             self.__keypair = None
95
96         if self.__delete_keys_on_clean:
97             if self.keypair_settings.public_filepath:
98                 os.chmod(self.keypair_settings.public_filepath, 0o777)
99                 os.remove(self.keypair_settings.public_filepath)
100             if self.keypair_settings.private_filepath:
101                 os.chmod(self.keypair_settings.private_filepath, 0o777)
102                 os.remove(self.keypair_settings.private_filepath)
103
104     def get_keypair(self):
105         """
106         Returns the OpenStack keypair object
107         :return:
108         """
109         return self.__keypair
110
111
112 class KeypairSettings:
113     """
114     Class representing a keypair configuration
115     """
116
117     def __init__(self, **kwargs):
118         """
119         Constructor - all parameters are optional
120         :param name: The keypair name.
121         :param public_filepath: The path to/from the filesystem where the
122                                 public key file is or will be stored
123         :param private_filepath: The path where the generated private key file
124                                  will be stored
125         :return:
126         """
127
128         self.name = kwargs.get('name')
129         self.public_filepath = kwargs.get('public_filepath')
130         self.private_filepath = kwargs.get('private_filepath')
131
132         if not self.name:
133             raise Exception('Name is a required attribute')