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