Open secgroups and add check_ssh in sfc_colorado1
[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 = "m1.small"
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     # boot INSTANCE
165     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
166     logger.debug(
167         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
168         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
169     instance = os_utils.create_instance_and_wait_for_active(FLAVOR,
170                                                             image_id,
171                                                             network_id,
172                                                             INSTANCE_NAME)
173
174     if instance is None:
175         logger.error("Error while booting instance.")
176         sys.exit(-1)
177     # Retrieve IP of INSTANCE
178     instance_ip = instance.networks.get(NET_NAME)[0]
179     logger.debug("Instance '%s' got private ip '%s'." %
180                  (INSTANCE_NAME, instance_ip))
181
182     logger.info("Adding '%s' to security group '%s'..."
183                 % (INSTANCE_NAME, SECGROUP_NAME))
184     os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
185
186     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME)
187     floatip_dic = os_utils.create_floating_ip(neutron_client)
188     floatip_client = floatip_dic['fip_addr']
189     # floatip_id = floatip_dic['fip_id']
190
191     if floatip_client is None:
192         logger.error("Cannot create floating IP.")
193         sys.exit(-1)
194     logger.info("Floating IP created: '%s'" % floatip_client)
195
196     logger.info("Associating floating ip: '%s' to VM '%s' "
197                 % (floatip_client, INSTANCE_NAME))
198     if not os_utils.add_floating_ip(nova_client, instance.id, floatip_client):
199         logger.error("Cannot associate floating IP to VM.")
200         sys.exit(-1)
201
202 # STARTING SECOND VM (server) ###
203
204     # boot INTANCE
205     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
206     logger.debug(
207         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
208         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
209     instance_2 = os_utils.create_instance_and_wait_for_active(FLAVOR,
210                                                               image_id,
211                                                               network_id,
212                                                               INSTANCE_NAME_2)
213
214     if instance_2 is None:
215         logger.error("Error while booting instance.")
216         sys.exit(-1)
217     # Retrieve IP of INSTANCE
218     instance_ip_2 = instance_2.networks.get(NET_NAME)[0]
219     logger.debug("Instance '%s' got private ip '%s'." %
220                  (INSTANCE_NAME_2, instance_ip_2))
221
222     logger.info("Adding '%s' to security group '%s'..."
223                 % (INSTANCE_NAME_2, SECGROUP_NAME))
224     os_utils.add_secgroup_to_instance(nova_client, instance_2.id, sg_id)
225
226     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME_2)
227     floatip_dic = os_utils.create_floating_ip(neutron_client)
228     floatip_server = floatip_dic['fip_addr']
229     # floatip_id = floatip_dic['fip_id']
230
231     if floatip_server is None:
232         logger.error("Cannot create floating IP.")
233         sys.exit(-1)
234     logger.info("Floating IP created: '%s'" % floatip_server)
235
236     logger.info("Associating floating ip: '%s' to VM '%s' "
237                 % (floatip_server, INSTANCE_NAME_2))
238
239     if not os_utils.add_floating_ip(nova_client,
240                                     instance_2.id,
241                                     floatip_server):
242         logger.error("Cannot associate floating IP to VM.")
243         sys.exit(-1)
244
245     # CREATION OF THE 2 SF ####
246
247     tacker_script = "%s/testcases/features/sfc/%s" % \
248                     (FUNCTEST_REPO, TACKER_SCRIPT)
249     logger.info("Executing tacker script: '%s'" % tacker_script)
250     subprocess.call(tacker_script, shell=True)
251
252     # SSH CALL TO START HTTP SERVER
253     ssh = paramiko.SSHClient()
254     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
255
256     try:
257         ssh.connect(floatip_server, username="root",
258                     password="opnfv", timeout=2)
259         command = "python -m SimpleHTTPServer 80 > /dev/null 2>&1 &"
260         logger.info("Starting HTTP server")
261         (stdin, stdout, stderr) = ssh.exec_command(command)
262     except:
263         logger.debug("Waiting for %s..." % floatip_server)
264         time.sleep(6)
265         # timeout -= 1
266
267     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
268     ips = []
269     try:
270         for instance in instances:
271             if "server" not in instance.name:
272                 if "client" not in instance.name:
273                     logger.debug(
274                         "This is the instance name: %s " % instance.name)
275                     floatip_dic = os_utils.create_floating_ip(neutron_client)
276                     floatip = floatip_dic['fip_addr']
277                     ips.append(floatip)
278                     instance.add_floating_ip(floatip)
279     except:
280         logger.debug("Problems assigning floating IP to SFs")
281
282     # If no IPs were obtained, then we cant continue
283     if not ips:
284         logger.error('Failed to obtain IPs, cant continue, exiting')
285         return
286
287     logger.debug("Floating IPs for SFs: %s..." % ips)
288
289     # Check SSH connectivity to VNFs
290     r = 0
291     retries = 100
292     check = [False, False]
293
294     logger.info("Checking SSH connectivity to the SFs with ips %s" % str(ips))
295     while r < retries and not all(check):
296         try:
297             check = [check_ssh(ips[0]), check_ssh(ips[1])]
298         except Exception:
299             logger.exception("SSH check failed")
300             check = [False, False]
301         time.sleep(3)
302         r += 1
303
304     if not all(check):
305         logger.error("Cannot establish SSH connection to the SFs")
306         sys.exit(1)
307
308     logger.info("SSH connectivity to the SFs established")
309
310     # SSH TO START THE VXLAN_TOOL ON SF1
311     logger.info("Configuring the SFs")
312     try:
313         ssh.connect(ips[0], username="root",
314                     password="opnfv", timeout=2)
315         command = ("nohup python vxlan_tool.py -i eth0 "
316                    "-d forward -v off -b 80 > /dev/null 2>&1 &")
317         (stdin, stdout, stderr) = ssh.exec_command(command)
318     except:
319         logger.debug("Waiting for %s..." % ips[0])
320         time.sleep(6)
321         # timeout -= 1
322
323     try:
324         while 1:
325             (stdin, stdout, stderr) = ssh.exec_command(
326                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
327             if len(stdout.readlines()) > 0:
328                 logger.debug("HTTP firewall started")
329                 break
330             else:
331                 logger.debug("HTTP firewall not started")
332                 time.sleep(3)
333     except Exception:
334         logger.exception("vxlan_tool not started in SF1")
335
336     # SSH TO START THE VXLAN_TOOL ON SF2
337     try:
338         ssh.connect(ips[1], username="root",
339                     password="opnfv", timeout=2)
340         command = ("nohup python vxlan_tool.py -i eth0 "
341                    "-d forward -v off -b 22 > /dev/null 2>&1 &")
342         (stdin, stdout, stderr) = ssh.exec_command(command)
343     except:
344         logger.debug("Waiting for %s..." % ips[1])
345         time.sleep(6)
346         # timeout -= 1
347
348     try:
349         while 1:
350             (stdin, stdout, stderr) = ssh.exec_command(
351                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
352             if len(stdout.readlines()) > 0:
353                 logger.debug("SSH firewall started")
354                 break
355             else:
356                 logger.debug("SSH firewall not started")
357                 time.sleep(3)
358     except Exception:
359         logger.exception("vxlan_tool not started in SF2")
360
361     # SSH to modify the classification flows in compute
362
363     contr_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
364                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
365     logger.info("Executing script to modify the classi: '%s'" % contr_cmd3)
366     process = subprocess.Popen(contr_cmd3,
367                                shell=True,
368                                stdout=subprocess.PIPE)
369
370     i = 0
371
372     # SSH TO EXECUTE cmd_client
373     logger.info("TEST STARTED")
374     try:
375         ssh.connect(floatip_client, username="root",
376                     password="opnfv", timeout=2)
377         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
378         (stdin, stdout, stderr) = ssh.exec_command(command)
379
380         # WRITE THE CORRECT WAY TO DO LOGGING
381         if "timed out" in stdout.readlines()[0]:
382             logger.info('\033[92m' + "TEST 1 [PASSED] "
383                         "==> SSH BLOCKED" + '\033[0m')
384             i = i + 1
385             json_results.update({"Test 1: SSH Blocked": "Passed"})
386         else:
387             logger.error('\033[91m' + "TEST 1 [FAILED] "
388                          "==> SSH NOT BLOCKED" + '\033[0m')
389             status = "FAIL"
390             json_results.update({"Test 1: SSH Blocked": "Failed"})
391             failures += 1
392     except:
393         logger.debug("Waiting for %s..." % floatip_client)
394         time.sleep(6)
395         # timeout -= 1
396
397     # SSH TO EXECUTE cmd_client
398     try:
399         ssh.connect(floatip_client, username="root",
400                     password="opnfv", timeout=2)
401         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
402         (stdin, stdout, stderr) = ssh.exec_command(command)
403
404         if "succeeded" in stdout.readlines()[0]:
405             logger.info('\033[92m' + "TEST 2 [PASSED] "
406                         "==> HTTP WORKS" + '\033[0m')
407             i = i + 1
408             json_results.update({"Test 2: HTTP works": "Passed"})
409         else:
410             logger.error('\033[91m' + "TEST 2 [FAILED] "
411                          "==> HTTP BLOCKED" + '\033[0m')
412             status = "FAIL"
413             json_results.update({"Test 2: HTTP works": "Failed"})
414             failures += 1
415     except:
416         logger.debug("Waiting for %s..." % floatip_client)
417         time.sleep(6)
418         # timeout -= 1
419
420     # CHANGE OF CLASSIFICATION #
421     logger.info("Changing the classification")
422     tacker_classi = "%s/testcases/features/sfc/%s" % \
423                     (FUNCTEST_REPO, TACKER_CHANGECLASSI)
424     subprocess.call(tacker_classi, shell=True)
425
426     logger.info("Wait for ODL to update the classification rules in OVS")
427     time.sleep(10)
428
429     # SSH to modify the classification flows in compute
430
431     contr_cmd4 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
432                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
433     logger.info("Executing script to modify the classi: '%s'" % contr_cmd4)
434     process = subprocess.Popen(contr_cmd4,
435                                shell=True,
436                                stdout=subprocess.PIPE)
437
438     # SSH TO EXECUTE cmd_client
439
440     try:
441         ssh.connect(floatip_client, username="root",
442                     password="opnfv", timeout=2)
443         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
444         (stdin, stdout, stderr) = ssh.exec_command(command)
445
446         if "timed out" in stdout.readlines()[0]:
447             logger.info('\033[92m' + "TEST 3 [PASSED] "
448                         "==> HTTP BLOCKED" + '\033[0m')
449             i = i + 1
450             json_results.update({"Test 3: HTTP Blocked": "Passed"})
451         else:
452             logger.error('\033[91m' + "TEST 3 [FAILED] "
453                          "==> HTTP NOT BLOCKED" + '\033[0m')
454             status = "FAIL"
455             json_results.update({"Test 3: HTTP Blocked": "Failed"})
456             failures += 1
457     except:
458         logger.debug("Waiting for %s..." % floatip_client)
459         time.sleep(6)
460         # timeout -= 1
461
462     # SSH TO EXECUTE cmd_client
463     try:
464         ssh.connect(floatip_client, username="root",
465                     password="opnfv", timeout=2)
466         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
467         (stdin, stdout, stderr) = ssh.exec_command(command)
468
469         if "succeeded" in stdout.readlines()[0]:
470             logger.info('\033[92m' + "TEST 4 [PASSED] "
471                         "==> SSH WORKS" + '\033[0m')
472             i = i + 1
473             json_results.update({"Test 4: SSH works": "Passed"})
474         else:
475             logger.error('\033[91m' + "TEST 4 [FAILED] "
476                          "==> SSH BLOCKED" + '\033[0m')
477             status = "FAIL"
478             json_results.update({"Test 4: SSH works": "Failed"})
479             failures += 1
480     except:
481         logger.debug("Waiting for %s..." % floatip_client)
482         time.sleep(6)
483         # timeout -= 1
484
485     if i == 4:
486         for x in range(0, 5):
487             logger.info('\033[92m' + "SFC TEST WORKED"
488                         " :) \n" + '\033[0m')
489
490     if args.report:
491         stop_time = time.time()
492         json_results.update({"tests": "4", "failures": int(failures)})
493         logger.debug("Promise Results json: " + str(json_results))
494         ft_utils.push_results_to_db("sfc",
495                                     "functest-odl-sfc",
496                                     start_time,
497                                     stop_time,
498                                     status,
499                                     json_results)
500     if status == "PASS":
501         sys.exit(0)
502     else:
503         sys.exit(1)
504
505 if __name__ == '__main__':
506     main()