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