Merge "Fix image format set for rally test cases"
[functest.git] / testcases / features / sfc / sfc.py
1 import os
2 import subprocess
3 import sys
4 import time
5
6 import argparse
7 import functest.utils.functest_logger as ft_logger
8 import functest.utils.functest_utils as ft_utils
9 import functest.utils.openstack_utils as os_utils
10 import paramiko
11 from functest.utils.functest_utils import FUNCTEST_REPO as FUNCTEST_REPO
12
13 parser = argparse.ArgumentParser()
14
15 parser.add_argument("-r", "--report",
16                     help="Create json result file",
17                     action="store_true")
18
19 args = parser.parse_args()
20
21 """ logging configuration """
22 logger = ft_logger.Logger("ODL_SFC").getLogger()
23
24 HOME = os.environ['HOME'] + "/"
25
26 VM_BOOT_TIMEOUT = 180
27 INSTANCE_NAME = "client"
28 FLAVOR = "m1.small"
29 IMAGE_NAME = "sf_nsh_colorado"
30 IMAGE_FILENAME = "sf_nsh_colorado.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     # Allow any port so that tacker commands reaches the server.
57     # This will be deleted when tacker is included in OPNFV installation
58
59     ssh_options = '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
60     contr_cmd = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
61                  " 'fuel node'|grep controller|awk '{print $10}'")
62     logger.info("Executing script to get ip_server: '%s'" % contr_cmd)
63     process = subprocess.Popen(contr_cmd,
64                                shell=True,
65                                stdout=subprocess.PIPE,
66                                stderr=subprocess.PIPE)
67     ip_server = process.stdout.readline().rstrip()
68
69     contr_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
70                   " 'fuel node'|grep compute|awk '{print $10}'")
71     logger.info("Executing script to get ip_compute: '%s'" % contr_cmd2)
72     process = subprocess.Popen(contr_cmd2,
73                                shell=True,
74                                stdout=subprocess.PIPE,
75                                stderr=subprocess.PIPE)
76     ip_compute = process.stdout.readline().rstrip()
77
78     iptable_cmd1 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
79                     " ssh " + ip_server + " iptables -P INPUT ACCEPT ")
80     iptable_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
81                     " ssh " + ip_server + " iptables -t nat -P INPUT ACCEPT ")
82
83     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd1)
84     subprocess.call(iptable_cmd1, shell=True, stderr=subprocess.PIPE)
85
86     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd2)
87     subprocess.call(iptable_cmd2, shell=True, stderr=subprocess.PIPE)
88
89 # Getting the different clients
90
91     nova_client = os_utils.get_nova_client()
92     neutron_client = os_utils.get_neutron_client()
93     glance_client = os_utils.get_glance_client()
94
95 # Download the image
96
97     if not os.path.isfile(IMAGE_PATH):
98         logger.info("Downloading image")
99         ft_utils.download_url(
100             "http://artifacts.opnfv.org/sfc/demo/sf_nsh_colorado.qcow2",
101             "/home/opnfv/functest/data/")
102     else:
103         logger.info("Using old image")
104
105 # Create glance image and the neutron network
106
107     image_id = os_utils.create_glance_image(glance_client,
108                                             IMAGE_NAME,
109                                             IMAGE_PATH,
110                                             disk=IMAGE_FORMAT,
111                                             container="bare",
112                                             public=True)
113
114     network_dic = os_utils.create_network_full(neutron_client,
115                                                NET_NAME,
116                                                SUBNET_NAME,
117                                                ROUTER_NAME,
118                                                SUBNET_CIDR)
119     if not network_dic:
120         logger.error(
121             "There has been a problem when creating the neutron network")
122         sys.exit(-1)
123
124     network_id = network_dic["net_id"]
125
126     sg_id = os_utils.create_security_group_full(neutron_client,
127                                                 SECGROUP_NAME, SECGROUP_DESCR)
128
129     # boot INTANCE
130     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
131     logger.debug(
132         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
133         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
134     instance = os_utils.create_instance_and_wait_for_active(FLAVOR,
135                                                             image_id,
136                                                             network_id,
137                                                             INSTANCE_NAME)
138
139     if instance is None:
140         logger.error("Error while booting instance.")
141         sys.exit(-1)
142     # Retrieve IP of INSTANCE
143     instance_ip = instance.networks.get(NET_NAME)[0]
144     logger.debug("Instance '%s' got private ip '%s'." %
145                  (INSTANCE_NAME, instance_ip))
146
147     logger.info("Adding '%s' to security group '%s'..."
148                 % (INSTANCE_NAME, SECGROUP_NAME))
149     os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
150
151     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME)
152     floatip_dic = os_utils.create_floating_ip(neutron_client)
153     floatip_client = floatip_dic['fip_addr']
154     # floatip_id = floatip_dic['fip_id']
155
156     if floatip_client is None:
157         logger.error("Cannot create floating IP.")
158         sys.exit(-1)
159     logger.info("Floating IP created: '%s'" % floatip_client)
160
161     logger.info("Associating floating ip: '%s' to VM '%s' "
162                 % (floatip_client, INSTANCE_NAME))
163     if not os_utils.add_floating_ip(nova_client, instance.id, floatip_client):
164         logger.error("Cannot associate floating IP to VM.")
165         sys.exit(-1)
166
167 # STARTING SECOND VM (server) ###
168
169     # boot INTANCE
170     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
171     logger.debug(
172         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
173         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
174     instance_2 = os_utils.create_instance_and_wait_for_active(FLAVOR,
175                                                               image_id,
176                                                               network_id,
177                                                               INSTANCE_NAME_2)
178
179     if instance_2 is None:
180         logger.error("Error while booting instance.")
181         sys.exit(-1)
182     # Retrieve IP of INSTANCE
183     instance_ip_2 = instance_2.networks.get(NET_NAME)[0]
184     logger.debug("Instance '%s' got private ip '%s'." %
185                  (INSTANCE_NAME_2, instance_ip_2))
186
187     logger.info("Adding '%s' to security group '%s'..."
188                 % (INSTANCE_NAME_2, SECGROUP_NAME))
189     os_utils.add_secgroup_to_instance(nova_client, instance_2.id, sg_id)
190
191     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME_2)
192     floatip_dic = os_utils.create_floating_ip(neutron_client)
193     floatip_server = floatip_dic['fip_addr']
194     # floatip_id = floatip_dic['fip_id']
195
196     if floatip_server is None:
197         logger.error("Cannot create floating IP.")
198         sys.exit(-1)
199     logger.info("Floating IP created: '%s'" % floatip_server)
200
201     logger.info("Associating floating ip: '%s' to VM '%s' "
202                 % (floatip_server, INSTANCE_NAME_2))
203
204     if not os_utils.add_floating_ip(nova_client,
205                                     instance_2.id,
206                                     floatip_server):
207         logger.error("Cannot associate floating IP to VM.")
208         sys.exit(-1)
209
210     # CREATION OF THE 2 SF ####
211
212     tacker_script = "%s/testcases/features/sfc/%s" % \
213                     (FUNCTEST_REPO, TACKER_SCRIPT)
214     logger.info("Executing tacker script: '%s'" % tacker_script)
215     subprocess.call(tacker_script, shell=True)
216
217     # SSH CALL TO START HTTP SERVER
218     ssh = paramiko.SSHClient()
219     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
220
221     try:
222         ssh.connect(floatip_server, username="root",
223                     password="opnfv", timeout=2)
224         command = "python -m SimpleHTTPServer 80 > /dev/null 2>&1 &"
225         logger.info("Starting HTTP server")
226         (stdin, stdout, stderr) = ssh.exec_command(command)
227     except:
228         logger.debug("Waiting for %s..." % floatip_server)
229         time.sleep(6)
230         # timeout -= 1
231
232     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
233     ips = []
234     try:
235         for instance in instances:
236             if "server" not in instance.name:
237                 if "client" not in instance.name:
238                     logger.debug(
239                         "This is the instance name: %s " % instance.name)
240                     floatip_dic = os_utils.create_floating_ip(neutron_client)
241                     floatip = floatip_dic['fip_addr']
242                     ips.append(floatip)
243                     instance.add_floating_ip(floatip)
244     except:
245         logger.debug("Problems assigning floating IP to SFs")
246
247     # If no IPs were obtained, then we cant continue
248     if not ips:
249         logger.error('Failed to obtain IPs, cant continue, exiting')
250         return
251
252     logger.debug("Floating IPs for SFs: %s..." % ips)
253
254     # SSH TO START THE VXLAN_TOOL ON SF1
255     logger.info("Configuring the SFs")
256     try:
257         ssh.connect(ips[0], username="root",
258                     password="opnfv", timeout=2)
259         command = ("nohup python vxlan_tool.py -i eth0 "
260                    "-d forward -v off -b 80 > /dev/null 2>&1 &")
261         (stdin, stdout, stderr) = ssh.exec_command(command)
262     except:
263         logger.debug("Waiting for %s..." % ips[0])
264         time.sleep(6)
265         # timeout -= 1
266
267     try:
268         while 1:
269             (stdin, stdout, stderr) = ssh.exec_command(
270                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
271             if len(stdout.readlines()) > 0:
272                 logger.debug("HTTP firewall started")
273                 break
274             else:
275                 logger.debug("HTTP firewall not started")
276                 time.sleep(3)
277     except Exception:
278         logger.exception("vxlan_tool not started in SF1")
279
280     # SSH TO START THE VXLAN_TOOL ON SF2
281     try:
282         ssh.connect(ips[1], username="root",
283                     password="opnfv", timeout=2)
284         command = ("nohup python vxlan_tool.py -i eth0 "
285                    "-d forward -v off -b 22 > /dev/null 2>&1 &")
286         (stdin, stdout, stderr) = ssh.exec_command(command)
287     except:
288         logger.debug("Waiting for %s..." % ips[1])
289         time.sleep(6)
290         # timeout -= 1
291
292     try:
293         while 1:
294             (stdin, stdout, stderr) = ssh.exec_command(
295                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
296             if len(stdout.readlines()) > 0:
297                 logger.debug("SSH firewall started")
298                 break
299             else:
300                 logger.debug("SSH firewall not started")
301                 time.sleep(3)
302     except Exception:
303         logger.exception("vxlan_tool not started in SF2")
304
305     # SSH to modify the classification flows in compute
306
307     contr_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
308                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
309     logger.info("Executing script to modify the classi: '%s'" % contr_cmd3)
310     process = subprocess.Popen(contr_cmd3,
311                                shell=True,
312                                stdout=subprocess.PIPE)
313
314     logger.info("Waiting for 60 seconds before TEST")
315     for j in range(0, 6):
316         logger.info("Test starting in {0} seconds".format(str((6 - j)*10)))
317         time.sleep(10)
318
319     i = 0
320
321     # SSH TO EXECUTE cmd_client
322     logger.info("TEST STARTED")
323     try:
324         ssh.connect(floatip_client, username="root",
325                     password="opnfv", timeout=2)
326         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
327         (stdin, stdout, stderr) = ssh.exec_command(command)
328
329         # WRITE THE CORRECT WAY TO DO LOGGING
330         if "timed out" in stdout.readlines()[0]:
331             logger.info('\033[92m' + "TEST 1 [PASSED] "
332                         "==> SSH BLOCKED" + '\033[0m')
333             i = i + 1
334         else:
335             logger.error('\033[91m' + "TEST 1 [FAILED] "
336                          "==> SSH NOT BLOCKED" + '\033[0m')
337             return
338     except:
339         logger.debug("Waiting for %s..." % floatip_client)
340         time.sleep(6)
341         # timeout -= 1
342
343     # SSH TO EXECUTE cmd_client
344     try:
345         ssh.connect(floatip_client, username="root",
346                     password="opnfv", timeout=2)
347         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
348         (stdin, stdout, stderr) = ssh.exec_command(command)
349
350         if "succeeded" in stdout.readlines()[0]:
351             logger.info('\033[92m' + "TEST 2 [PASSED] "
352                         "==> HTTP WORKS" + '\033[0m')
353             i = i + 1
354         else:
355             logger.error('\033[91m' + "TEST 2 [FAILED] "
356                          "==> HTTP BLOCKED" + '\033[0m')
357             return
358     except:
359         logger.debug("Waiting for %s..." % floatip_client)
360         time.sleep(6)
361         # timeout -= 1
362
363     # CHANGE OF CLASSIFICATION #
364     logger.info("Changing the classification")
365     tacker_classi = "%s/testcases/features/sfc/%s" % \
366                     (FUNCTEST_REPO, TACKER_CHANGECLASSI)
367     subprocess.call(tacker_classi, shell=True)
368
369     logger.info("Wait for ODL to update the classification rules in OVS")
370     time.sleep(10)
371
372     # SSH to modify the classification flows in compute
373
374     contr_cmd4 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
375                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
376     logger.info("Executing script to modify the classi: '%s'" % contr_cmd4)
377     process = subprocess.Popen(contr_cmd4,
378                                shell=True,
379                                stdout=subprocess.PIPE)
380
381     # SSH TO EXECUTE cmd_client
382
383     try:
384         ssh.connect(floatip_client, username="root",
385                     password="opnfv", timeout=2)
386         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
387         (stdin, stdout, stderr) = ssh.exec_command(command)
388
389         if "timed out" in stdout.readlines()[0]:
390             logger.info('\033[92m' + "TEST 3 [WORKS] "
391                         "==> HTTP BLOCKED" + '\033[0m')
392             i = i + 1
393         else:
394             logger.error('\033[91m' + "TEST 3 [FAILED] "
395                          "==> HTTP NOT BLOCKED" + '\033[0m')
396             return
397     except:
398         logger.debug("Waiting for %s..." % floatip_client)
399         time.sleep(6)
400         # timeout -= 1
401
402     # SSH TO EXECUTE cmd_client
403     try:
404         ssh.connect(floatip_client, username="root",
405                     password="opnfv", timeout=2)
406         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
407         (stdin, stdout, stderr) = ssh.exec_command(command)
408
409         if "succeeded" in stdout.readlines()[0]:
410             logger.info('\033[92m' + "TEST 4 [WORKS] "
411                         "==> SSH WORKS" + '\033[0m')
412             i = i + 1
413         else:
414             logger.error('\033[91m' + "TEST 4 [FAILED] "
415                          "==> SSH BLOCKED" + '\033[0m')
416             return
417     except:
418         logger.debug("Waiting for %s..." % floatip_client)
419         time.sleep(6)
420         # timeout -= 1
421
422     if i == 4:
423         for x in range(0, 5):
424             logger.info('\033[92m' + "SFC TEST WORKED"
425                         " :) \n" + '\033[0m')
426
427     # TODO report results to DB
428     # functest_utils.logger_test_results("SFC",
429     # "odl-sfc",
430     # status, details)
431     # see doctor, promise, domino, ...
432     # if args.report:
433         # logger.info("Pushing odl-SFC results")
434         # functest_utils.push_results_to_db("functest",
435         #                                  "odl-sfc",
436         #                                  start_time,
437         #                                  stop_time,
438         #                                  status,
439         #                                  details)
440
441     sys.exit(0)
442
443 if __name__ == '__main__':
444     main()