35ced61c5db081aa374036d821e8fa817f2f8d66
[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 from neutronclient.v2_0 import client as neutronclient
23
24 import functest.utils.functest_logger as ft_logger
25 import functest.utils.functest_utils as functest_utils
26 import functest.utils.openstack_utils as openstack_utils
27
28 """ logging configuration """
29 logger = ft_logger.Logger("onos").getLogger()
30
31 # onos parameters
32 TEST_DB = functest_utils.get_parameter_from_yaml(
33     "results.test_db_url")
34 ONOS_REPO_PATH = functest_utils.get_parameter_from_yaml(
35     "general.directories.dir_repos")
36 ONOS_CONF_DIR = functest_utils.get_parameter_from_yaml(
37     "general.directories.dir_functest_conf")
38 REPO_PATH = ONOS_REPO_PATH + '/functest/'
39 if not os.path.exists(REPO_PATH):
40     logger.error("Functest repository directory not found '%s'" % REPO_PATH)
41     exit(-1)
42
43 ONOSCI_PATH = ONOS_REPO_PATH + "/"
44 starttime = datetime.datetime.now()
45
46 HOME = os.environ['HOME'] + "/"
47 INSTALLER_TYPE = os.environ['INSTALLER_TYPE']
48 DEPLOY_SCENARIO = os.environ['DEPLOY_SCENARIO']
49 ONOSCI_PATH = ONOS_REPO_PATH + "/"
50 GLANCE_IMAGE_NAME = functest_utils.get_parameter_from_yaml(
51     "onos_sfc.image_name")
52 GLANCE_IMAGE_FILENAME = functest_utils.get_parameter_from_yaml(
53     "onos_sfc.image_file_name")
54 GLANCE_IMAGE_PATH = functest_utils.get_parameter_from_yaml(
55     "general.directories.dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
56 SFC_PATH = REPO_PATH + functest_utils.get_parameter_from_yaml(
57     "general.directories.dir_onos_sfc")
58
59
60 def RunScript(testname):
61     """
62     Run ONOS Test Script
63     Parameters:
64     testname: ONOS Testcase Name
65     """
66     runtest = ONOSCI_PATH + "onos/TestON/bin/cli.py run " + testname
67     logger.debug("Run script " + testname)
68     os.system(runtest)
69
70
71 def DownloadCodes(url="https://github.com/wuwenbin2/OnosSystemTest.git"):
72     """
73     Download Onos Teston codes
74     Parameters:
75     url: github url
76     """
77     downloadcode = "git clone " + url + " " + ONOSCI_PATH + "OnosSystemTest"
78     logger.debug("Download Onos Teston codes " + url)
79     os.system(downloadcode)
80
81
82 def GetResult():
83     LOGPATH = ONOSCI_PATH + "onos/TestON/logs"
84     cmd = "grep -rnh " + "Fail" + " " + LOGPATH
85     Resultbuffer = os.popen(cmd).read()
86     # duration = datetime.datetime.now() - starttime
87     time.sleep(2)
88
89     if re.search("\s+[1-9]+\s+", Resultbuffer):
90         logger.debug("Testcase Fails\n" + Resultbuffer)
91         # Result = "Failed"
92     else:
93         logger.debug("Testcases Success")
94         # Result = "Success"
95     # payload={'timestart': str(starttime),
96     #          'duration': str(duration),
97     #            'status': Result}
98     cmd = "grep -rnh 'Execution Time' " + LOGPATH
99     Resultbuffer = os.popen(cmd).read()
100     time1 = Resultbuffer[114:128]
101     time2 = Resultbuffer[28:42]
102     cmd = "grep -rnh 'Success Percentage' " + LOGPATH + "/FUNCvirNetNB_*"
103     Resultbuffer = os.popen(cmd).read()
104     if Resultbuffer.find('100%') >= 0:
105         result1 = 'Success'
106     else:
107         result1 = 'Failed'
108     cmd = "grep -rnh 'Success Percentage' " + LOGPATH + "/FUNCvirNetNBL3*"
109     Resultbuffer = os.popen(cmd).read()
110     if Resultbuffer.find('100%') >= 0:
111         result2 = 'Success'
112     else:
113         result2 = 'Failed'
114     status1 = []
115     status2 = []
116     cmd = "grep -rnh 'h3' " + LOGPATH + "/FUNCvirNetNB_*"
117     Resultbuffer = os.popen(cmd).read()
118     pattern = re.compile("<h3>([^-]+) - ([^-]+) - (\S*)</h3>")
119     # res = pattern.search(Resultbuffer).groups()
120     res = pattern.findall(Resultbuffer)
121     i = 0
122     for index in range(len(res)):
123         status1.append({'Case name:': res[i][0] + res[i][1],
124                         'Case result': res[i][2]})
125         i = i + 1
126     cmd = "grep -rnh 'h3' " + LOGPATH + "/FUNCvirNetNBL3*"
127     Resultbuffer = os.popen(cmd).read()
128     pattern = re.compile("<h3>([^-]+) - ([^-]+) - (\S*)</h3>")
129     # res = pattern.search(Resultbuffer).groups()
130     res = pattern.findall(Resultbuffer)
131     i = 0
132     for index in range(len(res)):
133         status2.append({'Case name:': res[i][0] + res[i][1],
134                         'Case result': res[i][2]})
135         i = i + 1
136     payload = {'timestart': str(starttime),
137                'FUNCvirNet': {'duration': time1,
138                               'result': result1,
139                               'status': status1},
140                'FUNCvirNetL3': {'duration': time2,
141                                 'result': result2,
142                                 'status': status2}}
143     return payload
144
145
146 def SetOnosIp():
147     cmd = "openstack catalog show network | grep publicURL"
148     cmd_output = os.popen(cmd).read()
149     OC1 = re.search(r"\d+\.\d+\.\d+\.\d+", cmd_output).group()
150     os.environ['OC1'] = OC1
151     time.sleep(2)
152     logger.debug("ONOS IP is " + OC1)
153
154
155 def SetOnosIpForJoid():
156     cmd = "env | grep SDN_CONTROLLER"
157     cmd_output = os.popen(cmd).read()
158     OC1 = re.search(r"\d+\.\d+\.\d+\.\d+", cmd_output).group()
159     os.environ['OC1'] = OC1
160     time.sleep(2)
161     logger.debug("ONOS IP is " + OC1)
162
163
164 def CleanOnosTest():
165     TESTONPATH = ONOSCI_PATH + "onos/"
166     cmd = "rm -rf " + TESTONPATH
167     os.system(cmd)
168     time.sleep(2)
169     logger.debug("Clean ONOS Teston")
170
171
172 def CreateImage():
173     glance_client = openstack_utils.get_glance_client()
174     image_id = openstack_utils.create_glance_image(glance_client,
175                                                    GLANCE_IMAGE_NAME,
176                                                    GLANCE_IMAGE_PATH)
177     EXIT_CODE = -1
178     if not image_id:
179         logger.error("Failed to create a Glance image...")
180         return(EXIT_CODE)
181     logger.debug("Image '%s' with ID=%s created successfully."
182                  % (GLANCE_IMAGE_NAME, image_id))
183
184
185 def SfcTest():
186     cmd = "python " + SFC_PATH + "Sfc.py"
187     logger.debug("Run sfc tests")
188     os.system(cmd)
189
190
191 def GetIp(type):
192     cmd = "openstack catalog show " + type + " | grep publicURL"
193     cmd_output = os.popen(cmd).read()
194     ip = re.search(r"\d+\.\d+\.\d+\.\d+", cmd_output).group()
195     return ip
196
197
198 def Replace(before, after):
199     file = "Sfc_fun.py"
200     cmd = "sed -i 's/" + before + "/" + after + "/g' " + SFC_PATH + file
201     os.system(cmd)
202
203
204 def SetSfcConf():
205     Replace("keystone_ip", GetIp("keystone"))
206     Replace("neutron_ip", GetIp("neutron"))
207     Replace("nova_ip", GetIp("nova"))
208     Replace("glance_ip", GetIp("glance"))
209     pwd = os.environ['OS_PASSWORD']
210     Replace("console", pwd)
211     creds_neutron = openstack_utils.get_credentials("neutron")
212     neutron_client = neutronclient.Client(**creds_neutron)
213     ext_net = openstack_utils.get_external_net(neutron_client)
214     Replace("admin_floating_net", ext_net)
215     logger.info("Modify configuration for SFC")
216
217
218 def main():
219     start_time = time.time()
220     stop_time = start_time
221     # DownloadCodes()
222     # if args.installer == "joid":
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 DEPLOY_SCENARIO == "os-onos-sfc-ha":
258         CreateImage()
259         SetSfcConf()
260         SfcTest()
261
262     # CleanOnosTest()
263
264
265 if __name__ == '__main__':
266     main()