Merge "Reverted the file permission"
[functest.git] / functest / opnfv_tests / sdn / onos / teston / onos.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 import urlparse
22
23 import argparse
24 from neutronclient.v2_0 import client as neutronclient
25
26 import functest.utils.functest_constants as ft_constants
27 import functest.utils.functest_logger as ft_logger
28 import functest.utils.functest_utils as ft_utils
29 import functest.utils.openstack_utils as openstack_utils
30
31
32 parser = argparse.ArgumentParser()
33 parser.add_argument("-t", "--testcase", help="Testcase name")
34 args = parser.parse_args()
35
36
37 """ logging configuration """
38 logger = ft_logger.Logger("onos").getLogger()
39
40 # onos parameters
41 ONOSCI_PATH = ft_constants.REPOS_DIR + "/"
42 starttime = datetime.datetime.now()
43
44 INSTALLER_TYPE = ft_constants.CI_INSTALLER_TYPE
45 ONOS_SFC_IMAGE_NAME = ft_constants.ONOS_SFC_IMAGE_NAME
46 ONOS_SFC_IMAGE_PATH = os.path.join(ft_constants.FUNCTEST_DATA_DIR,
47                                    ft_constants.ONOS_SFC_IMAGE_FILENAME)
48 ONOS_SFC_PATH = os.path.join(ft_constants.FUNCTEST_REPO_DIR,
49                              ft_constants.ONOS_SFC_RELATIVE_PATH)
50
51
52 def RunScript(testname):
53     """
54     Run ONOS Test Script
55     Parameters:
56     testname: ONOS Testcase Name
57     """
58     runtest = ONOSCI_PATH + "onos/TestON/bin/cli.py run " + testname
59     logger.debug("Run script " + testname)
60     os.system(runtest)
61
62
63 def DownloadCodes(url="https://github.com/wuwenbin2/OnosSystemTest.git"):
64     """
65     Download Onos Teston codes
66     Parameters:
67     url: github url
68     """
69     downloadcode = "git clone " + url + " " + ONOSCI_PATH + "OnosSystemTest"
70     logger.debug("Download Onos Teston codes " + url)
71     os.system(downloadcode)
72
73
74 def GetResult():
75     LOGPATH = ONOSCI_PATH + "onos/TestON/logs"
76     cmd = "grep -rnh " + "Fail" + " " + LOGPATH
77     Resultbuffer = os.popen(cmd).read()
78     # duration = datetime.datetime.now() - starttime
79     time.sleep(2)
80
81     if re.search("\s+[1-9]+\s+", Resultbuffer):
82         logger.debug("Testcase Fails\n" + Resultbuffer)
83         # Result = "Failed"
84     else:
85         logger.debug("Testcases Success")
86         # Result = "Success"
87     # payload={'timestart': str(starttime),
88     #          'duration': str(duration),
89     #            'status': Result}
90     cmd = "grep -rnh 'Execution Time' " + LOGPATH
91     Resultbuffer = os.popen(cmd).read()
92     time1 = Resultbuffer[114:128]
93     time2 = Resultbuffer[28:42]
94     cmd = "grep -rnh 'Success Percentage' " + LOGPATH + "/FUNCvirNetNB_*"
95     Resultbuffer = os.popen(cmd).read()
96     if Resultbuffer.find('100%') >= 0:
97         result1 = 'Success'
98     else:
99         result1 = 'Failed'
100     cmd = "grep -rnh 'Success Percentage' " + LOGPATH + "/FUNCvirNetNBL3*"
101     Resultbuffer = os.popen(cmd).read()
102     if Resultbuffer.find('100%') >= 0:
103         result2 = 'Success'
104     else:
105         result2 = 'Failed'
106     status1 = []
107     status2 = []
108     cmd = "grep -rnh 'h3' " + LOGPATH + "/FUNCvirNetNB_*"
109     Resultbuffer = os.popen(cmd).read()
110     pattern = re.compile("<h3>([^-]+) - ([^-]+) - (\S*)</h3>")
111     # res = pattern.search(Resultbuffer).groups()
112     res = pattern.findall(Resultbuffer)
113     i = 0
114     for index in range(len(res)):
115         status1.append({'Case name:': res[i][0] + res[i][1],
116                         'Case result': res[i][2]})
117         i = i + 1
118     cmd = "grep -rnh 'h3' " + LOGPATH + "/FUNCvirNetNBL3*"
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         status2.append({'Case name:': res[i][0] + res[i][1],
126                         'Case result': res[i][2]})
127         i = i + 1
128     payload = {'timestart': str(starttime),
129                'FUNCvirNet': {'duration': time1,
130                               'result': result1,
131                               'status': status1},
132                'FUNCvirNetL3': {'duration': time2,
133                                 'result': result2,
134                                 'status': status2}}
135     return payload
136
137
138 def SetOnosIp():
139     # cmd = "openstack catalog show network | grep publicURL"
140     neutron_url = openstack_utils.get_endpoint(service_type='network')
141     OC1 = urlparse.urlparse(neutron_url).hostname
142     os.environ['OC1'] = OC1
143     time.sleep(2)
144     logger.debug("ONOS IP is " + OC1)
145
146
147 def SetOnosIpForJoid():
148     cmd = "env | grep SDN_CONTROLLER"
149     cmd_output = os.popen(cmd).read()
150     OC1 = re.search(r"\d+\.\d+\.\d+\.\d+", cmd_output).group()
151     os.environ['OC1'] = OC1
152     time.sleep(2)
153     logger.debug("ONOS IP is " + OC1)
154
155
156 def CleanOnosTest():
157     TESTONPATH = ONOSCI_PATH + "onos/"
158     cmd = "rm -rf " + TESTONPATH
159     os.system(cmd)
160     time.sleep(2)
161     logger.debug("Clean ONOS Teston")
162
163
164 def CreateImage():
165     glance_client = openstack_utils.get_glance_client()
166     image_id = openstack_utils.create_glance_image(glance_client,
167                                                    ONOS_SFC_IMAGE_NAME,
168                                                    ONOS_SFC_IMAGE_PATH)
169     EXIT_CODE = -1
170     if not image_id:
171         logger.error("Failed to create a Glance image...")
172         return(EXIT_CODE)
173     logger.debug("Image '%s' with ID=%s created successfully."
174                  % (ONOS_SFC_IMAGE_NAME, image_id))
175
176
177 def SfcTest():
178     cmd = "python " + ONOS_SFC_PATH + "/Sfc.py"
179     logger.debug("Run sfc tests")
180     os.system(cmd)
181
182
183 def GetIp(type):
184     # cmd = "openstack catalog show " + type + " | grep publicURL"
185     url = openstack_utils.get_endpoint(service_type=type)
186     return urlparse.urlparse(url).hostname
187
188
189 def Replace(before, after):
190     file = "/Sfc_fun.py"
191     cmd = "sed -i 's/" + before + "/" + after + "/g' " + ONOS_SFC_PATH + file
192     os.system(cmd)
193
194
195 def SetSfcConf():
196     Replace("keystone_ip", GetIp("keystone"))
197     Replace("neutron_ip", GetIp("neutron"))
198     Replace("nova_ip", GetIp("nova"))
199     Replace("glance_ip", GetIp("glance"))
200     pwd = ft_constants.OS_PASSWORD
201     Replace("console", pwd)
202     creds_neutron = openstack_utils.get_credentials("neutron")
203     neutron_client = neutronclient.Client(**creds_neutron)
204     ext_net = openstack_utils.get_external_net(neutron_client)
205     Replace("admin_floating_net", ext_net)
206     logger.info("Modify configuration for SFC")
207
208
209 def OnosTest():
210     start_time = time.time()
211     stop_time = start_time
212     if INSTALLER_TYPE == "joid":
213         logger.debug("Installer is Joid")
214         SetOnosIpForJoid()
215     else:
216         SetOnosIp()
217     RunScript("FUNCvirNetNB")
218     RunScript("FUNCvirNetNBL3")
219     try:
220         logger.debug("Push ONOS results into DB")
221         # TODO check path result for the file
222         result = GetResult()
223         stop_time = time.time()
224
225         # ONOS success criteria = all tests OK
226         # i.e. FUNCvirNet & FUNCvirNetL3
227         status = "FAIL"
228         try:
229             if (result['FUNCvirNet']['result'] == "Success" and
230                     result['FUNCvirNetL3']['result'] == "Success"):
231                     status = "PASS"
232         except:
233             logger.error("Unable to set ONOS criteria")
234
235         ft_utils.push_results_to_db("functest",
236                                     "onos",
237                                     start_time,
238                                     stop_time,
239                                     status,
240                                     result)
241
242     except:
243         logger.error("Error pushing results into Database")
244
245     if status == "FAIL":
246         EXIT_CODE = -1
247         exit(EXIT_CODE)
248
249
250 def main():
251
252     if args.testcase == "sfc":
253         CreateImage()
254         SetSfcConf()
255         SfcTest()
256     else:
257         OnosTest()
258
259
260 if __name__ == '__main__':
261     main()