Create ovs log artifact on odl-sfc fail
[functest.git] / functest / opnfv_tests / 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 re
10 import json
11 import SSHUtils as ssh_utils
12 import ovs_utils
13 import thread
14
15 parser = argparse.ArgumentParser()
16
17 parser.add_argument("-r", "--report",
18                     help="Create json result file",
19                     action="store_true")
20
21 args = parser.parse_args()
22
23 """ logging configuration """
24 logger = ft_logger.Logger("ODL_SFC").getLogger()
25
26 FUNCTEST_RESULTS_DIR = '/home/opnfv/functest/results/odl-sfc'
27 FUNCTEST_REPO = ft_utils.FUNCTEST_REPO
28 REPO_PATH = os.path.join(os.environ['repos_dir'], 'functest/')
29 CLIENT = "client"
30 SERVER = "server"
31 FLAVOR = "custom"
32 IMAGE_NAME = "sf_nsh_colorado"
33 IMAGE_FILENAME = "sf_nsh_colorado.qcow2"
34 IMAGE_FORMAT = "qcow2"
35 IMAGE_DIR = "/home/opnfv/functest/data"
36 IMAGE_PATH = os.path.join(IMAGE_DIR, IMAGE_FILENAME)
37 IMAGE_URL = "http://artifacts.opnfv.org/sfc/demo/" + IMAGE_FILENAME
38
39 # NEUTRON Private Network parameters
40 NET_NAME = "example-net"
41 SUBNET_NAME = "example-subnet"
42 SUBNET_CIDR = "11.0.0.0/24"
43 ROUTER_NAME = "example-router"
44 SECGROUP_NAME = "example-sg"
45 SECGROUP_DESCR = "Example Security group"
46 SFC_TEST_DIR = os.path.join(REPO_PATH, "functest/opnfv_tests/features/sfc/")
47 TACKER_SCRIPT = SFC_TEST_DIR + "sfc_tacker.bash"
48 TACKER_CHANGECLASSI = SFC_TEST_DIR + "sfc_change_classi.bash"
49 ssh_options = '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
50 json_results = {"tests": 4, "failures": 0}
51
52 PROXY = {
53     'ip': '10.20.0.2',
54     'username': 'root',
55     'password': 'r00tme'
56 }
57
58 # run given command locally and return commands output if success
59
60
61 def run_cmd(cmd, wdir=None, ignore_stderr=False, ignore_no_output=True):
62     pipe = subprocess.Popen(cmd, shell=True,
63                             stdin=subprocess.PIPE,
64                             stdout=subprocess.PIPE,
65                             stderr=subprocess.PIPE, cwd=wdir)
66
67     (output, errors) = pipe.communicate()
68     if output:
69         output = output.strip()
70     if pipe.returncode < 0:
71         logger.error(errors)
72         return False
73     if errors:
74         logger.error(errors)
75         if ignore_stderr:
76             return True
77         else:
78             return False
79
80     if ignore_no_output:
81         if not output:
82             return True
83
84     return output
85
86 # run given command on OpenStack controller
87
88
89 def run_cmd_on_cntlr(cmd):
90     ip_cntlrs = get_openstack_node_ips("controller")
91     if not ip_cntlrs:
92         return None
93
94     ssh_cmd = "ssh %s %s %s" % (ssh_options, ip_cntlrs[0], cmd)
95     return run_cmd_on_fm(ssh_cmd)
96
97 # run given command on OpenStack Compute node
98
99
100 def run_cmd_on_compute(cmd):
101     ip_computes = get_openstack_node_ips("compute")
102     if not ip_computes:
103         return None
104
105     ssh_cmd = "ssh %s %s %s" % (ssh_options, ip_computes[0], cmd)
106     return run_cmd_on_fm(ssh_cmd)
107
108 # run given command on Fuel Master
109
110
111 def run_cmd_on_fm(cmd, username="root", passwd="r00tme"):
112     ip = os.environ.get("INSTALLER_IP")
113     ssh_cmd = "sshpass -p %s ssh %s %s@%s %s" % (
114         passwd, ssh_options, username, ip, cmd)
115     return run_cmd(ssh_cmd)
116
117 # run given command on Remote Machine, Can be VM
118
119
120 def run_cmd_remote(ip, cmd, username="root", passwd="opnfv"):
121     ssh_opt_append = "%s -o ConnectTimeout=50 " % ssh_options
122     ssh_cmd = "sshpass -p %s ssh %s %s@%s %s" % (
123         passwd, ssh_opt_append, username, ip, cmd)
124     return run_cmd(ssh_cmd)
125
126 # Get OpenStack Nodes IP Address
127
128
129 def get_openstack_node_ips(role):
130     fuel_env = os.environ.get("FUEL_ENV")
131     if fuel_env is not None:
132         cmd = "fuel2 node list -f json -e %s" % fuel_env
133     else:
134         cmd = "fuel2 node list -f json"
135
136     nodes = run_cmd_on_fm(cmd)
137     ips = []
138     nodes = json.loads(nodes)
139     for node in nodes:
140         if role in node["roles"]:
141             ips.append(node["ip"])
142
143     return ips
144
145 # Configures IPTABLES on OpenStack Controller
146
147
148 def configure_iptables():
149     iptable_cmds = ["iptables -P INPUT ACCEPT",
150                     "iptables -t nat -P INPUT ACCEPT",
151                     "iptables -A INPUT -m state \
152                     --state NEW,ESTABLISHED,RELATED -j ACCEPT"]
153
154     for cmd in iptable_cmds:
155         logger.info("Configuring %s on contoller" % cmd)
156         run_cmd_on_cntlr(cmd)
157
158     return
159
160
161 def download_image():
162     if not os.path.isfile(IMAGE_PATH):
163         logger.info("Downloading image")
164         ft_utils.download_url(IMAGE_URL, IMAGE_DIR)
165
166     logger.info("Using old image")
167     return
168
169
170 def setup_glance(glance_client):
171     image_id = os_utils.create_glance_image(glance_client,
172                                             IMAGE_NAME,
173                                             IMAGE_PATH,
174                                             disk=IMAGE_FORMAT,
175                                             container="bare",
176                                             public=True)
177
178     return image_id
179
180
181 def setup_neutron(neutron_client):
182     n_dict = os_utils.create_network_full(neutron_client,
183                                           NET_NAME,
184                                           SUBNET_NAME,
185                                           ROUTER_NAME,
186                                           SUBNET_CIDR)
187     if not n_dict:
188         logger.error("failed to create neutron network")
189         sys.exit(-1)
190
191     network_id = n_dict["net_id"]
192     return network_id
193
194
195 def setup_ingress_egress_secgroup(neutron_client, protocol,
196                                   min_port=None, max_port=None):
197     secgroups = os_utils.get_security_groups(neutron_client)
198     for sg in secgroups:
199         os_utils.create_secgroup_rule(neutron_client, sg['id'],
200                                       'ingress', protocol,
201                                       port_range_min=min_port,
202                                       port_range_max=max_port)
203         os_utils.create_secgroup_rule(neutron_client, sg['id'],
204                                       'egress', protocol,
205                                       port_range_min=min_port,
206                                       port_range_max=max_port)
207     return
208
209
210 def setup_security_groups(neutron_client):
211     sg_id = os_utils.create_security_group_full(neutron_client,
212                                                 SECGROUP_NAME, SECGROUP_DESCR)
213     setup_ingress_egress_secgroup(neutron_client, "icmp")
214     setup_ingress_egress_secgroup(neutron_client, "udp", 67, 68)
215     setup_ingress_egress_secgroup(neutron_client, "tcp", 22, 22)
216     setup_ingress_egress_secgroup(neutron_client, "tcp", 80, 80)
217     return sg_id
218
219
220 def boot_instance(nova_client, name, flavor, image_id, network_id, sg_id):
221     logger.info("Creating instance '%s'..." % name)
222     logger.debug(
223         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
224         "network=%s \n" % (name, flavor, image_id, network_id))
225
226     instance = os_utils.create_instance_and_wait_for_active(flavor,
227                                                             image_id,
228                                                             network_id,
229                                                             name)
230
231     if instance is None:
232         logger.error("Error while booting instance.")
233         sys.exit(-1)
234
235     instance_ip = instance.networks.get(NET_NAME)[0]
236     logger.debug("Instance '%s' got private ip '%s'." %
237                  (name, instance_ip))
238
239     logger.info("Adding '%s' to security group %s" % (name, SECGROUP_NAME))
240     os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
241
242     return instance_ip
243
244
245 def ping(remote, pkt_cnt=1, iface=None, retries=100, timeout=None):
246     ping_cmd = 'ping'
247
248     if timeout:
249         ping_cmd = ping_cmd + ' -w %s' % timeout
250
251     grep_cmd = "grep -e 'packet loss' -e rtt"
252
253     if iface is not None:
254         ping_cmd = ping_cmd + ' -I %s' % iface
255
256     ping_cmd = ping_cmd + ' -i 0 -c %d %s' % (pkt_cnt, remote)
257     cmd = ping_cmd + '|' + grep_cmd
258
259     while retries > 0:
260         output = run_cmd(cmd)
261         if not output:
262             return False
263
264         match = re.search('(\d*)% packet loss', output)
265         if not match:
266             return False
267
268         packet_loss = int(match.group(1))
269         if packet_loss == 0:
270             return True
271
272         retries = retries - 1
273
274     return False
275
276
277 def get_floating_ips(nova_client, neutron_client):
278     ips = []
279     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
280     for instance in instances:
281         floatip_dic = os_utils.create_floating_ip(neutron_client)
282         floatip = floatip_dic['fip_addr']
283         instance.add_floating_ip(floatip)
284         logger.info("Instance name and ip %s:%s " % (instance.name, floatip))
285         logger.info("Waiting for instance %s:%s to come up" %
286                     (instance.name, floatip))
287         if not ping(floatip):
288             logger.info("Instance %s:%s didn't come up" %
289                         (instance.name, floatip))
290             sys.exit(1)
291
292         if instance.name == "server":
293             logger.info("Server:%s is reachable" % floatip)
294             server_ip = floatip
295         elif instance.name == "client":
296             logger.info("Client:%s is reachable" % floatip)
297             client_ip = floatip
298         else:
299             logger.info("SF:%s is reachable" % floatip)
300             ips.append(floatip)
301
302     return server_ip, client_ip, ips[1], ips[0]
303
304 # Start http server on a give machine, Can be VM
305
306
307 def start_http_server(ip):
308     cmd = "\'python -m SimpleHTTPServer 80"
309     cmd = cmd + " > /dev/null 2>&1 &\'"
310     return run_cmd_remote(ip, cmd)
311
312 # Set firewall using vxlan_tool.py on a give machine, Can be VM
313
314
315 def vxlan_firewall(sf, iface="eth0", port="22", block=True):
316     cmd = "python vxlan_tool.py"
317     cmd = cmd + " -i " + iface + " -d forward -v off"
318     if block:
319         cmd = "python vxlan_tool.py -i eth0 -d forward -v off -b " + port
320
321     cmd = "sh -c 'cd /root;nohup " + cmd + " > /dev/null 2>&1 &'"
322     run_cmd_remote(sf, cmd)
323
324 # Run netcat on a give machine, Can be VM
325
326
327 def netcat(s_ip, c_ip, port="80", timeout=5):
328     cmd = "nc -zv "
329     cmd = cmd + " -w %s %s %s" % (timeout, s_ip, port)
330     cmd = cmd + " 2>&1"
331     output = run_cmd_remote(c_ip, cmd)
332     logger.info("%s" % output)
333     return output
334
335
336 def is_ssh_blocked(srv_prv_ip, client_ip):
337     res = netcat(srv_prv_ip, client_ip, port="22")
338     match = re.search("nc:.*timed out:.*", res, re.M)
339     if match:
340         return True
341
342     return False
343
344
345 def is_http_blocked(srv_prv_ip, client_ip):
346     res = netcat(srv_prv_ip, client_ip, port="80")
347     match = re.search(".* 80 port.* succeeded!", res, re.M)
348     if match:
349         return False
350
351     return True
352
353
354 def capture_err_logs(ovs_logger, controller_clients,
355                      compute_clients, error):
356     timestamp = time.strftime("%Y%m%d-%H%M%S")
357     ovs_logger.dump_ovs_logs(controller_clients,
358                              compute_clients,
359                              related_error=error,
360                              timestamp=timestamp)
361     return
362
363
364 def update_json_results(name, result):
365     json_results.update({name: result})
366     if result is not "Passed":
367         json_results["failures"] += 1
368
369     return
370
371
372 def get_ssh_clients(role):
373     clients = []
374     for ip in get_openstack_node_ips(role):
375         s_client = ssh_utils.get_ssh_client(ip,
376                                             'root',
377                                             proxy=PROXY)
378         clients.append(s_client)
379
380     return clients
381
382 # Check SSH connectivity to VNFs
383
384
385 def check_ssh(ips, retries=100):
386     check = [False, False]
387     logger.info("Checking SSH connectivity to the SFs with ips %s" % str(ips))
388     while retries and not all(check):
389         for index, ip in enumerate(ips):
390             check[index] = run_cmd_remote(ip, "exit")
391
392         if all(check):
393             logger.info("SSH connectivity to the SFs established")
394             return True
395
396         time.sleep(3)
397         retries -= 1
398
399     return False
400
401 # Measure the time it takes to update the classification rules
402
403
404 def capture_time_log(ovs_logger, compute_clients):
405     i = 0
406     first_RSP = ""
407     start_time = time.time()
408     while True:
409         rsps = ovs_logger.ofctl_time_counter(compute_clients[0])
410         if not i:
411             if len(rsps) > 0:
412                 first_RSP = rsps[0]
413                 i = i + 1
414             else:
415                 first_RSP = 0
416                 i = i + 1
417         if (len(rsps) > 1):
418             if(first_RSP != rsps[0]):
419                 if (rsps[0] == rsps[1]):
420                     stop_time = time.time()
421                     logger.info("classification rules updated")
422                     difference = stop_time - start_time
423                     logger.info("It took %s seconds" % difference)
424                     break
425         time.sleep(1)
426     return
427
428
429 def main():
430     installer_type = os.environ.get("INSTALLER_TYPE")
431     if installer_type != "fuel":
432         logger.error(
433             '\033[91mCurrently supported only Fuel Installer type\033[0m')
434         sys.exit(1)
435
436     installer_ip = os.environ.get("INSTALLER_IP")
437     if not installer_ip:
438         logger.error(
439             '\033[91minstaller ip is not set\033[0m')
440         logger.error(
441             '\033[91mexport INSTALLER_IP=<ip>\033[0m')
442         sys.exit(1)
443
444     env_list = run_cmd_on_fm("fuel2 env list -f json")
445     fuel_env = os.environ.get("FUEL_ENV")
446     if len(eval(env_list)) > 1 and fuel_env is None:
447         out = run_cmd_on_fm("fuel env")
448         logger.error(
449             '\033[91mMore than one fuel env found\033[0m\n %s' % out)
450         logger.error(
451             '\033[91mexport FUEL_ENV=<env-id> to set ENV\033[0m')
452         sys.exit(1)
453
454     start_time = time.time()
455     status = "PASS"
456     configure_iptables()
457     download_image()
458     _, custom_flv_id = os_utils.get_or_create_flavor(
459         FLAVOR, 1500, 10, 1, public=True)
460     if not custom_flv_id:
461         logger.error("Failed to create custom flavor")
462         sys.exit(1)
463
464     glance_client = os_utils.get_glance_client()
465     neutron_client = os_utils.get_neutron_client()
466     nova_client = os_utils.get_nova_client()
467
468     controller_clients = get_ssh_clients("controller")
469     compute_clients = get_ssh_clients("compute")
470
471     ovs_logger = ovs_utils.OVSLogger(
472         os.path.join(os.getcwd(), 'ovs-logs'),
473         FUNCTEST_RESULTS_DIR)
474
475     image_id = setup_glance(glance_client)
476     network_id = setup_neutron(neutron_client)
477     sg_id = setup_security_groups(neutron_client)
478
479     boot_instance(
480         nova_client, CLIENT, FLAVOR, image_id, network_id, sg_id)
481     srv_prv_ip = boot_instance(
482         nova_client, SERVER, FLAVOR, image_id, network_id, sg_id)
483
484     subprocess.call(TACKER_SCRIPT, shell=True)
485
486     # Start measuring the time it takes to implement the classification rules
487     try:
488         thread.start_new_thread(capture_time_log,
489                                 (ovs_logger, compute_clients,))
490     except Exception, e:
491         logger.error("Unable to start the thread that counts time %s" % e)
492
493     server_ip, client_ip, sf1, sf2 = get_floating_ips(
494         nova_client, neutron_client)
495
496     if not check_ssh([sf1, sf2]):
497         logger.error("Cannot establish SSH connection to the SFs")
498         sys.exit(1)
499
500     logger.info("Starting HTTP server on %s" % server_ip)
501     if not start_http_server(server_ip):
502         logger.error(
503             '\033[91mFailed to start HTTP server on %s\033[0m' % server_ip)
504         sys.exit(1)
505
506     logger.info("Starting HTTP firewall on %s" % sf2)
507     vxlan_firewall(sf2, port="80")
508     logger.info("Starting SSH firewall on %s" % sf1)
509     vxlan_firewall(sf1, port="22")
510
511     logger.info("Wait for ODL to update the classification rules in OVS")
512     time.sleep(120)
513
514     logger.info("Test SSH")
515     if is_ssh_blocked(srv_prv_ip, client_ip):
516         logger.info('\033[92mTEST 1 [PASSED] ==> SSH BLOCKED\033[0m')
517         update_json_results("Test 1: SSH Blocked", "Passed")
518     else:
519         error = ('\033[91mTEST 1 [FAILED] ==> SSH NOT BLOCKED\033[0m')
520         logger.error(error)
521         capture_err_logs(
522             ovs_logger, controller_clients, compute_clients, error)
523         update_json_results("Test 1: SSH Blocked", "Failed")
524
525     logger.info("Test HTTP")
526     if not is_http_blocked(srv_prv_ip, client_ip):
527         logger.info('\033[92mTEST 2 [PASSED] ==> HTTP WORKS\033[0m')
528         update_json_results("Test 2: HTTP works", "Passed")
529     else:
530         error = ('\033[91mTEST 2 [FAILED] ==> HTTP BLOCKED\033[0m')
531         logger.error(error)
532         capture_err_logs(
533             ovs_logger, controller_clients, compute_clients, error)
534         update_json_results("Test 2: HTTP works", "Failed")
535
536     logger.info("Changing the classification")
537     subprocess.call(TACKER_CHANGECLASSI, shell=True)
538
539     # Start measuring the time it takes to implement the classification rules
540     try:
541         thread.start_new_thread(capture_time_log,
542                                 (ovs_logger, compute_clients,))
543     except Exception, e:
544         logger.error("Unable to start the thread that counts time %s" % e)
545
546     logger.info("Wait for ODL to update the classification rules in OVS")
547     time.sleep(100)
548
549     logger.info("Test HTTP")
550     if is_http_blocked(srv_prv_ip, client_ip):
551         logger.info('\033[92mTEST 3 [PASSED] ==> HTTP Blocked\033[0m')
552         update_json_results("Test 3: HTTP Blocked", "Passed")
553     else:
554         error = ('\033[91mTEST 3 [FAILED] ==> HTTP WORKS\033[0m')
555         logger.error(error)
556         capture_err_logs(controller_clients, compute_clients, error)
557         update_json_results("Test 3: HTTP Blocked", "Failed")
558
559     logger.info("Test SSH")
560     if not is_ssh_blocked(srv_prv_ip, client_ip):
561         logger.info('\033[92mTEST 4 [PASSED] ==> SSH Works\033[0m')
562         update_json_results("Test 4: SSH Works", "Passed")
563     else:
564         error = ('\033[91mTEST 4 [FAILED] ==> SSH BLOCKED\033[0m')
565         logger.error(error)
566         capture_err_logs(controller_clients, compute_clients, error)
567         update_json_results("Test 4: SSH Works", "Failed")
568
569     if json_results["failures"]:
570         status = "FAIL"
571         logger.error('\033[91mSFC TESTS: %s :( FOUND %s FAIL \033[0m' % (
572             status, json_results["failures"]))
573
574     ovs_logger.create_artifact_archive()
575
576     if args.report:
577         stop_time = time.time()
578         logger.debug("Promise Results json: " + str(json_results))
579         ft_utils.push_results_to_db("sfc",
580                                     "functest-odl-sfc",
581                                     start_time,
582                                     stop_time,
583                                     status,
584                                     json_results)
585
586     if status == "PASS":
587         logger.info('\033[92mSFC ALL TESTS: %s :)\033[0m' % status)
588         sys.exit(0)
589
590     sys.exit(1)
591
592 if __name__ == '__main__':
593     main()