97fd166f863b4a60ca7d57aedd9c1c5807b8dd59
[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) 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     # Create a server instance with name vmname
99     # and check that it gets into the ACTIVE state
100     def create_server(self, vmname, image, flavor, key_name,
101                       nic, sec_group, avail_zone=None, user_data=None,
102                       config_drive=None, files=None):
103         """Create a new server."""
104         if sec_group:
105             security_groups = [sec_group['id']]
106         else:
107             security_groups = None
108
109         # Also attach the created security group for the test
110         LOG.info('Creating instance %s with AZ %s', vmname, avail_zone)
111         instance = self.novaclient.servers.create(name=vmname,
112                                                   image=image,
113                                                   flavor=flavor,
114                                                   key_name=key_name,
115                                                   nics=nic,
116                                                   availability_zone=avail_zone,
117                                                   userdata=user_data,
118                                                   config_drive=config_drive,
119                                                   files=files,
120                                                   security_groups=security_groups)
121         return instance
122
123     def poll_server(self, instance):
124         """Poll a server from its reference."""
125         return self.novaclient.servers.get(instance.id)
126
127     def get_server_list(self):
128         """Get the list of all servers."""
129         servers_list = self.novaclient.servers.list()
130         return servers_list
131
132     def delete_server(self, server):
133         """Delete a server from its object reference."""
134         self.novaclient.servers.delete(server)
135
136     def find_flavor(self, flavor_type):
137         """Find a flavor by name."""
138         try:
139             flavor = self.novaclient.flavors.find(name=flavor_type)
140             return flavor
141         except Exception:
142             return None
143
144     def create_flavor(self, name, ram, vcpus, disk, ephemeral=0):
145         """Create a flavor."""
146         return self.novaclient.flavors.create(name=name, ram=ram, vcpus=vcpus, disk=disk,
147                                               ephemeral=ephemeral)
148
149     def get_hypervisor(self, hyper_name):
150         """Get the hypervisor from its name.
151
152         Can raise novaclient.exceptions.NotFound
153         """
154         # first get the id from name
155         hyper = self.novaclient.hypervisors.search(hyper_name)[0]
156         # get full hypervisor object
157         return self.novaclient.hypervisors.get(hyper.id)