6d90d3e9a04b890eefba3938865ae3e7effd0d79
[snaps.git] / snaps / openstack / utils / glance_utils.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 snaps import file_utils
18 from glanceclient.client import Client
19 from snaps.openstack.utils import keystone_utils
20
21 __author__ = 'spisarski'
22
23 logger = logging.getLogger('glance_utils')
24
25 """
26 Utilities for basic neutron API calls
27 """
28
29
30 def glance_client(os_creds):
31     """
32     Creates and returns a glance client object
33     :return: the glance client
34     """
35     return Client(version=os_creds.image_api_version, session=keystone_utils.keystone_session(os_creds))
36
37
38 def get_image(nova, glance, image_name):
39     """
40     Returns an OpenStack image object for a given name
41     :param nova: the Nova client
42     :param glance: the Glance client
43     :param image_name: the image name to lookup
44     :return: the image object or None
45     """
46     try:
47         image_dict = nova.images.find(name=image_name)
48         if image_dict:
49             return glance.images.get(image_dict.id)
50     except:
51         pass
52     return None
53
54
55 def create_image(glance, image_settings):
56     """
57     Creates and returns OpenStack image object with an external URL
58     :param glance: the glance client
59     :param image_settings: the image settings object
60     :return: the OpenStack image object
61     :raise Exception if using a file and it cannot be found
62     """
63     if image_settings.url:
64         return glance.images.create(name=image_settings.name, disk_format=image_settings.format,
65                                     container_format="bare", location=image_settings.url)
66     elif image_settings.image_file:
67         image_file = file_utils.get_file(image_settings.image_file)
68         return glance.images.create(name=image_settings.name, disk_format=image_settings.format,
69                                     container_format="bare", data=image_file)
70
71
72 def delete_image(glance, image):
73     """
74     Deletes an image from OpenStack
75     :param glance: the glance client
76     :param image: the image to delete
77     """
78     glance.images.delete(image)