Multi-compute support and python refactoring
[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 paramiko
8
9 import functest.utils.functest_logger as ft_logger
10 import functest.utils.functest_utils as ft_utils
11 import functest.utils.openstack_utils as os_utils
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 FUNCTEST_REPO = ft_utils.FUNCTEST_REPO
25
26 HOME = os.environ['HOME'] + "/"
27
28 VM_BOOT_TIMEOUT = 180
29 INSTANCE_NAME = "client"
30 FLAVOR = "custom"
31 IMAGE_NAME = "sf_nsh_colorado"
32 IMAGE_FILENAME = "sf_nsh_colorado.qcow2"
33 IMAGE_FORMAT = "qcow2"
34 IMAGE_PATH = "/home/opnfv/functest/data" + "/" + IMAGE_FILENAME
35
36 # NEUTRON Private Network parameters
37
38 NET_NAME = "example-net"
39 SUBNET_NAME = "example-subnet"
40 SUBNET_CIDR = "11.0.0.0/24"
41 ROUTER_NAME = "example-router"
42
43 SECGROUP_NAME = "example-sg"
44 SECGROUP_DESCR = "Example Security group"
45
46 INSTANCE_NAME_2 = "server"
47
48 # TEST_DB = ft_utils.get_parameter_from_yaml("results.test_db_url")
49
50 PRE_SETUP_SCRIPT = 'sfc_pre_setup.bash'
51 TACKER_SCRIPT = 'sfc_tacker.bash'
52 TEARDOWN_SCRIPT = "sfc_teardown.bash"
53 TACKER_CHANGECLASSI = "sfc_change_classi.bash"
54
55 ssh_options = '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
56
57
58 def check_ssh(ip):
59     cmd = "sshpass -p opnfv ssh " + ssh_options + " -q " + ip + " exit"
60     success = subprocess.call(cmd, shell=True) == 0
61     if not success:
62         logger.debug("Wating for SSH connectivity in SF with IP: %s" % ip)
63     return success
64
65
66 def main():
67
68     # Allow any port so that tacker commands reaches the server.
69     # This will be deleted when tacker is included in OPNFV installation
70
71     status = "PASS"
72     failures = 0
73     start_time = time.time()
74     json_results = {}
75
76     contr_cmd = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
77                  " 'fuel node'|grep controller|awk '{print $10}'")
78     logger.info("Executing script to get ip_server: '%s'" % contr_cmd)
79     process = subprocess.Popen(contr_cmd,
80                                shell=True,
81                                stdout=subprocess.PIPE,
82                                stderr=subprocess.PIPE)
83     ip_server = process.stdout.readline().rstrip()
84
85     contr_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
86                   " 'fuel node'|grep compute|awk '{print $10}'")
87     logger.info("Executing script to get ip_compute: '%s'" % contr_cmd2)
88     process = subprocess.Popen(contr_cmd2,
89                                shell=True,
90                                stdout=subprocess.PIPE,
91                                stderr=subprocess.PIPE)
92     ip_compute = process.stdout.readline().rstrip()
93
94     iptable_cmd1 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
95                     " ssh " + ip_server + " iptables -P INPUT ACCEPT ")
96     iptable_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
97                     " ssh " + ip_server + " iptables -t nat -P INPUT ACCEPT ")
98     iptable_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
99                     " ssh " + ssh_options + " " + ip_server +
100                     " iptables -A INPUT -m state"
101                     " --state NEW,ESTABLISHED,RELATED -j ACCEPT")
102
103     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd1)
104     subprocess.call(iptable_cmd1, shell=True, stderr=subprocess.PIPE)
105
106     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd2)
107     subprocess.call(iptable_cmd2, shell=True, stderr=subprocess.PIPE)
108
109     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd3)
110     subprocess.call(iptable_cmd3, shell=True, stderr=subprocess.PIPE)
111
112 # Getting the different clients
113
114     nova_client = os_utils.get_nova_client()
115     neutron_client = os_utils.get_neutron_client()
116     glance_client = os_utils.get_glance_client()
117
118 # Download the image
119
120     if not os.path.isfile(IMAGE_PATH):
121         logger.info("Downloading image")
122         ft_utils.download_url(
123             "http://artifacts.opnfv.org/sfc/demo/sf_nsh_colorado.qcow2",
124             "/home/opnfv/functest/data/")
125     else:
126         logger.info("Using old image")
127
128 # Create glance image and the neutron network
129
130     image_id = os_utils.create_glance_image(glance_client,
131                                             IMAGE_NAME,
132                                             IMAGE_PATH,
133                                             disk=IMAGE_FORMAT,
134                                             container="bare",
135                                             public=True)
136
137     network_dic = os_utils.create_network_full(neutron_client,
138                                                NET_NAME,
139                                                SUBNET_NAME,
140                                                ROUTER_NAME,
141                                                SUBNET_CIDR)
142     if not network_dic:
143         logger.error(
144             "There has been a problem when creating the neutron network")
145         sys.exit(-1)
146
147     network_id = network_dic["net_id"]
148
149     sg_id = os_utils.create_security_group_full(neutron_client,
150                                                 SECGROUP_NAME, SECGROUP_DESCR)
151
152     secgroups = os_utils.get_security_groups(neutron_client)
153
154     for sg in secgroups:
155         os_utils.create_secgroup_rule(neutron_client, sg['id'],
156                                       'ingress', 'tcp',
157                                       port_range_min=22,
158                                       port_range_max=22)
159         os_utils.create_secgroup_rule(neutron_client, sg['id'],
160                                       'egress', 'tcp',
161                                       port_range_min=22,
162                                       port_range_max=22)
163
164     _, custom_flv_id = os_utils.get_or_create_flavor(
165         'custom', 1500, 10, 1, public=True)
166     if not custom_flv_id:
167         logger.error("Failed to create custom flavor")
168         sys.exit(1)
169
170     # boot INSTANCE
171     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
172     logger.debug(
173         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
174         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
175     instance = os_utils.create_instance_and_wait_for_active(FLAVOR,
176                                                             image_id,
177                                                             network_id,
178                                                             INSTANCE_NAME)
179
180     if instance is None:
181         logger.error("Error while booting instance.")
182         sys.exit(-1)
183     # Retrieve IP of INSTANCE
184     instance_ip = instance.networks.get(NET_NAME)[0]
185     logger.debug("Instance '%s' got private ip '%s'." %
186                  (INSTANCE_NAME, instance_ip))
187
188     logger.info("Adding '%s' to security group '%s'..."
189                 % (INSTANCE_NAME, SECGROUP_NAME))
190     os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
191
192     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME)
193     floatip_dic = os_utils.create_floating_ip(neutron_client)
194     floatip_client = floatip_dic['fip_addr']
195     # floatip_id = floatip_dic['fip_id']
196
197     if floatip_client is None:
198         logger.error("Cannot create floating IP.")
199         sys.exit(-1)
200     logger.info("Floating IP created: '%s'" % floatip_client)
201
202     logger.info("Associating floating ip: '%s' to VM '%s' "
203                 % (floatip_client, INSTANCE_NAME))
204     if not os_utils.add_floating_ip(nova_client, instance.id, floatip_client):
205         logger.error("Cannot associate floating IP to VM.")
206         sys.exit(-1)
207
208 # STARTING SECOND VM (server) ###
209
210     # boot INTANCE
211     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
212     logger.debug(
213         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
214         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
215     instance_2 = os_utils.create_instance_and_wait_for_active(FLAVOR,
216                                                               image_id,
217                                                               network_id,
218                                                               INSTANCE_NAME_2)
219
220     if instance_2 is None:
221         logger.error("Error while booting instance.")
222         sys.exit(-1)
223     # Retrieve IP of INSTANCE
224     instance_ip_2 = instance_2.networks.get(NET_NAME)[0]
225     logger.debug("Instance '%s' got private ip '%s'." %
226                  (INSTANCE_NAME_2, instance_ip_2))
227
228     logger.info("Adding '%s' to security group '%s'..."
229                 % (INSTANCE_NAME_2, SECGROUP_NAME))
230     os_utils.add_secgroup_to_instance(nova_client, instance_2.id, sg_id)
231
232     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME_2)
233     floatip_dic = os_utils.create_floating_ip(neutron_client)
234     floatip_server = floatip_dic['fip_addr']
235     # floatip_id = floatip_dic['fip_id']
236
237     if floatip_server is None:
238         logger.error("Cannot create floating IP.")
239         sys.exit(-1)
240     logger.info("Floating IP created: '%s'" % floatip_server)
241
242     logger.info("Associating floating ip: '%s' to VM '%s' "
243                 % (floatip_server, INSTANCE_NAME_2))
244
245     if not os_utils.add_floating_ip(nova_client,
246                                     instance_2.id,
247                                     floatip_server):
248         logger.error("Cannot associate floating IP to VM.")
249         sys.exit(-1)
250
251     # CREATION OF THE 2 SF ####
252
253     tacker_script = "%s/testcases/features/sfc/%s" % \
254                     (FUNCTEST_REPO, TACKER_SCRIPT)
255     logger.info("Executing tacker script: '%s'" % tacker_script)
256     subprocess.call(tacker_script, shell=True)
257
258     # SSH CALL TO START HTTP SERVER
259     ssh = paramiko.SSHClient()
260     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
261
262     try:
263         ssh.connect(floatip_server, username="root",
264                     password="opnfv", timeout=2)
265         command = "python -m SimpleHTTPServer 80 > /dev/null 2>&1 &"
266         logger.info("Starting HTTP server")
267         (stdin, stdout, stderr) = ssh.exec_command(command)
268     except:
269         logger.debug("Waiting for %s..." % floatip_server)
270         time.sleep(6)
271         # timeout -= 1
272
273     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
274     ips = []
275     try:
276         for instance in instances:
277             if "server" not in instance.name:
278                 if "client" not in instance.name:
279                     logger.debug(
280                         "This is the instance name: %s " % instance.name)
281                     floatip_dic = os_utils.create_floating_ip(neutron_client)
282                     floatip = floatip_dic['fip_addr']
283                     ips.append(floatip)
284                     instance.add_floating_ip(floatip)
285     except:
286         logger.debug("Problems assigning floating IP to SFs")
287
288     # If no IPs were obtained, then we cant continue
289     if not ips:
290         logger.error('Failed to obtain IPs, cant continue, exiting')
291         return
292
293     logger.debug("Floating IPs for SFs: %s..." % ips)
294
295     # Check SSH connectivity to VNFs
296     r = 0
297     retries = 100
298     check = [False, False]
299
300     logger.info("Checking SSH connectivity to the SFs with ips %s" % str(ips))
301     while r < retries and not all(check):
302         try:
303             check = [check_ssh(ips[0]), check_ssh(ips[1])]
304         except Exception:
305             logger.exception("SSH check failed")
306             check = [False, False]
307         time.sleep(3)
308         r += 1
309
310     if not all(check):
311         logger.error("Cannot establish SSH connection to the SFs")
312         sys.exit(1)
313
314     logger.info("SSH connectivity to the SFs established")
315
316     # SSH TO START THE VXLAN_TOOL ON SF1
317     logger.info("Configuring the SFs")
318     try:
319         ssh.connect(ips[0], username="root",
320                     password="opnfv", timeout=2)
321         command = ("nohup python vxlan_tool.py -i eth0 "
322                    "-d forward -v off -b 80 > /dev/null 2>&1 &")
323         (stdin, stdout, stderr) = ssh.exec_command(command)
324     except:
325         logger.debug("Waiting for %s..." % ips[0])
326         time.sleep(6)
327         # timeout -= 1
328
329     try:
330         while 1:
331             (stdin, stdout, stderr) = ssh.exec_command(
332                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
333             if len(stdout.readlines()) > 0:
334                 logger.debug("HTTP firewall started")
335                 break
336             else:
337                 logger.debug("HTTP firewall not started")
338                 time.sleep(3)
339     except Exception:
340         logger.exception("vxlan_tool not started in SF1")
341
342     # SSH TO START THE VXLAN_TOOL ON SF2
343     try:
344         ssh.connect(ips[1], username="root",
345                     password="opnfv", timeout=2)
346         command = ("nohup python vxlan_tool.py -i eth0 "
347                    "-d forward -v off -b 22 > /dev/null 2>&1 &")
348         (stdin, stdout, stderr) = ssh.exec_command(command)
349     except:
350         logger.debug("Waiting for %s..." % ips[1])
351         time.sleep(6)
352         # timeout -= 1
353
354     try:
355         while 1:
356             (stdin, stdout, stderr) = ssh.exec_command(
357                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
358             if len(stdout.readlines()) > 0:
359                 logger.debug("SSH firewall started")
360                 break
361             else:
362                 logger.debug("SSH firewall not started")
363                 time.sleep(3)
364     except Exception:
365         logger.exception("vxlan_tool not started in SF2")
366
367     # SSH to modify the classification flows in compute
368
369     contr_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
370                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
371     logger.info("Executing script to modify the classi: '%s'" % contr_cmd3)
372     process = subprocess.Popen(contr_cmd3,
373                                shell=True,
374                                stdout=subprocess.PIPE)
375
376     i = 0
377
378     # SSH TO EXECUTE cmd_client
379     logger.info("TEST STARTED")
380     try:
381         ssh.connect(floatip_client, username="root",
382                     password="opnfv", timeout=2)
383         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
384         (stdin, stdout, stderr) = ssh.exec_command(command)
385
386         # WRITE THE CORRECT WAY TO DO LOGGING
387         if "timed out" in stdout.readlines()[0]:
388             logger.info('\033[92m' + "TEST 1 [PASSED] "
389                         "==> SSH BLOCKED" + '\033[0m')
390             i = i + 1
391             json_results.update({"Test 1: SSH Blocked": "Passed"})
392         else:
393             logger.error('\033[91m' + "TEST 1 [FAILED] "
394                          "==> SSH NOT BLOCKED" + '\033[0m')
395             status = "FAIL"
396             json_results.update({"Test 1: SSH Blocked": "Failed"})
397             failures += 1
398     except:
399         logger.debug("Waiting for %s..." % floatip_client)
400         time.sleep(6)
401         # timeout -= 1
402
403     # SSH TO EXECUTE cmd_client
404     try:
405         ssh.connect(floatip_client, username="root",
406                     password="opnfv", timeout=2)
407         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
408         (stdin, stdout, stderr) = ssh.exec_command(command)
409
410         if "succeeded" in stdout.readlines()[0]:
411             logger.info('\033[92m' + "TEST 2 [PASSED] "
412                         "==> HTTP WORKS" + '\033[0m')
413             i = i + 1
414             json_results.update({"Test 2: HTTP works": "Passed"})
415         else:
416             logger.error('\033[91m' + "TEST 2 [FAILED] "
417                          "==> HTTP BLOCKED" + '\033[0m')
418             status = "FAIL"
419             json_results.update({"Test 2: HTTP works": "Failed"})
420             failures += 1
421     except:
422         logger.debug("Waiting for %s..." % floatip_client)
423         time.sleep(6)
424         # timeout -= 1
425
426     # CHANGE OF CLASSIFICATION #
427     logger.info("Changing the classification")
428     tacker_classi = "%s/testcases/features/sfc/%s" % \
429                     (FUNCTEST_REPO, TACKER_CHANGECLASSI)
430     subprocess.call(tacker_classi, shell=True)
431
432     logger.info("Wait for ODL to update the classification rules in OVS")
433     time.sleep(10)
434
435     # SSH to modify the classification flows in compute
436
437     contr_cmd4 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
438                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
439     logger.info("Executing script to modify the classi: '%s'" % contr_cmd4)
440     process = subprocess.Popen(contr_cmd4,
441                                shell=True,
442                                stdout=subprocess.PIPE)
443
444     # SSH TO EXECUTE cmd_client
445
446     try:
447         ssh.connect(floatip_client, username="root",
448                     password="opnfv", timeout=2)
449         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
450         (stdin, stdout, stderr) = ssh.exec_command(command)
451
452         if "timed out" in stdout.readlines()[0]:
453             logger.info('\033[92m' + "TEST 3 [PASSED] "
454                         "==> HTTP BLOCKED" + '\033[0m')
455             i = i + 1
456             json_results.update({"Test 3: HTTP Blocked": "Passed"})
457         else:
458             logger.error('\033[91m' + "TEST 3 [FAILED] "
459                          "==> HTTP NOT BLOCKED" + '\033[0m')
460             status = "FAIL"
461             json_results.update({"Test 3: HTTP Blocked": "Failed"})
462             failures += 1
463     except:
464         logger.debug("Waiting for %s..." % floatip_client)
465         time.sleep(6)
466         # timeout -= 1
467
468     # SSH TO EXECUTE cmd_client
469     try:
470         ssh.connect(floatip_client, username="root",
471                     password="opnfv", timeout=2)
472         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
473         (stdin, stdout, stderr) = ssh.exec_command(command)
474
475         if "succeeded" in stdout.readlines()[0]:
476             logger.info('\033[92m' + "TEST 4 [PASSED] "
477                         "==> SSH WORKS" + '\033[0m')
478             i = i + 1
479             json_results.update({"Test 4: SSH works": "Passed"})
480         else:
481             logger.error('\033[91m' + "TEST 4 [FAILED] "
482                          "==> SSH BLOCKED" + '\033[0m')
483             status = "FAIL"
484             json_results.update({"Test 4: SSH works": "Failed"})
485             failures += 1
486     except:
487         logger.debug("Waiting for %s..." % floatip_client)
488         time.sleep(6)
489         # timeout -= 1
490
491     if i == 4:
492         for x in range(0, 5):
493             logger.info('\033[92m' + "SFC TEST WORKED"
494                         " :) \n" + '\033[0m')
495
496     if args.report:
497         stop_time = time.time()
498         json_results.update({"tests": "4", "failures": int(failures)})
499         logger.debug("Promise Results json: " + str(json_results))
500         ft_utils.push_results_to_db("sfc",
501                                     "functest-odl-sfc",
502                                     start_time,
503                                     stop_time,
504                                     status,
505                                     json_results)
506     if status == "PASS":
507         sys.exit(0)
508     else:
509         sys.exit(1)
510
511 if __name__ == '__main__':
512     main()