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