42264b0d067e30045998d963d5037251edd28780
[snaps.git] / snaps / openstack / create_flavor.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
17 from novaclient.exceptions import NotFound
18
19 from snaps.openstack.utils import nova_utils
20
21 __author__ = 'spisarski'
22
23 logger = logging.getLogger('create_image')
24
25 MEM_PAGE_SIZE_ANY = {'hw:mem_page_size': 'any'}
26 MEM_PAGE_SIZE_LARGE = {'hw:mem_page_size': 'large'}
27
28
29 class OpenStackFlavor:
30     """
31     Class responsible for creating a user in OpenStack
32     """
33
34     def __init__(self, os_creds, flavor_settings):
35         """
36         Constructor
37         :param os_creds: The OpenStack connection credentials
38         :param flavor_settings: The flavor settings
39         :return:
40         """
41         self.__os_creds = os_creds
42         self.flavor_settings = flavor_settings
43         self.__flavor = None
44         self.__nova = None
45
46     def create(self, cleanup=False):
47         """
48         Creates the image in OpenStack if it does not already exist
49         :param cleanup: Denotes whether or not this is being called for cleanup
50                         or not
51         :return: The OpenStack flavor object
52         """
53         self.__nova = nova_utils.nova_client(self.__os_creds)
54         self.__flavor = nova_utils.get_flavor_by_name(
55             self.__nova, self.flavor_settings.name)
56         if self.__flavor:
57             logger.info(
58                 'Found flavor with name - ' + self.flavor_settings.name)
59         elif not cleanup:
60             self.__flavor = nova_utils.create_flavor(
61                 self.__nova, self.flavor_settings)
62             if self.flavor_settings.metadata:
63                 nova_utils.set_flavor_keys(self.__nova, self.__flavor,
64                                            self.flavor_settings.metadata)
65         else:
66             logger.info('Did not create flavor due to cleanup mode')
67
68         return self.__flavor
69
70     def clean(self):
71         """
72         Cleanse environment of all artifacts
73         :return: void
74         """
75         if self.__flavor:
76             try:
77                 nova_utils.delete_flavor(self.__nova, self.__flavor)
78             except NotFound:
79                 pass
80
81             self.__flavor = None
82
83     def get_flavor(self):
84         """
85         Returns the OpenStack flavor object
86         :return:
87         """
88         return self.__flavor
89
90
91 class FlavorSettings:
92     """
93     Configuration settings for OpenStack flavor creation
94     """
95
96     def __init__(self, **kwargs):
97         """
98         Constructor
99         :param config: dict() object containing the configuration settings
100                        using the attribute names below as each member's the
101                        key and overrides any of the other parameters.
102         :param name: the flavor's name (required)
103         :param flavor_id: the string ID (default 'auto')
104         :param ram: the required RAM in MB (required)
105         :param disk: the size of the root disk in GB (required)
106         :param vcpus: the number of virtual CPUs (required)
107         :param ephemeral: the size of the ephemeral disk in GB (default 0)
108         :param swap: the size of the dedicated swap disk in GB (default 0)
109         :param rxtx_factor: the receive/transmit factor to be set on ports if
110                             backend supports QoS extension (default 1.0)
111         :param is_public: denotes whether or not the flavor is public
112                           (default True)
113         :param metadata: freeform dict() for special metadata
114         """
115         self.name = kwargs.get('name')
116
117         if kwargs.get('flavor_id'):
118             self.flavor_id = kwargs['flavor_id']
119         else:
120             self.flavor_id = 'auto'
121
122         self.ram = kwargs.get('ram')
123         self.disk = kwargs.get('disk')
124         self.vcpus = kwargs.get('vcpus')
125
126         if kwargs.get('ephemeral'):
127             self.ephemeral = kwargs['ephemeral']
128         else:
129             self.ephemeral = 0
130
131         if kwargs.get('swap'):
132             self.swap = kwargs['swap']
133         else:
134             self.swap = 0
135
136         if kwargs.get('rxtx_factor'):
137             self.rxtx_factor = kwargs['rxtx_factor']
138         else:
139             self.rxtx_factor = 1.0
140
141         if kwargs.get('is_public') is not None:
142             self.is_public = kwargs['is_public']
143         else:
144             self.is_public = True
145
146         if kwargs.get('metadata'):
147             self.metadata = kwargs['metadata']
148         else:
149             self.metadata = None
150
151         if not self.name or not self.ram or not self.disk or not self.vcpus:
152             raise Exception(
153                 'The attributes name, ram, disk, and vcpus are required for'
154                 'FlavorSettings')
155
156         if not isinstance(self.ram, int):
157             raise Exception('The ram attribute must be a integer')
158
159         if not isinstance(self.disk, int):
160             raise Exception('The ram attribute must be a integer')
161
162         if not isinstance(self.vcpus, int):
163             raise Exception('The vcpus attribute must be a integer')
164
165         if self.ephemeral and not isinstance(self.ephemeral, int):
166             raise Exception('The ephemeral attribute must be an integer')
167
168         if self.swap and not isinstance(self.swap, int):
169             raise Exception('The swap attribute must be an integer')
170
171         if self.rxtx_factor and not isinstance(self.rxtx_factor, (int, float)):
172             raise Exception(
173                 'The is_public attribute must be an integer or float')
174
175         if self.is_public and not isinstance(self.is_public, bool):
176             raise Exception('The is_public attribute must be a boolean')