summaryrefslogtreecommitdiffstats
path: root/nfvbench/compute.py
blob: d5a811953ea44a637b81924e95db83de51c0c577 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# Copyright 2016 Cisco Systems, Inc.  All rights reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
"""Module to interface with nova and glance."""

import time
import traceback

from glanceclient import exc as glance_exception
try:
    from glanceclient.openstack.common.apiclient.exceptions import NotFound as GlanceImageNotFound
except ImportError:
    from glanceclient.v1.apiclient.exceptions import NotFound as GlanceImageNotFound
import keystoneauth1
import novaclient

from log import LOG


class Compute(object):
    """Class to interface with nova and glance."""

    def __init__(self, nova_client, glance_client, config):
        """Create a new compute instance to interact with nova and glance."""
        self.novaclient = nova_client
        self.glance_client = glance_client
        self.config = config

    def find_image(self, image_name):
        """Find an image by name."""
        try:
            return next(self.glance_client.images.list(filters={'name': image_name}), None)
        except (novaclient.exceptions.NotFound, keystoneauth1.exceptions.http.NotFound,
                GlanceImageNotFound):
            pass
        return None

    def upload_image_via_url(self, final_image_name, image_file, retry_count=60):
        """Directly upload image to Nova via URL if image is not present."""
        retry = 0
        try:
            # check image is file/url based.
            with open(image_file) as f_image:
                img = self.glance_client.images.create(name=str(final_image_name),
                                                       disk_format="qcow2",
                                                       container_format="bare",
                                                       visibility="public")
                self.glance_client.images.upload(img.id, image_data=f_image)
            # Check for the image in glance
            while img.status in ['queued', 'saving'] and retry < retry_count:
                img = self.glance_client.images.get(img.id)
                retry += 1
                LOG.debug("Image not yet active, retrying %s of %s...", retry, retry_count)
                time.sleep(self.config.generic_poll_sec)
            if img.status != 'active':
                LOG.error("Image uploaded but too long to get to active state")
                raise Exception("Image update active state timeout")
        except glance_exception.HTTPForbidden:
            LOG.error("Cannot upload image without admin access. Please make "
                      "sure the image is uploaded and is either public or owned by you.")
            return False
        except IOError:
            # catch the exception for file based errors.
            LOG.error("Failed while uploading the image. Please make sure the "
                      "image at the specified location %s is correct.", image_file)
            return False
        except keystoneauth1.exceptions.http.NotFound as exc:
            LOG.error("Authentication error while uploading the image: %s", str(exc))
            return False
        except Exception:
            LOG.error(traceback.format_exc())
            LOG.error("Failed to upload image %s.", image_file)
            return False
        return True

    def delete_image(self, img_name):
        """Delete an image by name."""
        try:
            LOG.log("Deleting image %s...", img_name)
            img = self.find_image(image_name=img_name)
            self.glance_client.images.delete(img.id)
        except Exception:
            LOG.error("Failed to delete the image %s.", img_name)
            return False

        return True

    # Create a server instance with name vmname
    # and check that it gets into the ACTIVE state
    def create_server(self, vmname, image, flavor, key_name,
                      nic, sec_group, avail_zone=None, user_data=None,
                      config_drive=None, files=None):
        """Create a new server."""
        if sec_group:
            security_groups = [sec_group['id']]
        else:
            security_groups = None

        # Also attach the created security group for the test
        instance = self.novaclient.servers.create(name=vmname,
                                                  image=image,
                                                  flavor=flavor,
                                                  key_name=key_name,
                                                  nics=nic,
                                                  availability_zone=avail_zone,
                                                  userdata=user_data,
                                                  config_drive=config_drive,
                                                  files=files,
                                                  security_groups=security_groups)
        return instance

    def poll_server(self, instance):
        """Poll a server from its reference."""
        return self.novaclient.servers.get(instance.id)

    def get_server_list(self):
        """Get the list of all servers."""
        servers_list = self.novaclient.servers.list()
        return servers_list

    def delete_server(self, server):
        """Delete a server from its object reference."""
        self.novaclient.servers.delete(server)

    def find_flavor(self, flavor_type):
        """Find a flavor by name."""
        try:
            flavor = self.novaclient.flavors.find(name=flavor_type)
            return flavor
        except Exception:
            return None

    def create_flavor(self, name, ram, vcpus, disk, ephemeral=0):
        """Create a flavor."""
        return self.novaclient.flavors.create(name=name, ram=ram, vcpus=vcpus, disk=disk,
                                              ephemeral=ephemeral)

    def get_hypervisor(self, hyper_name):
        """Get the hypervisor from its name.

        Can raise novaclient.exceptions.NotFound
        """
        # first get the id from name
        hyper = self.novaclient.hypervisors.search(hyper_name)[0]
        # get full hypervisor object
        return self.novaclient.hypervisors.get(hyper.id)