NFVBENCH-153 Add support for python3
[nfvbench.git] / nfvbench / compute.py
1 # Copyright 2016 Cisco Systems, Inc.  All rights reserved.
2 #
3 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
4 #    not use this file except in compliance with the License. You may obtain
5 #    a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #    Unless required by applicable law or agreed to in writing, software
10 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 #    License for the specific language governing permissions and limitations
13 #    under the License.
14 """Module to interface with nova and glance."""
15
16 import time
17 import traceback
18
19 from glanceclient import exc as glance_exception
20 try:
21     from glanceclient.openstack.common.apiclient.exceptions import NotFound as GlanceImageNotFound
22 except ImportError:
23     from glanceclient.v1.apiclient.exceptions import NotFound as GlanceImageNotFound
24 import keystoneauth1
25 import novaclient
26
27 from .log import LOG
28
29
30 class Compute(object):
31     """Class to interface with nova and glance."""
32
33     def __init__(self, nova_client, glance_client, config):
34         """Create a new compute instance to interact with nova and glance."""
35         self.novaclient = nova_client
36         self.glance_client = glance_client
37         self.config = config
38
39     def find_image(self, image_name):
40         """Find an image by name."""
41         try:
42             return next(self.glance_client.images.list(filters={'name': image_name}), None)
43         except (novaclient.exceptions.NotFound, keystoneauth1.exceptions.http.NotFound,
44                 GlanceImageNotFound):
45             pass
46         return None
47
48     def upload_image_via_url(self, final_image_name, image_file, retry_count=60):
49         """Directly upload image to Nova via URL if image is not present."""
50         retry = 0
51         try:
52             # check image is file/url based.
53             with open(image_file, 'rb') as f_image:
54                 img = self.glance_client.images.create(name=str(final_image_name),
55                                                        disk_format="qcow2",
56                                                        container_format="bare",
57                                                        visibility="public")
58                 self.glance_client.images.upload(img.id, image_data=f_image)
59             # Check for the image in glance
60             while img.status in ['queued', 'saving'] and retry < retry_count:
61                 img = self.glance_client.images.get(img.id)
62                 retry += 1
63                 LOG.debug("Image not yet active, retrying %s of %s...", retry, retry_count)
64                 time.sleep(self.config.generic_poll_sec)
65             if img.status != 'active':
66                 LOG.error("Image uploaded but too long to get to active state")
67                 raise Exception("Image update active state timeout")
68         except glance_exception.HTTPForbidden:
69             LOG.error("Cannot upload image without admin access. Please make "
70                       "sure the image is uploaded and is either public or owned by you.")
71             return False
72         except IOError:
73             # catch the exception for file based errors.
74             LOG.error("Failed while uploading the image. Please make sure the "
75                       "image at the specified location %s is correct.", image_file)
76             return False
77         except keystoneauth1.exceptions.http.NotFound as exc:
78             LOG.error("Authentication error while uploading the image: %s", str(exc))
79             return False
80         except Exception:
81             LOG.error(traceback.format_exc())
82             LOG.error("Failed to upload image %s.", image_file)
83             return False
84         return True
85
86     def delete_image(self, img_name):
87         """Delete an image by name."""
88         try:
89             LOG.log("Deleting image %s...", img_name)
90             img = self.find_image(image_name=img_name)
91             self.glance_client.images.delete(img.id)
92         except Exception:
93             LOG.error("Failed to delete the image %s.", img_name)
94             return False
95
96         return True
97
98     def image_multiqueue_enabled(self, img):
99         """Check if multiqueue property is enabled on given image."""
100         try:
101             return img['hw_vif_multiqueue_enabled'] == 'true'
102         except KeyError:
103             return False
104
105     def image_set_multiqueue(self, img, enabled):
106         """Set multiqueue property as enabled or disabled on given image."""
107         cur_mqe = self.image_multiqueue_enabled(img)
108         LOG.info('Image %s hw_vif_multiqueue_enabled property is "%s"',
109                  img.name, str(cur_mqe).lower())
110         if cur_mqe != enabled:
111             mqe = str(enabled).lower()
112             self.glance_client.images.update(img.id, hw_vif_multiqueue_enabled=mqe)
113             img['hw_vif_multiqueue_enabled'] = mqe
114             LOG.info('Image %s hw_vif_multiqueue_enabled property changed to "%s"', img.name, mqe)
115
116     # Create a server instance with name vmname
117     # and check that it gets into the ACTIVE state
118     def create_server(self, vmname, image, flavor, key_name,
119                       nic, sec_group, avail_zone=None, user_data=None,
120                       config_drive=None, files=None):
121         """Create a new server."""
122         if sec_group:
123             security_groups = [sec_group['id']]
124         else:
125             security_groups = None
126
127         # Also attach the created security group for the test
128         LOG.info('Creating instance %s with AZ: "%s"', vmname, avail_zone)
129         instance = self.novaclient.servers.create(name=vmname,
130                                                   image=image,
131                                                   flavor=flavor,
132                                                   key_name=key_name,
133                                                   nics=nic,
134                                                   availability_zone=avail_zone,
135                                                   userdata=user_data,
136                                                   config_drive=config_drive,
137                                                   files=files,
138                                                   security_groups=security_groups)
139         return instance
140
141     def poll_server(self, instance):
142         """Poll a server from its reference."""
143         return self.novaclient.servers.get(instance.id)
144
145     def get_server_list(self):
146         """Get the list of all servers."""
147         servers_list = self.novaclient.servers.list()
148         return servers_list
149
150     def delete_server(self, server):
151         """Delete a server from its object reference."""
152         self.novaclient.servers.delete(server)
153
154     def find_flavor(self, flavor_type):
155         """Find a flavor by name."""
156         try:
157             flavor = self.novaclient.flavors.find(name=flavor_type)
158             return flavor
159         except Exception:
160             return None
161
162     def create_flavor(self, name, ram, vcpus, disk, ephemeral=0):
163         """Create a flavor."""
164         return self.novaclient.flavors.create(name=name, ram=ram, vcpus=vcpus, disk=disk,
165                                               ephemeral=ephemeral)
166
167     def get_hypervisor(self, hyper_name):
168         """Get the hypervisor from its name.
169
170         Can raise novaclient.exceptions.NotFound
171         """
172         # first get the id from name
173         hyper = self.novaclient.hypervisors.search(hyper_name)[0]
174         # get full hypervisor object
175         return self.novaclient.hypervisors.get(hyper.id)