Merge "Fix PEP8 errors in prox_binseach"
[yardstick.git] / yardstick / benchmark / scenarios / networking / sfc_openstack.py
1 ##############################################################################
2 # Copyright (c) 2017 Ericsson AB and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 from __future__ import print_function
10 from __future__ import absolute_import
11 import os
12 from novaclient import client as novaclient
13 from neutronclient.v2_0 import client as neutronclient
14
15
16 def get_credentials(service):  # pragma: no cover
17     """Returns a creds dictionary filled with the following keys:
18     * username
19     * password/api_key (depending on the service)
20     * tenant_name/project_id (depending on the service)
21     * auth_url
22     :param service: a string indicating the name of the service
23                     requesting the credentials.
24     """
25     creds = {}
26     # Unfortunately, each of the OpenStack client will request slightly
27     # different entries in their credentials dict.
28     if service.lower() in ("nova", "cinder"):
29         password = "api_key"
30         tenant = "project_id"
31     else:
32         password = "password"
33         tenant = "tenant_name"
34
35     # The most common way to pass these info to the script is to do it through
36     # environment variables.
37     # NOTE(ralonsoh): OS_TENANT_NAME is deprecated.
38     project_name = os.environ.get('OS_PROJECT_NAME', 'admin')
39     creds.update({
40         "username": os.environ.get('OS_USERNAME', "admin"),
41         password: os.environ.get("OS_PASSWORD", 'admin'),
42         "auth_url": os.environ.get("OS_AUTH_URL"),
43         tenant: os.environ.get("OS_TENANT_NAME", project_name),
44     })
45     cacert = os.environ.get("OS_CACERT")
46     if cacert is not None:
47         # each openstack client uses differnt kwargs for this
48         creds.update({"cacert": cacert,
49                       "ca_cert": cacert,
50                       "https_ca_cert": cacert,
51                       "https_cacert": cacert,
52                       "ca_file": cacert})
53         creds.update({"insecure": "True", "https_insecure": "True"})
54         if not os.path.isfile(cacert):
55             print(("WARNING: The 'OS_CACERT' environment variable is " +
56                    "set to %s but the file does not exist." % cacert))
57     return creds
58
59
60 def get_instances(nova_client):  # pragma: no cover
61     try:
62         instances = nova_client.servers.list(search_opts={'all_tenants': 1})
63         return instances
64     except Exception as e:  # pylint: disable=broad-except
65         print("Error [get_instances(nova_client)]:", e)
66         return None
67
68
69 def get_SFs(nova_client):  # pragma: no cover
70     try:
71         instances = get_instances(nova_client)
72         SFs = []
73         for instance in instances:
74             if "sfc_test" not in instance.name:
75                 SFs.append(instance)
76         return SFs
77     except Exception as e:  # pylint: disable=broad-except
78         print("Error [get_SFs(nova_client)]:", e)
79         return None
80
81
82 def get_external_net_id(neutron_client):  # pragma: no cover
83     for network in neutron_client.list_networks()['networks']:
84         if network['router:external']:
85             return network['id']
86     return False
87
88
89 def create_floating_ips(neutron_client):  # pragma: no cover
90     extnet_id = get_external_net_id(neutron_client)
91     ips = []
92     props = {'floating_network_id': extnet_id}
93     try:
94         while len(ips) < 2:
95             ip_json = neutron_client.create_floatingip({'floatingip': props})
96             fip_addr = ip_json['floatingip']['floating_ip_address']
97             ips.append(fip_addr)
98     except Exception as e:  # pylint: disable=broad-except
99         print("Error [create_floating_ip(neutron_client)]:", e)
100         return None
101     return ips
102
103
104 def floatIPtoSFs(SFs, floatips):  # pragma: no cover
105     try:
106         i = 0
107         for SF in SFs:
108             SF.add_floating_ip(floatips[i])
109             i = i + 1
110         return True
111     except Exception as e:  # pylint: disable=broad-except
112         print(("Error [add_floating_ip(nova_client, '%s', '%s')]:" %
113                (SF, floatips[i]), e))
114         return False
115
116
117 def get_an_IP():  # pragma: no cover
118
119     creds_nova = get_credentials("nova")
120     nova_client = novaclient.Client(version='2', **creds_nova)
121     creds_neutron = get_credentials("neutron")
122     neutron_client = neutronclient.Client(**creds_neutron)
123     SFs = get_SFs(nova_client)
124     floatips = create_floating_ips(neutron_client)
125     floatIPtoSFs(SFs, floatips)
126     return floatips