6ced052f950ceb60d8b1a7bc66e72559f02af5e1
[snaps.git] / snaps / openstack / create_image.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 time
17
18 from glanceclient.exc import HTTPNotFound
19
20 from snaps.openstack.utils import glance_utils
21
22 __author__ = 'spisarski'
23
24 logger = logging.getLogger('create_image')
25
26 IMAGE_ACTIVE_TIMEOUT = 600
27 POLL_INTERVAL = 3
28 STATUS_ACTIVE = 'active'
29
30
31 class OpenStackImage:
32     """
33     Class responsible for creating an image in OpenStack
34     """
35
36     def __init__(self, os_creds, image_settings):
37         """
38         Constructor
39         :param os_creds: The OpenStack connection credentials
40         :param image_settings: The image settings
41         :return:
42         """
43         self.__os_creds = os_creds
44         self.image_settings = image_settings
45         self.__image = None
46         self.__glance = glance_utils.glance_client(os_creds)
47
48     def create(self, cleanup=False):
49         """
50         Creates the image in OpenStack if it does not already exist and returns the domain Image object
51         :param cleanup: Denotes whether or not this is being called for cleanup or not
52         :return: The OpenStack Image object
53         """
54         self.__image = glance_utils.get_image(self.__glance, self.image_settings.name)
55         if self.__image:
56             logger.info('Found image with name - ' + self.image_settings.name)
57             return self.__image
58         elif not cleanup:
59             self.__image = glance_utils.create_image(self.__glance, self.image_settings)
60             logger.info('Creating image')
61             if self.__image and self.image_active(block=True):
62                 logger.info('Image is now active with name - ' + self.image_settings.name)
63                 return self.__image
64             else:
65                 raise Exception('Image was not created or activated in the alloted amount of time')
66         else:
67             logger.info('Did not create image due to cleanup mode')
68
69         return self.__image
70
71     def clean(self):
72         """
73         Cleanse environment of all artifacts
74         :return: void
75         """
76         if self.__image:
77             try:
78                 glance_utils.delete_image(self.__glance, self.__image)
79             except HTTPNotFound:
80                 pass
81             self.__image = None
82
83     def get_image(self):
84         """
85         Returns the domain Image object as it was populated when create() was called
86         :return: the object
87         """
88         return self.__image
89
90     def image_active(self, block=False, timeout=IMAGE_ACTIVE_TIMEOUT, poll_interval=POLL_INTERVAL):
91         """
92         Returns true when the image status returns the value of expected_status_code
93         :param block: When true, thread will block until active or timeout value in seconds has been exceeded (False)
94         :param timeout: The timeout value
95         :param poll_interval: The polling interval in seconds
96         :return: T/F
97         """
98         return self._image_status_check(STATUS_ACTIVE, block, timeout, poll_interval)
99
100     def _image_status_check(self, expected_status_code, block, timeout, poll_interval):
101         """
102         Returns true when the image status returns the value of expected_status_code
103         :param expected_status_code: instance status evaluated with this string value
104         :param block: When true, thread will block until active or timeout value in seconds has been exceeded (False)
105         :param timeout: The timeout value
106         :param poll_interval: The polling interval in seconds
107         :return: T/F
108         """
109         # sleep and wait for image status change
110         if block:
111             start = time.time()
112         else:
113             start = time.time() - timeout
114
115         while timeout > time.time() - start:
116             status = self._status(expected_status_code)
117             if status:
118                 logger.info('Image is active with name - ' + self.image_settings.name)
119                 return True
120
121             logger.debug('Retry querying image status in ' + str(poll_interval) + ' seconds')
122             time.sleep(poll_interval)
123             logger.debug('Image status query timeout in ' + str(timeout - (time.time() - start)))
124
125         logger.error('Timeout checking for image status for ' + expected_status_code)
126         return False
127
128     def _status(self, expected_status_code):
129         """
130         Returns True when active else False
131         :param expected_status_code: instance status evaluated with this string value
132         :return: T/F
133         """
134         # TODO - Place this API call into glance_utils.
135         status = glance_utils.get_image_status(self.__glance, self.__image)
136         if not status:
137             logger.warn('Cannot image status for image with ID - ' + self.__image.id)
138             return False
139
140         if status == 'ERROR':
141             raise Exception('Instance had an error during deployment')
142         logger.debug('Instance status is - ' + status)
143         return status == expected_status_code
144
145
146 class ImageSettings:
147     def __init__(self, config=None, name=None, image_user=None, img_format=None, url=None, image_file=None,
148                  extra_properties=None, nic_config_pb_loc=None):
149         """
150
151         :param config: dict() object containing the configuration settings using the attribute names below as each
152                        member's the key and overrides any of the other parameters.
153         :param name: the image's name (required)
154         :param image_user: the image's default sudo user (required)
155         :param img_format: the image type (required)
156         :param url: the image download location (requires url or img_file)
157         :param image_file: the image file location (requires url or img_file)
158         :param extra_properties: dict() object containing extra parameters to pass when loading the image;
159                                  can be ids of kernel and initramfs images for a 3-part image
160         :param nic_config_pb_loc: the file location to the Ansible Playbook that can configure multiple NICs
161         """
162
163         if config:
164             self.name = config.get('name')
165             self.image_user = config.get('image_user')
166             self.format = config.get('format')
167             self.url = config.get('download_url')
168             self.image_file = config.get('image_file')
169             self.extra_properties = config.get('extra_properties')
170             self.nic_config_pb_loc = config.get('nic_config_pb_loc')
171         else:
172             self.name = name
173             self.image_user = image_user
174             self.format = img_format
175             self.url = url
176             self.image_file = image_file
177             self.extra_properties = extra_properties
178             self.nic_config_pb_loc = nic_config_pb_loc
179
180         if not self.name or not self.image_user or not self.format:
181             raise Exception("The attributes name, image_user, format, and url are required for ImageSettings")
182
183         if not self.url and not self.image_file:
184             raise Exception('URL or image file must be set')
185
186         if self.url and self.image_file:
187             raise Exception('Please set either URL or image file, not both')