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