Merge "DRAFT: remove apexlake"
[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     creds.update({
38         "username": os.environ.get('OS_USERNAME', "admin"),
39         password: os.environ.get("OS_PASSWORD", 'admin'),
40         "auth_url": os.environ.get("OS_AUTH_URL"),
41         tenant: os.environ.get("OS_TENANT_NAME", "admin"),
42     })
43     cacert = os.environ.get("OS_CACERT")
44     if cacert is not None:
45         # each openstack client uses differnt kwargs for this
46         creds.update({"cacert": cacert,
47                       "ca_cert": cacert,
48                       "https_ca_cert": cacert,
49                       "https_cacert": cacert,
50                       "ca_file": cacert})
51         creds.update({"insecure": "True", "https_insecure": "True"})
52         if not os.path.isfile(cacert):
53             print(("WARNING: The 'OS_CACERT' environment variable is " +
54                    "set to %s but the file does not exist." % cacert))
55     return creds
56
57
58 def get_instances(nova_client):  # pragma: no cover
59     try:
60         instances = nova_client.servers.list(search_opts={'all_tenants': 1})
61         return instances
62     except Exception as e:
63         print("Error [get_instances(nova_client)]:", e)
64         return None
65
66
67 def get_SFs(nova_client):  # pragma: no cover
68     try:
69         instances = get_instances(nova_client)
70         SFs = []
71         for instance in instances:
72             if "sfc_test" not in instance.name:
73                 SFs.append(instance)
74         return SFs
75     except Exception as e:
76         print("Error [get_SFs(nova_client)]:", e)
77         return None
78
79
80 def get_external_net_id(neutron_client):  # pragma: no cover
81     for network in neutron_client.list_networks()['networks']:
82         if network['router:external']:
83             return network['id']
84     return False
85
86
87 def create_floating_ips(neutron_client):  # pragma: no cover
88     extnet_id = get_external_net_id(neutron_client)
89     ips = []
90     props = {'floating_network_id': extnet_id}
91     try:
92         while len(ips) < 2:
93             ip_json = neutron_client.create_floatingip({'floatingip': props})
94             fip_addr = ip_json['floatingip']['floating_ip_address']
95             ips.append(fip_addr)
96     except Exception as e:
97         print("Error [create_floating_ip(neutron_client)]:", e)
98         return None
99     return ips
100
101
102 def floatIPtoSFs(SFs, floatips):  # pragma: no cover
103     try:
104         i = 0
105         for SF in SFs:
106             SF.add_floating_ip(floatips[i])
107             i = i + 1
108         return True
109     except Exception as e:
110         print(("Error [add_floating_ip(nova_client, '%s', '%s')]:" %
111                (SF, floatips[i]), e))
112         return False
113
114
115 def get_an_IP():  # pragma: no cover
116
117     creds_nova = get_credentials("nova")
118     nova_client = novaclient.Client(version='2', **creds_nova)
119     creds_neutron = get_credentials("neutron")
120     neutron_client = neutronclient.Client(**creds_neutron)
121     SFs = get_SFs(nova_client)
122     floatips = create_floating_ips(neutron_client)
123     floatIPtoSFs(SFs, floatips)
124     return floatips
125
126
127 if __name__ == '__main__':  # pragma: no cover
128     get_an_IP()