0073cc92cd7f939c44f92cba8502f8f2261fcd7c
[functest.git] / testcases / 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 paramiko
10
11
12 parser = argparse.ArgumentParser()
13
14 parser.add_argument("-r", "--report",
15                     help="Create json result file",
16                     action="store_true")
17
18 args = parser.parse_args()
19
20 """ logging configuration """
21 logger = ft_logger.Logger("ODL_SFC").getLogger()
22
23 REPO_PATH = os.environ['repos_dir'] + '/functest/'
24 HOME = os.environ['HOME'] + "/"
25
26 VM_BOOT_TIMEOUT = 180
27 INSTANCE_NAME = "client"
28 FLAVOR = "m1.small"
29 IMAGE_NAME = "sf_nsh_colorado"
30 IMAGE_FILENAME = "sf_nsh_colorado.qcow2"
31 IMAGE_FORMAT = "qcow2"
32 IMAGE_PATH = "/home/opnfv/functest/data" + "/" + IMAGE_FILENAME
33
34 # NEUTRON Private Network parameters
35
36 NET_NAME = "example-net"
37 SUBNET_NAME = "example-subnet"
38 SUBNET_CIDR = "11.0.0.0/24"
39 ROUTER_NAME = "example-router"
40
41 SECGROUP_NAME = "example-sg"
42 SECGROUP_DESCR = "Example Security group"
43
44 INSTANCE_NAME_2 = "server"
45
46 # TEST_DB = ft_utils.get_parameter_from_yaml("results.test_db_url")
47
48 PRE_SETUP_SCRIPT = 'sfc_pre_setup.bash'
49 TACKER_SCRIPT = 'sfc_tacker.bash'
50 TEARDOWN_SCRIPT = "sfc_teardown.bash"
51 TACKER_CHANGECLASSI = "sfc_change_classi.bash"
52
53
54 def main():
55
56     # Allow any port so that tacker commands reaches the server.
57     # This will be deleted when tacker is included in OPNFV installation
58
59     ssh_options = '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
60     contr_cmd = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
61                  " 'fuel node'|grep controller|awk '{print $10}'")
62     logger.info("Executing script to get ip_server: '%s'" % contr_cmd)
63     process = subprocess.Popen(contr_cmd,
64                                shell=True,
65                                stdout=subprocess.PIPE)
66     ip_server = process.stdout.readline().rstrip()
67
68     contr_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
69                   " 'fuel node'|grep compute|awk '{print $10}'")
70     logger.info("Executing script to get ip_compute: '%s'" % contr_cmd2)
71     process = subprocess.Popen(contr_cmd2,
72                                shell=True,
73                                stdout=subprocess.PIPE)
74     ip_compute = process.stdout.readline().rstrip()
75
76     iptable_cmd1 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
77                     " ssh " + ip_server + " iptables -P INPUT ACCEPT ")
78     iptable_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
79                     " ssh " + ip_server + " iptables -t nat -P INPUT ACCEPT ")
80
81     subprocess.call(iptable_cmd1, shell=True)
82     subprocess.call(iptable_cmd2, shell=True)
83
84 # Getting the different clients
85
86     nova_client = os_utils.get_nova_client()
87     neutron_client = os_utils.get_neutron_client()
88     glance_client = os_utils.get_glance_client()
89
90 # Download the image
91
92     if not os.path.isfile(IMAGE_PATH):
93         logger.info("Downloading image")
94         ft_utils.download_url(
95             "http://artifacts.opnfv.org/sfc/demo/sf_nsh_colorado.qcow2",
96             "/home/opnfv/functest/data/")
97     else:
98         logger.info("Using old image")
99
100 # Create glance image and the neutron network
101
102     image_id = os_utils.create_glance_image(glance_client,
103                                             IMAGE_NAME,
104                                             IMAGE_PATH,
105                                             disk=IMAGE_FORMAT,
106                                             container="bare",
107                                             public=True)
108
109     network_dic = os_utils.create_network_full(neutron_client,
110                                                NET_NAME,
111                                                SUBNET_NAME,
112                                                ROUTER_NAME,
113                                                SUBNET_CIDR)
114     if not network_dic:
115         logger.error(
116             "There has been a problem when creating the neutron network")
117         sys.exit(-1)
118
119     network_id = network_dic["net_id"]
120
121     sg_id = os_utils.create_security_group_full(neutron_client,
122                                                 SECGROUP_NAME, SECGROUP_DESCR)
123
124     # boot INTANCE
125     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
126     logger.debug(
127         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
128         "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
129     instance = os_utils.create_instance_and_wait_for_active(FLAVOR,
130                                                             image_id,
131                                                             network_id,
132                                                             INSTANCE_NAME)
133
134     if instance is None:
135         logger.error("Error while booting instance.")
136         sys.exit(-1)
137     # Retrieve IP of INSTANCE
138     instance_ip = instance.networks.get(NET_NAME)[0]
139     logger.debug("Instance '%s' got private ip '%s'." %
140                  (INSTANCE_NAME, instance_ip))
141
142     logger.info("Adding '%s' to security group '%s'..."
143                 % (INSTANCE_NAME, SECGROUP_NAME))
144     os_utils.add_secgroup_to_instance(nova_client, instance.id, sg_id)
145
146     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME)
147     floatip_dic = os_utils.create_floating_ip(neutron_client)
148     floatip_client = floatip_dic['fip_addr']
149     # floatip_id = floatip_dic['fip_id']
150
151     if floatip_client is None:
152         logger.error("Cannot create floating IP.")
153         sys.exit(-1)
154     logger.info("Floating IP created: '%s'" % floatip_client)
155
156     logger.info("Associating floating ip: '%s' to VM '%s' "
157                 % (floatip_client, INSTANCE_NAME))
158     if not os_utils.add_floating_ip(nova_client, instance.id, floatip_client):
159         logger.error("Cannot associate floating IP to VM.")
160         sys.exit(-1)
161
162 # STARTING SECOND VM (server) ###
163
164     # boot INTANCE
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_2 = os_utils.create_instance_and_wait_for_active(FLAVOR,
170                                                               image_id,
171                                                               network_id,
172                                                               INSTANCE_NAME_2)
173
174     if instance_2 is None:
175         logger.error("Error while booting instance.")
176         sys.exit(-1)
177     # Retrieve IP of INSTANCE
178     instance_ip_2 = instance_2.networks.get(NET_NAME)[0]
179     logger.debug("Instance '%s' got private ip '%s'." %
180                  (INSTANCE_NAME_2, instance_ip_2))
181
182     logger.info("Adding '%s' to security group '%s'..."
183                 % (INSTANCE_NAME_2, SECGROUP_NAME))
184     os_utils.add_secgroup_to_instance(nova_client, instance_2.id, sg_id)
185
186     logger.info("Creating floating IP for VM '%s'..." % INSTANCE_NAME_2)
187     floatip_dic = os_utils.create_floating_ip(neutron_client)
188     floatip_server = floatip_dic['fip_addr']
189     # floatip_id = floatip_dic['fip_id']
190
191     if floatip_server is None:
192         logger.error("Cannot create floating IP.")
193         sys.exit(-1)
194     logger.info("Floating IP created: '%s'" % floatip_server)
195
196     logger.info("Associating floating ip: '%s' to VM '%s' "
197                 % (floatip_server, INSTANCE_NAME_2))
198
199     if not os_utils.add_floating_ip(nova_client,
200                                     instance_2.id,
201                                     floatip_server):
202         logger.error("Cannot associate floating IP to VM.")
203         sys.exit(-1)
204
205     # CREATION OF THE 2 SF ####
206
207     tacker_script = "/home/opnfv/repos/functest/testcases/features/sfc/" + \
208         TACKER_SCRIPT
209     logger.info("Executing tacker script: '%s'" % tacker_script)
210     subprocess.call(tacker_script, shell=True)
211
212     # SSH CALL TO START HTTP SERVER
213     ssh = paramiko.SSHClient()
214     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
215
216     try:
217         ssh.connect(floatip_server, username="root",
218                     password="opnfv", timeout=2)
219         command = "python -m SimpleHTTPServer 80 > /dev/null 2>&1 &"
220         logger.info("Starting HTTP server")
221         (stdin, stdout, stderr) = ssh.exec_command(command)
222     except:
223         logger.debug("Waiting for %s..." % floatip_server)
224         time.sleep(6)
225         # timeout -= 1
226
227     instances = nova_client.servers.list(search_opts={'all_tenants': 1})
228     ips = []
229     try:
230         for instance in instances:
231             if "server" not in instance.name:
232                 if "client" not in instance.name:
233                     logger.debug(
234                         "This is the instance name: %s " % instance.name)
235                     floatip_dic = os_utils.create_floating_ip(neutron_client)
236                     floatip = floatip_dic['fip_addr']
237                     ips.append(floatip)
238                     instance.add_floating_ip(floatip)
239     except:
240         logger.debug("Problems assigning floating IP to SFs")
241
242     logger.debug("Floating IPs for SFs: %s..." % ips)
243
244     # SSH TO START THE VXLAN_TOOL ON SF1
245     logger.info("Configuring the SFs")
246     try:
247         ssh.connect(ips[0], username="root",
248                     password="opnfv", timeout=2)
249         command = ("nohup python vxlan_tool.py -i eth0 "
250                    "-d forward -v off -f -b 80 &")
251         (stdin, stdout, stderr) = ssh.exec_command(command)
252     except:
253         logger.debug("Waiting for %s..." % ips[0])
254         time.sleep(6)
255         # timeout -= 1
256
257     try:
258         while 1:
259             (stdin, stdout, stderr) = ssh.exec_command("ps lax | grep python")
260             if "vxlan_tool.py" in stdout.readlines()[0]:
261                 logger.debug("HTTP firewall started")
262                 break
263             else:
264                 logger.debug("HTTP firewall not started")
265                 time.sleep(3)
266     except:
267         logger.error("vxlan_tool not started in SF1")
268
269     # SSH TO START THE VXLAN_TOOL ON SF2
270     try:
271         ssh.connect(ips[1], username="root",
272                     password="opnfv", timeout=2)
273         command = ("nohup python vxlan_tool.py -i eth0 "
274                    "-d forward -v off -f -b 22 &")
275         (stdin, stdout, stderr) = ssh.exec_command(command)
276     except:
277         logger.debug("Waiting for %s..." % ips[1])
278         time.sleep(6)
279         # timeout -= 1
280
281     try:
282         while 1:
283             (stdin, stdout, stderr) = ssh.exec_command("ps lax | grep python")
284             if "vxlan_tool.py" in stdout.readlines()[0]:
285                 logger.debug("SSH firewall started")
286                 break
287             else:
288                 logger.debug("SSH firewall not started")
289                 time.sleep(3)
290     except:
291         logger.error("vxlan_tool not started in SF2")
292
293     # SSH to modify the classification flows in compute
294
295     contr_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
296                   " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
297     logger.info("Executing script to modify the classi: '%s'" % contr_cmd3)
298     process = subprocess.Popen(contr_cmd3,
299                                shell=True,
300                                stdout=subprocess.PIPE)
301
302     # SSH TO EXECUTE cmd_client
303
304     logger.info("TEST STARTED")
305     try:
306         ssh.connect(floatip_client, username="root",
307                     password="opnfv", timeout=2)
308         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
309         (stdin, stdout, stderr) = ssh.exec_command(command)
310     except:
311         logger.debug("Waiting for %s..." % floatip_client)
312         time.sleep(6)
313         # timeout -= 1
314
315     # WRITE THE CORRECT WAY TO DO LOGGING
316     i = 0
317     if "timed out" in stdout.readlines()[0]:
318         logger.info('\033[92m' + "TEST 1 [PASSED] "
319                     "==> SSH BLOCKED" + '\033[0m')
320         i = i + 1
321     else:
322         logger.error('\033[91m' + "TEST 1 [FAILED] "
323                      "==> SSH NOT BLOCKED" + '\033[0m')
324         return
325
326     # SSH TO EXECUTE cmd_client
327
328     try:
329         ssh.connect(floatip_client, username="root",
330                     password="opnfv", timeout=2)
331         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
332         (stdin, stdout, stderr) = ssh.exec_command(command)
333     except:
334         logger.debug("Waiting for %s..." % floatip_client)
335         time.sleep(6)
336         # timeout -= 1
337
338     if "succeeded" in stdout.readlines()[0]:
339         logger.info('\033[92m' + "TEST 2 [PASSED] "
340                     "==> HTTP WORKS" + '\033[0m')
341         i = i + 1
342     else:
343         logger.error('\033[91m' + "TEST 2 [FAILED] "
344                      "==> HTTP BLOCKED" + '\033[0m')
345         return
346
347     # CHANGE OF CLASSIFICATION #
348     logger.info("Changing the classification")
349     tacker_classi = "/home/opnfv/repos/functest/testcases/features/sfc/" + \
350         TACKER_CHANGECLASSI
351     subprocess.call(tacker_classi, shell=True)
352
353     # SSH TO EXECUTE cmd_client
354
355     try:
356         ssh.connect(floatip_client, username="root",
357                     password="opnfv", timeout=2)
358         command = "nc -w 5 -zv " + instance_ip_2 + " 80 2>&1"
359         (stdin, stdout, stderr) = ssh.exec_command(command)
360     except:
361         logger.debug("Waiting for %s..." % floatip_client)
362         time.sleep(6)
363         # timeout -= 1
364
365     if "timed out" in stdout.readlines()[0]:
366         logger.info('\033[92m' + "TEST 3 [WORKS] "
367                     "==> HTTP BLOCKED" + '\033[0m')
368         i = i + 1
369     else:
370         logger.error('\033[91m' + "TEST 3 [FAILED] "
371                      "==> HTTP NOT BLOCKED" + '\033[0m')
372         return
373
374     # SSH TO EXECUTE cmd_client
375
376     try:
377         ssh.connect(floatip_client, username="root",
378                     password="opnfv", timeout=2)
379         command = "nc -w 5 -zv " + instance_ip_2 + " 22 2>&1"
380         (stdin, stdout, stderr) = ssh.exec_command(command)
381     except:
382         logger.debug("Waiting for %s..." % floatip_client)
383         time.sleep(6)
384         # timeout -= 1
385
386     if "succeeded" in stdout.readlines()[0]:
387         logger.info('\033[92m' + "TEST 4 [WORKS] "
388                     "==> SSH WORKS" + '\033[0m')
389         i = i + 1
390     else:
391         logger.error('\033[91m' + "TEST 4 [FAILED] "
392                      "==> SSH BLOCKED" + '\033[0m')
393         return
394
395     if i == 4:
396         for x in range(0, 5):
397             logger.info('\033[92m' + "SFC TEST WORKED"
398                         " :) \n" + '\033[0m')
399
400     sys.exit(0)
401
402 if __name__ == '__main__':
403     main()