stop hardcoded FUNCTEST_REPO path everywhere
[functest.git] / testcases / Controllers / ONOS / Teston / onosfunctest.py
1 """
2 Description: This test is to run onos Teston VTN scripts
3
4 List of test cases:
5 CASE1 - Northbound NBI test network/subnet/ports
6 CASE2 - Ovsdb test&Default configuration&Vm go online
7
8 lanqinglong@huawei.com
9 #
10 # All rights reserved. This program and the accompanying materials
11 # are made available under the terms of the Apache License, Version 2.0
12 # which accompanies this distribution, and is available at
13 # http://www.apache.org/licenses/LICENSE-2.0
14 #
15 """
16
17 import datetime
18 import os
19 import re
20 import time
21
22 import argparse
23 import functest.utils.functest_logger as ft_logger
24 import functest.utils.functest_utils as functest_utils
25 import functest.utils.openstack_utils as openstack_utils
26 from functest.utils.functest_utils import FUNCTEST_REPO as REPO_PATH
27 from neutronclient.v2_0 import client as neutronclient
28
29 parser = argparse.ArgumentParser()
30 parser.add_argument("-t", "--testcase", help="Testcase name")
31 args = parser.parse_args()
32
33
34 """ logging configuration """
35 logger = ft_logger.Logger("onos").getLogger()
36
37 # onos parameters
38 TEST_DB = functest_utils.get_parameter_from_yaml(
39     "results.test_db_url")
40 ONOS_REPO_PATH = functest_utils.get_parameter_from_yaml(
41     "general.directories.dir_repos")
42 ONOS_CONF_DIR = functest_utils.get_parameter_from_yaml(
43     "general.directories.dir_functest_conf")
44
45 ONOSCI_PATH = ONOS_REPO_PATH + "/"
46 starttime = datetime.datetime.now()
47
48 HOME = os.environ['HOME'] + "/"
49 INSTALLER_TYPE = os.environ['INSTALLER_TYPE']
50 DEPLOY_SCENARIO = os.environ['DEPLOY_SCENARIO']
51 ONOSCI_PATH = ONOS_REPO_PATH + "/"
52 GLANCE_IMAGE_NAME = functest_utils.get_parameter_from_yaml(
53     "onos_sfc.image_name")
54 GLANCE_IMAGE_FILENAME = functest_utils.get_parameter_from_yaml(
55     "onos_sfc.image_file_name")
56 GLANCE_IMAGE_PATH = functest_utils.get_parameter_from_yaml(
57     "general.directories.dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
58 SFC_PATH = REPO_PATH + "/" + functest_utils.get_parameter_from_yaml(
59     "general.directories.dir_onos_sfc")
60
61
62 def RunScript(testname):
63     """
64     Run ONOS Test Script
65     Parameters:
66     testname: ONOS Testcase Name
67     """
68     runtest = ONOSCI_PATH + "onos/TestON/bin/cli.py run " + testname
69     logger.debug("Run script " + testname)
70     os.system(runtest)
71
72
73 def DownloadCodes(url="https://github.com/wuwenbin2/OnosSystemTest.git"):
74     """
75     Download Onos Teston codes
76     Parameters:
77     url: github url
78     """
79     downloadcode = "git clone " + url + " " + ONOSCI_PATH + "OnosSystemTest"
80     logger.debug("Download Onos Teston codes " + url)
81     os.system(downloadcode)
82
83
84 def GetResult():
85     LOGPATH = ONOSCI_PATH + "onos/TestON/logs"
86     cmd = "grep -rnh " + "Fail" + " " + LOGPATH
87     Resultbuffer = os.popen(cmd).read()
88     # duration = datetime.datetime.now() - starttime
89     time.sleep(2)
90
91     if re.search("\s+[1-9]+\s+", Resultbuffer):
92         logger.debug("Testcase Fails\n" + Resultbuffer)
93         # Result = "Failed"
94     else:
95         logger.debug("Testcases Success")
96         # Result = "Success"
97     # payload={'timestart': str(starttime),
98     #          'duration': str(duration),
99     #            'status': Result}
100     cmd = "grep -rnh 'Execution Time' " + LOGPATH
101     Resultbuffer = os.popen(cmd).read()
102     time1 = Resultbuffer[114:128]
103     time2 = Resultbuffer[28:42]
104     cmd = "grep -rnh 'Success Percentage' " + LOGPATH + "/FUNCvirNetNB_*"
105     Resultbuffer = os.popen(cmd).read()
106     if Resultbuffer.find('100%') >= 0:
107         result1 = 'Success'
108     else:
109         result1 = 'Failed'
110     cmd = "grep -rnh 'Success Percentage' " + LOGPATH + "/FUNCvirNetNBL3*"
111     Resultbuffer = os.popen(cmd).read()
112     if Resultbuffer.find('100%') >= 0:
113         result2 = 'Success'
114     else:
115         result2 = 'Failed'
116     status1 = []
117     status2 = []
118     cmd = "grep -rnh 'h3' " + LOGPATH + "/FUNCvirNetNB_*"
119     Resultbuffer = os.popen(cmd).read()
120     pattern = re.compile("<h3>([^-]+) - ([^-]+) - (\S*)</h3>")
121     # res = pattern.search(Resultbuffer).groups()
122     res = pattern.findall(Resultbuffer)
123     i = 0
124     for index in range(len(res)):
125         status1.append({'Case name:': res[i][0] + res[i][1],
126                         'Case result': res[i][2]})
127         i = i + 1
128     cmd = "grep -rnh 'h3' " + LOGPATH + "/FUNCvirNetNBL3*"
129     Resultbuffer = os.popen(cmd).read()
130     pattern = re.compile("<h3>([^-]+) - ([^-]+) - (\S*)</h3>")
131     # res = pattern.search(Resultbuffer).groups()
132     res = pattern.findall(Resultbuffer)
133     i = 0
134     for index in range(len(res)):
135         status2.append({'Case name:': res[i][0] + res[i][1],
136                         'Case result': res[i][2]})
137         i = i + 1
138     payload = {'timestart': str(starttime),
139                'FUNCvirNet': {'duration': time1,
140                               'result': result1,
141                               'status': status1},
142                'FUNCvirNetL3': {'duration': time2,
143                                 'result': result2,
144                                 'status': status2}}
145     return payload
146
147
148 def SetOnosIp():
149     cmd = "openstack catalog show network | grep publicURL"
150     cmd_output = os.popen(cmd).read()
151     OC1 = re.search(r"\d+\.\d+\.\d+\.\d+", cmd_output).group()
152     os.environ['OC1'] = OC1
153     time.sleep(2)
154     logger.debug("ONOS IP is " + OC1)
155
156
157 def SetOnosIpForJoid():
158     cmd = "env | grep SDN_CONTROLLER"
159     cmd_output = os.popen(cmd).read()
160     OC1 = re.search(r"\d+\.\d+\.\d+\.\d+", cmd_output).group()
161     os.environ['OC1'] = OC1
162     time.sleep(2)
163     logger.debug("ONOS IP is " + OC1)
164
165
166 def CleanOnosTest():
167     TESTONPATH = ONOSCI_PATH + "onos/"
168     cmd = "rm -rf " + TESTONPATH
169     os.system(cmd)
170     time.sleep(2)
171     logger.debug("Clean ONOS Teston")
172
173
174 def CreateImage():
175     glance_client = openstack_utils.get_glance_client()
176     image_id = openstack_utils.create_glance_image(glance_client,
177                                                    GLANCE_IMAGE_NAME,
178                                                    GLANCE_IMAGE_PATH)
179     EXIT_CODE = -1
180     if not image_id:
181         logger.error("Failed to create a Glance image...")
182         return(EXIT_CODE)
183     logger.debug("Image '%s' with ID=%s created successfully."
184                  % (GLANCE_IMAGE_NAME, image_id))
185
186
187 def SfcTest():
188     cmd = "python " + SFC_PATH + "Sfc.py"
189     logger.debug("Run sfc tests")
190     os.system(cmd)
191
192
193 def GetIp(type):
194     cmd = "openstack catalog show " + type + " | grep publicURL"
195     cmd_output = os.popen(cmd).read()
196     ip = re.search(r"\d+\.\d+\.\d+\.\d+", cmd_output).group()
197     return ip
198
199
200 def Replace(before, after):
201     file = "Sfc_fun.py"
202     cmd = "sed -i 's/" + before + "/" + after + "/g' " + SFC_PATH + file
203     os.system(cmd)
204
205
206 def SetSfcConf():
207     Replace("keystone_ip", GetIp("keystone"))
208     Replace("neutron_ip", GetIp("neutron"))
209     Replace("nova_ip", GetIp("nova"))
210     Replace("glance_ip", GetIp("glance"))
211     pwd = os.environ['OS_PASSWORD']
212     Replace("console", pwd)
213     creds_neutron = openstack_utils.get_credentials("neutron")
214     neutron_client = neutronclient.Client(**creds_neutron)
215     ext_net = openstack_utils.get_external_net(neutron_client)
216     Replace("admin_floating_net", ext_net)
217     logger.info("Modify configuration for SFC")
218
219
220 def OnosTest():
221     start_time = time.time()
222     stop_time = start_time
223     if INSTALLER_TYPE == "joid":
224         logger.debug("Installer is Joid")
225         SetOnosIpForJoid()
226     else:
227         SetOnosIp()
228     RunScript("FUNCvirNetNB")
229     RunScript("FUNCvirNetNBL3")
230     try:
231         logger.debug("Push ONOS results into DB")
232         # TODO check path result for the file
233         result = GetResult()
234         stop_time = time.time()
235
236         # ONOS success criteria = all tests OK
237         # i.e. FUNCvirNet & FUNCvirNetL3
238         status = "FAIL"
239         try:
240             if (result['FUNCvirNet']['result'] == "Success" and
241                     result['FUNCvirNetL3']['result'] == "Success"):
242                     status = "PASS"
243         except:
244             logger.error("Unable to set ONOS criteria")
245
246         functest_utils.push_results_to_db("functest",
247                                           "onos",
248                                           logger,
249                                           start_time,
250                                           stop_time,
251                                           status,
252                                           result)
253
254     except:
255         logger.error("Error pushing results into Database")
256
257     if status == "FAIL":
258         EXIT_CODE = -1
259         exit(EXIT_CODE)
260
261
262 def main():
263
264     if args.testcase == "sfc":
265         CreateImage()
266         SetSfcConf()
267         SfcTest()
268     else:
269         OnosTest()
270
271 if __name__ == '__main__':
272     main()