Merge "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     iptable_cmd1 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
86                     " ssh " + ip_server + " iptables -P INPUT ACCEPT ")
87     iptable_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
88                     " ssh " + ip_server + " iptables -t nat -P INPUT ACCEPT ")
89     iptable_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
90                     " ssh " + ssh_options + " " + ip_server +
91                     " iptables -A INPUT -m state"
92                     " --state NEW,ESTABLISHED,RELATED -j ACCEPT")
93
94     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd1)
95     subprocess.call(iptable_cmd1, shell=True, stderr=subprocess.PIPE)
96
97     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd2)
98     subprocess.call(iptable_cmd2, shell=True, stderr=subprocess.PIPE)
99
100     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd3)
101     subprocess.call(iptable_cmd3, shell=True, stderr=subprocess.PIPE)
102
103 # Getting the different clients
104
105     nova_client = os_utils.get_nova_client()
106     neutron_client = os_utils.get_neutron_client()
107     glance_client = os_utils.get_glance_client()
108
109 # Download the image
110
111     if not os.path.isfile(IMAGE_PATH):
112         logger.info("Downloading image")
113         ft_utils.download_url(
114             "http://artifacts.opnfv.org/sfc/demo/sf_nsh_colorado.qcow2",
115             "/home/opnfv/functest/data/")
116     else:
117         logger.info("Using old image")
118
119 # Create glance image and the neutron network
120
121     image_id = os_utils.create_glance_image(glance_client,
122                                             IMAGE_NAME,
123                                             IMAGE_PATH,
124                                             disk=IMAGE_FORMAT,
125                                             container="bare",
126                                             public=True)
127
128     network_dic = os_utils.create_network_full(neutron_client,
129                                                NET_NAME,
130                                                SUBNET_NAME,
131                                                ROUTER_NAME,
132                                                SUBNET_CIDR)
133     if not network_dic:
134         logger.error(
135             "There has been a problem when creating the neutron network")
136         sys.exit(-1)
137
138     network_id = network_dic["net_id"]
139
140     sg_id = os_utils.create_security_group_full(neutron_client,
141                                                 SECGROUP_NAME, SECGROUP_DESCR)
142
143     secgroups = os_utils.get_security_groups(neutron_client)
144
145     for sg in secgroups:
146         os_utils.create_secgroup_rule(neutron_client, sg['id'],
147                                       'ingress', 'tcp',
148                                       port_range_min=22,
149                                       port_range_max=22)
150         os_utils.create_secgroup_rule(neutron_client, sg['id'],
151                                       'egress', 'tcp',
152                                       port_range_min=22,
153                                       port_range_max=22)
154         os_utils.create_secgroup_rule(neutron_client, sg['id'],
155                                       'ingress', 'tcp',
156                                       port_range_min=80,
157                                       port_range_max=80)
158         os_utils.create_secgroup_rule(neutron_client, sg['id'],
159                                       'egress', 'tcp',
160                                       port_range_min=80,
161                                       port_range_max=80)
162
163     _, custom_flv_id = os_utils.get_or_create_flavor(
164         'custom', 1500, 10, 1, public=True)
165     if not custom_flv_id:
166         logger.error("Failed to create custom flavor")
167         sys.exit(1)
168
169     # boot INSTANCE
170     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
171     logger.debug(
172         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
173         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
174     instance = os_utils.create_instance_and_wait_for_active(FLAVOR,
175                                                             image_id,
176                                                             network_id,
177                                                             INSTANCE_NAME,
178                                                             av_zone='nova')
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_2, 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                                                               av_zone='nova')
220
221     if instance_2 is None:
222         logger.error("Error while booting instance.")
223         sys.exit(-1)
224     # Retrieve IP of INSTANCE
225     instance_ip_2 = instance_2.networks.get(NET_NAME)[0]
226     logger.debug("Instance '%s' got private ip '%s'." %
227                  (INSTANCE_NAME_2, instance_ip_2))
228
229     logger.info("Adding '%s' to security group '%s'..."
230                 % (INSTANCE_NAME_2, SECGROUP_NAME))
231     os_utils.add_secgroup_to_instance(nova_client, instance_2.id, sg_id)
232
233     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME_2)
234     floatip_dic = os_utils.create_floating_ip(neutron_client)
235     floatip_server = floatip_dic['fip_addr']
236     # floatip_id = floatip_dic['fip_id']
237
238     if floatip_server is None:
239         logger.error("Cannot create floating IP.")
240         sys.exit(-1)
241     logger.info("Floating IP created: '%s'" % floatip_server)
242
243     logger.info("Associating floating ip: '%s' to VM '%s' "
244                 % (floatip_server, INSTANCE_NAME_2))
245
246     if not os_utils.add_floating_ip(nova_client,
247                                     instance_2.id,
248                                     floatip_server):
249         logger.error("Cannot associate floating IP to VM.")
250         sys.exit(-1)
251
252     # CREATION OF THE 2 SF ####
253
254     tacker_script = "%s/testcases/features/sfc/%s" % \
255                     (FUNCTEST_REPO, TACKER_SCRIPT)
256     logger.info("Executing tacker script: '%s'" % tacker_script)
257     subprocess.call(tacker_script, shell=True)
258
259     # SSH CALL TO START HTTP SERVER
260     ssh = paramiko.SSHClient()
261     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
262
263     try:
264         ssh.connect(floatip_server, username="root",
265                     password="opnfv", timeout=2)
266         command = "python -m SimpleHTTPServer 80 > /dev/null 2>&1 &"
267         logger.info("Starting HTTP server")
268         (stdin, stdout, stderr) = ssh.exec_command(command)
269     except:
270         logger.debug("Waiting for %s..." % floatip_server)
271         time.sleep(6)
272         # timeout -= 1
273
274     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
275     ips = []
276     try:
277         for instance in instances:
278             if "server" not in instance.name:
279                 if "client" not in instance.name:
280                     logger.debug(
281                         "This is the instance name: %s " % instance.name)
282                     floatip_dic = os_utils.create_floating_ip(neutron_client)
283                     floatip = floatip_dic['fip_addr']
284                     ips.append(floatip)
285                     instance.add_floating_ip(floatip)
286     except:
287         logger.debug("Problems assigning floating IP to SFs")
288
289     # If no IPs were obtained, then we cant continue
290     if not ips:
291         logger.error('Failed to obtain IPs, cant continue, exiting')
292         return
293
294     logger.debug("Floating IPs for SFs: %s..." % ips)
295
296     # Check SSH connectivity to VNFs
297     r = 0
298     retries = 100
299     check = [False, False]
300
301     logger.info("Checking SSH connectivity to the SFs with ips %s" % str(ips))
302     while r < retries and not all(check):
303         try:
304             check = [check_ssh(ips[0]), check_ssh(ips[1])]
305         except Exception:
306             logger.exception("SSH check failed")
307             check = [False, False]
308         time.sleep(3)
309         r += 1
310
311     if not all(check):
312         logger.error("Cannot establish SSH connection to the SFs")
313         sys.exit(1)
314
315     logger.info("SSH connectivity to the SFs established")
316
317     # SSH TO START THE VXLAN_TOOL ON SF1
318     logger.info("Configuring the SFs")
319     try:
320         ssh.connect(ips[0], username="root",
321                     password="opnfv", timeout=2)
322         command = ("nohup python vxlan_tool.py -i eth0 "
323                    "-d forward -v off -b 80 > /dev/null 2>&1 &")
324         (stdin, stdout, stderr) = ssh.exec_command(command)
325     except:
326         logger.debug("Waiting for %s..." % ips[0])
327         time.sleep(6)
328         # timeout -= 1
329
330     try:
331         while 1:
332             (stdin, stdout, stderr) = ssh.exec_command(
333                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
334             if len(stdout.readlines()) > 0:
335                 logger.debug("HTTP firewall started")
336                 break
337             else:
338                 logger.debug("HTTP firewall not started")
339                 time.sleep(3)
340     except Exception:
341         logger.exception("vxlan_tool not started in SF1")
342
343     # SSH TO START THE VXLAN_TOOL ON SF2
344     try:
345         ssh.connect(ips[1], username="root",
346                     password="opnfv", timeout=2)
347         command = ("nohup python vxlan_tool.py -i eth0 "
348                    "-d forward -v off -b 22 > /dev/null 2>&1 &")
349         (stdin, stdout, stderr) = ssh.exec_command(command)
350     except:
351         logger.debug("Waiting for %s..." % ips[1])
352         time.sleep(6)
353         # timeout -= 1
354
355     try:
356         while 1:
357             (stdin, stdout, stderr) = ssh.exec_command(
358                 "ps aux | grep \"vxlan_tool.py\" | grep -v grep")
359             if len(stdout.readlines()) > 0:
360                 logger.debug("SSH firewall started")
361                 break
362             else:
363                 logger.debug("SSH firewall not started")
364                 time.sleep(3)
365     except Exception:
366         logger.exception("vxlan_tool not started in SF2")
367
368     i = 0
369
370     # SSH TO EXECUTE cmd_client
371     logger.info("TEST STARTED")
372     try:
373         ssh.connect(floatip_client, username="root",
374                     password="opnfv", timeout=2)
375         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
376         (stdin, stdout, stderr) = ssh.exec_command(command)
377
378         # WRITE THE CORRECT WAY TO DO LOGGING
379         if "timed out" in stdout.readlines()[0]:
380             logger.info('\033[92m' + "TEST 1 [PASSED] "
381                         "==> SSH BLOCKED" + '\033[0m')
382             i = i + 1
383             json_results.update({"Test 1: SSH Blocked": "Passed"})
384         else:
385             logger.error('\033[91m' + "TEST 1 [FAILED] "
386                          "==> SSH NOT BLOCKED" + '\033[0m')
387             status = "FAIL"
388             json_results.update({"Test 1: SSH Blocked": "Failed"})
389             failures += 1
390     except:
391         logger.debug("Waiting for %s..." % floatip_client)
392         time.sleep(6)
393         # timeout -= 1
394
395     # SSH TO EXECUTE cmd_client
396     try:
397         ssh.connect(floatip_client, username="root",
398                     password="opnfv", timeout=2)
399         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
400         (stdin, stdout, stderr) = ssh.exec_command(command)
401
402         if "succeeded" in stdout.readlines()[0]:
403             logger.info('\033[92m' + "TEST 2 [PASSED] "
404                         "==> HTTP WORKS" + '\033[0m')
405             i = i + 1
406             json_results.update({"Test 2: HTTP works": "Passed"})
407         else:
408             logger.error('\033[91m' + "TEST 2 [FAILED] "
409                          "==> HTTP BLOCKED" + '\033[0m')
410             status = "FAIL"
411             json_results.update({"Test 2: HTTP works": "Failed"})
412             failures += 1
413     except:
414         logger.debug("Waiting for %s..." % floatip_client)
415         time.sleep(6)
416         # timeout -= 1
417
418     # CHANGE OF CLASSIFICATION #
419     logger.info("Changing the classification")
420     tacker_classi = "%s/testcases/features/sfc/%s" % \
421                     (FUNCTEST_REPO, TACKER_CHANGECLASSI)
422     subprocess.call(tacker_classi, shell=True)
423
424     logger.info("Wait for ODL to update the classification rules in OVS")
425     time.sleep(100)
426
427     # SSH TO EXECUTE cmd_client
428
429     try:
430         ssh.connect(floatip_client, username="root",
431                     password="opnfv", timeout=2)
432         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
433         (stdin, stdout, stderr) = ssh.exec_command(command)
434
435         if "timed out" in stdout.readlines()[0]:
436             logger.info('\033[92m' + "TEST 3 [PASSED] "
437                         "==> HTTP BLOCKED" + '\033[0m')
438             i = i + 1
439             json_results.update({"Test 3: HTTP Blocked": "Passed"})
440         else:
441             logger.error('\033[91m' + "TEST 3 [FAILED] "
442                          "==> HTTP NOT BLOCKED" + '\033[0m')
443             status = "FAIL"
444             json_results.update({"Test 3: HTTP Blocked": "Failed"})
445             failures += 1
446     except:
447         logger.debug("Waiting for %s..." % floatip_client)
448         time.sleep(6)
449         # timeout -= 1
450
451     # SSH TO EXECUTE cmd_client
452     try:
453         ssh.connect(floatip_client, username="root",
454                     password="opnfv", timeout=2)
455         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
456         (stdin, stdout, stderr) = ssh.exec_command(command)
457
458         if "succeeded" in stdout.readlines()[0]:
459             logger.info('\033[92m' + "TEST 4 [PASSED] "
460                         "==> SSH WORKS" + '\033[0m')
461             i = i + 1
462             json_results.update({"Test 4: SSH works": "Passed"})
463         else:
464             logger.error('\033[91m' + "TEST 4 [FAILED] "
465                          "==> SSH BLOCKED" + '\033[0m')
466             status = "FAIL"
467             json_results.update({"Test 4: SSH works": "Failed"})
468             failures += 1
469     except:
470         logger.debug("Waiting for %s..." % floatip_client)
471         time.sleep(6)
472         # timeout -= 1
473
474     if i == 4:
475         for x in range(0, 5):
476             logger.info('\033[92m' + "SFC TEST WORKED"
477                         " :) \n" + '\033[0m')
478
479     if args.report:
480         stop_time = time.time()
481         json_results.update({"tests": "4", "failures": int(failures)})
482         logger.debug("Promise Results json: " + str(json_results))
483         ft_utils.push_results_to_db("sfc",
484                                     "functest-odl-sfc",
485                                     start_time,
486                                     stop_time,
487                                     status,
488                                     json_results)
489     if status == "PASS":
490         sys.exit(0)
491     else:
492         sys.exit(1)
493
494 if __name__ == '__main__':
495     main()