dedf6e4480817ec061333676930dd386d61e10d7
[functest.git] / testcases / features / sfc / sfc.py
1 import argparse
2 import os
3 import subprocess
4 import sys
5 import time
6 import functest.utils.functest_logger as ft_logger
7 import functest.utils.functest_utils as ft_utils
8 import functest.utils.openstack_utils as os_utils
9 import paramiko
10
11
12 parser = argparse.ArgumentParser()
13
14 parser.add_argument("-r", "--report",
15                     help="Create json result file",
16                     action="store_true")
17
18 args = parser.parse_args()
19
20 """ logging configuration """
21 logger = ft_logger.Logger("create_instance_and_ip").getLogger()
22
23 REPO_PATH = os.environ['repos_dir'] + '/functest/'
24 HOME = os.environ['HOME'] + "/"
25
26 VM_BOOT_TIMEOUT = 180
27 INSTANCE_NAME = "client"
28 FLAVOR = "m1.small"
29 IMAGE_NAME = "sf_summit2016"
30 IMAGE_FILENAME = "sf_summit2016.qcow2"
31 IMAGE_FORMAT = "qcow2"
32 IMAGE_PATH = "/home/opnfv/functest/data" + "/" + IMAGE_FILENAME
33
34 # NEUTRON Private Network parameters
35
36 NET_NAME = "example-net"
37 SUBNET_NAME = "example-subnet"
38 SUBNET_CIDR = "11.0.0.0/24"
39 ROUTER_NAME = "example-router"
40
41 SECGROUP_NAME = "example-sg"
42 SECGROUP_DESCR = "Example Security group"
43
44 INSTANCE_NAME_2 = "server"
45
46 # TEST_DB = ft_utils.get_parameter_from_yaml("results.test_db_url")
47
48 PRE_SETUP_SCRIPT = 'sfc_pre_setup.bash'
49 TACKER_SCRIPT = 'sfc_tacker.bash'
50 TEARDOWN_SCRIPT = "sfc_teardown.bash"
51 TACKER_CHANGECLASSI = "sfc_change_classi.bash"
52
53
54 def main():
55
56     nova_client = os_utils.get_nova_client()
57     neutron_client = os_utils.get_neutron_client()
58     glance_client = os_utils.get_glance_client()
59
60 # Download the image
61
62     if not os.path.isfile(IMAGE_PATH):
63         logger.info("Downloading image")
64         ft_utils.download_url(
65             "http://artifacts.opnfv.org/sfc/demo/sf_summit2016.qcow2",
66             "/home/opnfv/functest/data/")
67     else:
68         logger.info("Using old image")
69
70 # Allow any port so that tacker commands reaches the server.
71 # CHECK IF THIS STILL MAKES SENSE WHEN TACKER IS INCLUDED IN OPNFV INSTALATION
72
73     controller_command = ("sshpass -p r00tme ssh root@10.20.0.2"
74                           " 'fuel node'|grep controller|awk '{print $10}'")
75     logger.info("Executing tacker script: '%s'" % controller_command)
76     process = subprocess.Popen(controller_command,
77                                shell=True,
78                                stdout=subprocess.PIPE)
79     ip = process.stdout.readline()
80
81     iptable_command1 = ("sshpass -p r00tme ssh root@10.20.0.2 ssh"
82                         " " + ip + " iptables -P INPUT ACCEPT ")
83     iptable_command2 = ("sshpass -p r00tme ssh root@10.20.0.2 ssh"
84                         " " + ip + "iptables -t nat -P INPUT ACCEPT ")
85
86     subprocess.call(iptable_command1, shell=True)
87     subprocess.call(iptable_command2, shell=True)
88
89 # Create glance image and the neutron network
90
91     image_id = os_utils.create_glance_image(glance_client,
92                                             IMAGE_NAME,
93                                             IMAGE_PATH,
94                                             disk=IMAGE_FORMAT,
95                                             container="bare",
96                                             public=True,
97                                             logger=logger)
98
99     network_dic = os_utils.create_network_full(logger,
100                                                neutron_client,
101                                                NET_NAME,
102                                                SUBNET_NAME,
103                                                ROUTER_NAME,
104                                                SUBNET_CIDR)
105     if not network_dic:
106         logger.error(
107             "There has been a problem when creating the neutron network")
108         sys.exit(-1)
109
110     network_id = network_dic["net_id"]
111
112     sg_id = os_utils.create_security_group_full(logger, neutron_client,
113                                                 SECGROUP_NAME, SECGROUP_DESCR)
114
115     # boot INTANCE
116     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
117     logger.debug(
118         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
119         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
120     instance = os_utils.create_instance_and_wait_for_active(FLAVOR,
121                                                             image_id,
122                                                             network_id,
123                                                             INSTANCE_NAME)
124
125     if instance is None:
126         logger.error("Error while booting instance.")
127         sys.exit(-1)
128     # Retrieve IP of INSTANCE
129     instance_ip = instance.networks.get(NET_NAME)[0]
130     logger.debug("Instance '%s' got private ip '%s'." %
131                  (INSTANCE_NAME, instance_ip))
132
133     logger.info("Adding '%s' to security group '%s'..."
134                 % (INSTANCE_NAME, SECGROUP_NAME))
135     os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
136
137     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME)
138     floatip_dic = os_utils.create_floating_ip(neutron_client)
139     floatip_client = floatip_dic['fip_addr']
140     # floatip_id = floatip_dic['fip_id']
141
142     if floatip_client is None:
143         logger.error("Cannot create floating IP.")
144         sys.exit(-1)
145     logger.info("Floating IP created: '%s'" % floatip_client)
146
147     logger.info("Associating floating ip: '%s' to VM '%s' "
148                 % (floatip_client, INSTANCE_NAME))
149     if not os_utils.add_floating_ip(nova_client, instance.id, floatip_client):
150         logger.error("Cannot associate floating IP to VM.")
151         sys.exit(-1)
152
153 # STARTING SECOND VM (server) ###
154
155     # boot INTANCE
156     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
157     logger.debug(
158         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
159         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
160     instance_2 = os_utils.create_instance_and_wait_for_active(FLAVOR,
161                                                               image_id,
162                                                               network_id,
163                                                               INSTANCE_NAME_2)
164
165     if instance_2 is None:
166         logger.error("Error while booting instance.")
167         sys.exit(-1)
168     # Retrieve IP of INSTANCE
169     instance_ip_2 = instance_2.networks.get(NET_NAME)[0]
170     logger.debug("Instance '%s' got private ip '%s'." %
171                  (INSTANCE_NAME_2, instance_ip_2))
172
173     logger.info("Adding '%s' to security group '%s'..."
174                 % (INSTANCE_NAME_2, SECGROUP_NAME))
175     os_utils.add_secgroup_to_instance(nova_client, instance_2.id, sg_id)
176
177     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME_2)
178     floatip_dic = os_utils.create_floating_ip(neutron_client)
179     floatip_server = floatip_dic['fip_addr']
180     # floatip_id = floatip_dic['fip_id']
181
182     if floatip_server is None:
183         logger.error("Cannot create floating IP.")
184         sys.exit(-1)
185     logger.info("Floating IP created: '%s'" % floatip_server)
186
187     logger.info("Associating floating ip: '%s' to VM '%s' "
188                 % (floatip_server, INSTANCE_NAME_2))
189
190     if not os_utils.add_floating_ip(nova_client,
191                                     instance_2.id,
192                                     floatip_server):
193         logger.error("Cannot associate floating IP to VM.")
194         sys.exit(-1)
195
196     # CREATION OF THE 2 SF ####
197
198     tacker_script = "/home/opnfv/repos/functest/testcases/features/sfc/" + \
199         TACKER_SCRIPT
200     logger.info("Executing tacker script: '%s'" % tacker_script)
201     subprocess.call(tacker_script, shell=True)
202
203     # SSH CALL TO START HTTP SERVER
204     ssh = paramiko.SSHClient()
205     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
206
207     try:
208         ssh.connect(floatip_server, username="root",
209                     password="opnfv", timeout=2)
210         command = "python -m SimpleHTTPServer 80 > /dev/null 2>&1 &"
211         logger.info("Starting HTTP server")
212         (stdin, stdout, stderr) = ssh.exec_command(command)
213     except:
214         logger.debug("Waiting for %s..." % floatip_server)
215         time.sleep(6)
216         # timeout -= 1
217
218     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
219     ips = []
220     try:
221         for instance in instances:
222             if "server" not in instance.name:
223                 if "client" not in instance.name:
224                     logger.debug(
225                         "This is the instance name: %s " % instance.name)
226                     floatip_dic = os_utils.create_floating_ip(neutron_client)
227                     floatip = floatip_dic['fip_addr']
228                     ips.append(floatip)
229                     instance.add_floating_ip(floatip)
230     except:
231         logger.debug("Problems assigning floating IP to SFs")
232
233     logger.debug("Floating IPs for SFs: %s..." % ips)
234     # SSH TO START THE VXLAN_TOOL ON SF1
235     logger.info("Configuring the SFs")
236     try:
237         ssh.connect(ips[0], username="root",
238                     password="opnfv", timeout=2)
239         command = ("nohup python vxlan_tool.py -i eth0 "
240                    "-d forward -v off -f -b 80 &")
241         (stdin, stdout, stderr) = ssh.exec_command(command)
242     except:
243         logger.debug("Waiting for %s..." % ips[0])
244         time.sleep(6)
245         # timeout -= 1
246
247     # SSH TO START THE VXLAN_TOOL ON SF2
248     try:
249         ssh.connect(ips[1], username="root",
250                     password="opnfv", timeout=2)
251         command = ("nohup python vxlan_tool.py -i eth0 "
252                    "-d forward -v off -f -b 22 &")
253         (stdin, stdout, stderr) = ssh.exec_command(command)
254     except:
255         logger.debug("Waiting for %s..." % ips[1])
256         time.sleep(6)
257         # timeout -= 1
258
259     # SSH TO EXECUTE cmd_client
260
261     logger.info("TEST STARTED")
262     try:
263         ssh.connect(floatip_client, username="root",
264                     password="opnfv", timeout=2)
265         command = "nc -w 5 -zv " + floatip_server + " 22 2>&1"
266         (stdin, stdout, stderr) = ssh.exec_command(command)
267     except:
268         logger.debug("Waiting for %s..." % floatip_client)
269         time.sleep(6)
270         # timeout -= 1
271
272     # WRITE THE CORRECT WAY TO DO LOGGING
273     i = 0
274     logger.info("First output: %s" % stdout.readlines())
275     if "timed out" in stdout.readlines()[0]:
276         logger.info('\033[92m' + "TEST 1 [PASSED] "
277                     "==> SSH BLOCKED" + '\033[0m')
278         i = i + 1
279     else:
280         logger.debug('\033[91m' + "TEST 1 [FAILED] "
281                      "==> SSH NOT BLOCKED" + '\033[0m')
282         return
283
284     # SSH TO EXECUTE cmd_client
285
286     try:
287         ssh.connect(floatip_client, username="root",
288                     password="opnfv", timeout=2)
289         command = "nc -w 5 -zv " + floatip_server + " 80 2>&1"
290         (stdin, stdout, stderr) = ssh.exec_command(command)
291     except:
292         logger.debug("Waiting for %s..." % floatip_client)
293         time.sleep(6)
294         # timeout -= 1
295
296     if "succeeded" in stdout.readlines()[0]:
297         logger.info('\033[92m' + "TEST 2 [PASSED] "
298                     "==> HTTP WORKS" + '\033[0m')
299         i = i + 1
300     else:
301         logger.debug('\033[91m' + "TEST 2 [FAILED] "
302                      "==> HTTP BLOCKED" + '\033[0m')
303         return
304
305     # CHANGE OF CLASSIFICATION #
306     logger.info("Changing the classification")
307     tacker_classi = "/home/opnfv/repos/functest/testcases/features/sfc/" + \
308         TACKER_CHANGECLASSI
309     subprocess.call(tacker_classi, shell=True)
310
311     # SSH TO EXECUTE cmd_client
312
313     try:
314         ssh.connect(floatip_client, username="root",
315                     password="opnfv", timeout=2)
316         command = "nc -w 5 -zv " + floatip_server + " 80 2>&1"
317         (stdin, stdout, stderr) = ssh.exec_command(command)
318     except:
319         logger.debug("Waiting for %s..." % floatip_client)
320         time.sleep(6)
321         # timeout -= 1
322
323     if "timed out" in stdout.readlines()[0]:
324         logger.info('\033[92m' + "TEST 3 [WORKS] "
325                     "==> HTTP BLOCKED" + '\033[0m')
326         i = i + 1
327     else:
328         logger.debug('\033[91m' + "TEST 3 [FAILED] "
329                      "==> HTTP NOT BLOCKED" + '\033[0m')
330         return
331
332     # SSH TO EXECUTE cmd_client
333
334     try:
335         ssh.connect(floatip_client, username="root",
336                     password="opnfv", timeout=2)
337         command = "nc -w 5 -zv " + floatip_server + " 22 2>&1"
338         (stdin, stdout, stderr) = ssh.exec_command(command)
339     except:
340         logger.debug("Waiting for %s..." % floatip_client)
341         time.sleep(6)
342         # timeout -= 1
343
344     if "succeeded" in stdout.readlines()[0]:
345         logger.info('\033[92m' + "TEST 4 [WORKS] "
346                     "==> SSH WORKS" + '\033[0m')
347         i = i + 1
348     else:
349         logger.debug('\033[91m' + "TEST 4 [FAILED] "
350                      "==> SSH BLOCKED" + '\033[0m')
351         return
352
353     if i == 4:
354         for x in range(0, 5):
355             logger.info('\033[92m' + "SFC TEST WORKED"
356                         " :) \n" + '\033[0m')
357
358     sys.exit(0)
359
360 if __name__ == '__main__':
361     main()