blob: 38517a12c0e240343d22d58c2209c88d219f7ef0 [file] [log] [blame]
Matteo Scandolo48d3d2d2017-08-08 13:05:27 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
A R Karthick9313b762016-11-07 13:14:35 -080017from OnosLog import OnosLog
A.R Karthick2e99c472017-03-22 19:13:51 -070018import logging
19logging.getLogger('scapy.runtime').setLevel(logging.ERROR)
A R Karthick76a497a2017-04-12 10:59:39 -070020from CordTestUtils import log_test as log
A R Karthicke14fc022016-12-08 14:50:29 -080021from onosclidriver import OnosCliDriver
A.R Karthickbe7768c2017-03-17 11:39:41 -070022from OnosCtrl import OnosCtrl
A R Karthick6f2ac6f2017-07-26 12:55:24 -070023try:
24 from docker import APIClient as Client
25except:
26 from docker import Client
Thangavelu K Sdcb04332017-01-27 22:57:56 +000027from CordContainer import *
28import json
29import requests
A R Karthick9313b762016-11-07 13:14:35 -080030import unittest
A R Karthicke14fc022016-12-08 14:50:29 -080031import os
32import time
A.R Karthick2e99c472017-03-22 19:13:51 -070033import warnings
A R Karthick9313b762016-11-07 13:14:35 -080034
A R Karthick81ece152017-01-11 16:46:43 -080035def get_controller_names(controllers):
36 controller_names = [ 'cord-onos' if controllers.index(c) == 0 else 'cord-onos-{}'.format(controllers.index(c)+1) for c in controllers ]
37 return controller_names
38
39def get_controller_map(controllers):
40 controller_map = ( ('cord-onos' if controllers.index(c) == 0 else 'cord-onos-{}'.format(controllers.index(c)+1),c) for c in controllers )
41 return dict(controller_map)
42
A R Karthick9313b762016-11-07 13:14:35 -080043class CordLogger(unittest.TestCase):
44
A R Karthicke14fc022016-12-08 14:50:29 -080045 controllers = os.getenv('ONOS_CONTROLLER_IP', '').split(',')
A R Karthick81ece152017-01-11 16:46:43 -080046 controller_names = get_controller_names(controllers)
47 controller_map = get_controller_map(controllers)
A R Karthicke14fc022016-12-08 14:50:29 -080048 cliSessions = {}
49 onosLogLevel = 'INFO'
50 curLogLevel = onosLogLevel
51 testLogLevel = os.getenv('LOG_LEVEL', onosLogLevel)
Thangavelu K Sdcb04332017-01-27 22:57:56 +000052 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../setup')
A R Karthicke8935c62016-12-08 18:17:17 -080053 archive_dir = os.path.join(setup_dir, 'test_logs')
A R Karthickeac16d72017-01-11 16:56:04 -080054 onos_data_dir = os.path.join(setup_dir, 'cord-onos-data')
A R Karthicke14fc022016-12-08 14:50:29 -080055
A.R Karthick2e99c472017-03-22 19:13:51 -070056 def __init__(self, *args, **kwargs):
57 warnings.simplefilter('ignore')
58 super(CordLogger, self).__init__(*args, **kwargs)
59
A R Karthicke14fc022016-12-08 14:50:29 -080060 @classmethod
61 def cliSessionEnter(cls):
62 try:
63 for controller in cls.controllers:
64 if not controller:
65 continue
66 retries = 0
A R Karthick6cc8b812016-12-09 10:24:40 -080067 while retries < 30:
A R Karthicke14fc022016-12-08 14:50:29 -080068 cli = OnosCliDriver(controller = controller, connect = True)
69 if cli.handle:
70 cls.cliSessions[controller] = cli
71 break
72 else:
73 retries += 1
74 time.sleep(2)
75 except:
76 pass
77
78 @classmethod
79 def cliSessionExit(cls):
80 try:
81 for controller, cli in cls.cliSessions.items():
82 if cli:
83 cli.disconnect()
84 except:
85 pass
86
A R Karthick9313b762016-11-07 13:14:35 -080087 def setUp(self):
88 '''Read the log buffer'''
A R Karthicke14fc022016-12-08 14:50:29 -080089 self.logSet()
A R Karthick9313b762016-11-07 13:14:35 -080090 try:
91 onosLog = OnosLog()
92 st, output = onosLog.get_log()
A R Karthick9313b762016-11-07 13:14:35 -080093 except: pass
94
95 def tearDown(self):
96 '''Dump the log buffer for ERRORS/warnings'''
A R Karthicke14fc022016-12-08 14:50:29 -080097 #reset the log level back to default log level after a test
98 self.logSet(level = self.onosLogLevel)
A R Karthick9313b762016-11-07 13:14:35 -080099 try:
100 onosLog = OnosLog()
101 st, output = onosLog.get_log( ('ERROR','WARN') )
A R Karthick9313b762016-11-07 13:14:35 -0800102 if st and output:
103 log.info('\nTest %s has errors and warnings\n' %self._testMethodName)
104 log.info('%s' %output)
105 else:
106 log.info('\nTest %s has no errors and warnings in the logs' %self._testMethodName)
107 except: pass
A R Karthicke8935c62016-12-08 18:17:17 -0800108 try:
109 self.archive_results(self._testMethodName)
110 except: pass
111
112 @classmethod
A.R Karthick53d92702017-03-13 10:10:38 -0700113 def archive_results(cls, testName, controllers = None, iteration = None, archive_partition = False):
A R Karthick81ece152017-01-11 16:46:43 -0800114 if not os.path.exists(cls.onos_data_dir):
115 return cls.archive_results_unshared(testName, controllers = controllers, iteration = iteration)
116 if not os.path.exists(cls.archive_dir):
117 os.mkdir(cls.archive_dir)
118 if controllers is None:
119 controllers = cls.controllers
120 controller_map = cls.controller_map
121 else:
122 controller_map = get_controller_map(controllers)
123
124 iteration_str = '' if iteration is None else '_{}'.format(iteration)
A.R Karthick53d92702017-03-13 10:10:38 -0700125 if archive_partition is False:
126 archive_target = 'log'
127 tar_options = ''
128 else:
129 archive_target = ''
130 tar_options = '--exclude=cache --exclude=tmp'
131
A R Karthick81ece152017-01-11 16:46:43 -0800132 for c in controller_map.keys():
133 archive_file = os.path.join(cls.archive_dir,
134 'logs_{}_{}{}.tar.gz'.format(controller_map[c], testName, iteration_str))
A.R Karthick53d92702017-03-13 10:10:38 -0700135 archive_path = os.path.join(cls.setup_dir, '{}-data'.format(c), archive_target)
136 cmd = 'cd {} && tar cvzf {} . {}'.format(archive_path, archive_file, tar_options)
A R Karthick81ece152017-01-11 16:46:43 -0800137 try:
138 os.system(cmd)
139 except: pass
140
141 @classmethod
142 def archive_results_unshared(cls, testName, controllers = None, iteration = None, cache_result = False):
A R Karthicke8935c62016-12-08 18:17:17 -0800143 log_map = {}
144 if controllers is None:
145 controllers = cls.controllers
146 else:
147 if type(controllers) in [ str, unicode ]:
148 controllers = [ controllers ]
149 try:
150 for controller in controllers:
151 onosLog = OnosLog(host = controller)
152 st, output = onosLog.get_log(cache_result = cache_result)
153 log_map[controller] = (st, output)
154 except:
155 return
156
157 if not os.path.exists(cls.archive_dir):
158 os.mkdir(cls.archive_dir)
159 for controller, results in log_map.items():
160 st, output = results
161 if st and output:
162 iteration_str = '' if iteration is None else '_{}'.format(iteration)
163 archive_file = os.path.join(cls.archive_dir,
164 'logs_{}_{}{}'.format(controller, testName, iteration_str))
165 archive_cmd = 'gzip -9 -f {}'.format(archive_file)
166 if os.access(archive_file, os.F_OK):
167 os.unlink(archive_file)
168 with open(archive_file, 'w') as fd:
169 fd.write(output)
170 try:
171 os.system(archive_cmd)
172 except: pass
A R Karthicke14fc022016-12-08 14:50:29 -0800173
174 @classmethod
175 def logSet(cls, level = None, app = 'org.onosproject', controllers = None, forced = False):
176 #explicit override of level is allowed to reset log levels
177 if level is None:
178 level = cls.testLogLevel
179 #if we are already at current/ONOS log level, there is nothing to do
180 if forced is False and level == cls.curLogLevel:
181 return
182 if controllers is None:
183 controllers = cls.controllers
184 else:
185 if type(controllers) in [str, unicode]:
186 controllers = [ controllers ]
187 cls.cliSessionEnter()
188 try:
189 for controller in controllers:
190 if cls.cliSessions.has_key(controller):
191 cls.cliSessions[controller].logSet(level = level, app = app)
192 cls.curLogLevel = level
193 except:
194 pass
195 cls.cliSessionExit()
Thangavelu K Sdcb04332017-01-27 22:57:56 +0000196
197 @classmethod
198 def stat_option(cls, stat = None, serverDetails = None):
199 # each stat option we can do some specific functions
200 if stat is None:
201 stat = cls.statOptionsList
202 if serverDetails is None:
203 serverDetails = cls.serverOptionsList
204 stat_choice = 'COLLECTD'
205 test_name = cls.testHostName
A R Karthickf7a613b2017-02-24 09:36:44 -0800206 test_image = 'cordtest/nose'
Thangavelu K Sdcb04332017-01-27 22:57:56 +0000207 if stat_choice in stat:
208 onos_ctrl = OnosCtrl('org.onosproject.cpman')
209 status, _ = onos_ctrl.activate()
210 if serverDetails is '':
211 ## default Test Container is used to install CollectD
212 pass
213 elif serverDetails in 'NEW':
214 test_image = 'cord-test/exserver'
215 test_name ='cord-collectd'
216 else:
217 pass
218 # cls.connect_server(serverDetails)
219 ## TO-DO for already up and running server, install collectd agent etc...
220 cls.start_collectd_agent_in_server(name = test_name, image = test_image)
221 for controller in cls.controllers:
222 if not controller:
223 continue
224 url_mem_stats = 'http://%s:8181/onos/cpman/controlmetrics/memory_metrics'%(controller)
225 url_cpu_stats = 'http://%s:8181/onos/cpman/controlmetrics/cpu_metrics'%(controller)
226 auth = ('karaf', 'karaf')
227 cls.collectd_agent_metrics(controller, auth, url = url_cpu_stats)
228 cls.collectd_agent_metrics(controller, auth, url = url_mem_stats)
229 return
230
231
232 @classmethod
233 def collectd_agent_metrics(cls,controller=None, auth =None, url = None):
234 '''This function is getting rules from ONOS with json format'''
235 if url:
236 resp = requests.get(url, auth = auth)
237 log.info('Collectd agent has provided metrics via ONOS controller, url = %s \nand status = %s' %(url,resp.json()))
238 return resp
239
240
241 @classmethod
242 def start_collectd_agent_in_server(cls, name = None, image = None):
243 container_cmd_exec = Container(name = name, image = image)
244 tty = False
245 dckr = Client()
246 cmd = 'sudo /etc/init.d/collectd start'
247 i = container_cmd_exec.execute(cmd = cmd, tty= tty, stream = True)
248 return
249
250 @classmethod
251 def disable_onos_apps(cls, stat = None, app = None):
252 stat_choice = 'COLLECTD'
253 if stat is None:
254 stat = cls.statOptionsList
255 if stat_choice in stat:
256 onos_ctrl = OnosCtrl('org.onosproject.cpman')
257 status, _ = onos_ctrl.deactivate()