cls_oaicitest.py 169 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#/*
# * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# * contributor license agreements.  See the NOTICE file distributed with
# * this work for additional information regarding copyright ownership.
# * The OpenAirInterface Software Alliance licenses this file to You under
# * the OAI Public License, Version 1.1  (the "License"); you may not use this file
# * except in compliance with the License.
# * You may obtain a copy of the License at
# *
# *      http://www.openairinterface.org/?page_id=698
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# *-------------------------------------------------------------------------------
# * For more information about the OpenAirInterface (OAI) Software Alliance:
# *      contact@openairinterface.org
# */
#---------------------------------------------------------------------
# 
#
#   Required Python Version
#     Python 3.x
#
#   Required Python Package
#     pexpect
#---------------------------------------------------------------------


#-----------------------------------------------------------
# Import Libs
#-----------------------------------------------------------
import sys		# arg
import re		# reg
import pexpect	# pexpect
import time		# sleep
import os
import subprocess
import xml.etree.ElementTree as ET
import logging
import datetime
import signal
Remi Hardy's avatar
Remi Hardy committed
45
import statistics as stat
46 47 48 49 50 51
from multiprocessing import Process, Lock, SimpleQueue
logging.basicConfig(
	level=logging.DEBUG,
	format="[%(asctime)s] %(name)s:%(levelname)s: %(message)s"
)

Remi Hardy's avatar
Remi Hardy committed
52 53 54
#import our libs
import helpreadme as HELP
import constants as CONST
hardy's avatar
hardy committed
55
import sshconnection
56

57 58
import cls_module_ue
import cls_ci_ueinfra		#class defining the multi Ue infrastrucure
Remi Hardy's avatar
Remi Hardy committed
59

hardy's avatar
hardy committed
60
logging.getLogger("matplotlib").setLevel(logging.WARNING)
hardy's avatar
hardy committed
61 62
import matplotlib.pyplot as plt
import numpy as np
Remi Hardy's avatar
Remi Hardy committed
63 64 65 66 67

#-----------------------------------------------------------
# Utility functions
#-----------------------------------------------------------

hardy's avatar
hardy committed
68
def GetPingTimeAnalysis(RAN,ping_log_file,ping_rttavg_threshold):
Remi Hardy's avatar
Remi Hardy committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	#ping time values read from file
	t_ping=[]
	#ping stats (dictionary) to be returned by the function
	ping_stat={}
	if (os.path.isfile(ping_log_file)):
		with open(ping_log_file,"r") as f:
			for line in f:
				#looking for time=xxx ms field
				result=re.match('^.+time=(?P<ping_time>[0-9\.]+)',line)
				if result != None:
					t_ping.append(float(result.group('ping_time')))

		#initial stats
		ping_stat['min_0']=min(t_ping)
		ping_stat['mean_0']=stat.mean(t_ping)
		ping_stat['median_0']=stat.median(t_ping)
		ping_stat['max_0']=max(t_ping)

		#get index of max value
		
		max_loc=t_ping.index(max(t_ping))
		ping_stat['max_loc']=max_loc
		#remove it
hardy's avatar
hardy committed
92 93
		t_ping_post=t_ping.copy()
		t_ping_post.pop(max_loc)
Remi Hardy's avatar
Remi Hardy committed
94
		#new stats after removing max value
hardy's avatar
hardy committed
95 96 97 98
		ping_stat['min_1']=min(t_ping_post)
		ping_stat['mean_1']=stat.mean(t_ping_post)
		ping_stat['median_1']=stat.median(t_ping_post)
		ping_stat['max_1']=max(t_ping_post)
Remi Hardy's avatar
Remi Hardy committed
99

100 101 102 103 104 105 106
		#plot ping over time and save png for artifacts
		ticks = np.arange(0, len(t_ping), 1)
		figure, axis = plt.subplots(figsize=(10, 10))
		axis.plot(ticks,t_ping,marker='o')
		axis.set_xlabel('Ping Events')
		axis.set_ylabel("Ping RTT (in ms)")
		axis.set_title(ping_log_file)
hardy's avatar
hardy committed
107 108
		axis.set_xticks(ticks)
		axis.set_xticklabels([])
109 110 111 112 113 114
		YMAX=20 #base scale
		if max(t_ping) > YMAX:
			y_max=max(t_ping)+1
		else:
			y_max=YMAX+1
		plt.ylim(0,y_max)
115 116 117 118
		if ping_rttavg_threshold != '':
			th_label="AVG Ping Fail Threshold="+ping_rttavg_threshold
			plt.axhline(y=float(ping_rttavg_threshold), color='r', linestyle='-',label=th_label)
			axis.legend()
119 120
		plt.savefig(ping_log_file+'.png')

hardy's avatar
hardy committed
121
		#copy the png file already to enb to move it move it later into the artifacts
122 123 124 125 126
		try:
			mySSH = sshconnection.SSHConnection()
			mySSH.copyout(RAN.eNBIPAddress, RAN.eNBUserName, RAN.eNBPassword, ping_log_file+'.png', RAN.eNBSourceCodePath + '/cmake_targets/')
		except:
			logging.debug('\u001B[1;37;41m Ping PNG SCP to eNB FAILED\u001B[0m')
hardy's avatar
hardy committed
127

Remi Hardy's avatar
Remi Hardy committed
128 129 130
		return ping_stat

	else:
hardy's avatar
hardy committed
131
		logging.error("GetPingTimeAnalysis : Ping log file does not exist")
Remi Hardy's avatar
Remi Hardy committed
132 133 134 135
		return -1

	

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
#-----------------------------------------------------------
# OaiCiTest Class Definition
#-----------------------------------------------------------
class OaiCiTest():
	
	def __init__(self):
		self.ranRepository = ''
		self.ranBranch = ''
		self.ranCommitID = ''
		self.ranAllowMerge = False
		self.ranTargetBranch = ''

		self.FailReportCnt = 0
		self.ADBIPAddress = ''
		self.ADBUserName = ''
		self.ADBPassword = ''
		self.ADBCentralized = True
		self.testCase_id = ''
		self.testXMLfiles = []
155 156 157
		self.testUnstable = False
		self.testMinStableId = '999999'
		self.testStabilityPointReached = False
158 159 160
		self.desc = ''
		self.ping_args = ''
		self.ping_packetloss_threshold = ''
161
		self.ping_rttavg_threshold =''
162 163
		self.iperf_args = ''
		self.iperf_packetloss_threshold = ''
hardy's avatar
hardy committed
164
		self.iperf_bitrate_threshold = ''
165 166
		self.iperf_profile = ''
		self.iperf_options = ''
167
		self.iperf_direction = ''
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
		self.nbMaxUEtoAttach = -1
		self.UEDevices = []
		self.UEDevicesStatus = []
		self.UEDevicesRemoteServer = []
		self.UEDevicesRemoteUser = []
		self.UEDevicesOffCmd = []
		self.UEDevicesOnCmd = []
		self.UEDevicesRebootCmd = []
		self.CatMDevices = []
		self.UEIPAddresses = []
		self.idle_sleep_time = 0
		self.x2_ho_options = 'network'
		self.x2NbENBs = 0
		self.x2ENBBsIds = []
		self.x2ENBConnectedUEs = []
		self.repeatCounts = []
		self.finalStatus = False
		self.UEIPAddress = ''
		self.UEUserName = ''
		self.UEPassword = ''
		self.UE_instance = 0
		self.UESourceCodePath = ''
		self.UELogFile = ''
		self.Build_OAI_UE_args = ''
		self.Initialize_OAI_UE_args = ''
		self.clean_repository = True
		self.air_interface=''
		self.expectedNbOfConnectedUEs = 0
196
		self.ue_id = '' #used for module identification
Remi Hardy's avatar
Remi Hardy committed
197
		self.ue_trace ='' #used to enable QLog trace for Module UE, passed to Module UE object at InitializeUE()
198

hardy's avatar
hardy committed
199

200 201 202 203
	def BuildOAIUE(self,HTML):
		if self.UEIPAddress == '' or self.ranRepository == '' or self.ranBranch == '' or self.UEUserName == '' or self.UEPassword == '' or self.UESourceCodePath == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
hardy's avatar
hardy committed
204
		SSH = sshconnection.SSHConnection()
205 206 207 208 209 210 211 212 213 214
		SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
		result = re.search('--nrUE', self.Build_OAI_UE_args)
		if result is not None:
			self.air_interface='nr-uesoftmodem'
			ue_prefix = 'NR '
		else:
			self.air_interface='lte-uesoftmodem'
			ue_prefix = ''
		result = re.search('([a-zA-Z0-9\:\-\.\/])+\.git', self.ranRepository)
		if result is not None:
215
			full_ran_repo_name = self.ranRepository.replace('git/', 'git')
216 217 218 219 220 221 222 223 224 225 226 227 228
		else:
			full_ran_repo_name = self.ranRepository + '.git'
		SSH.command('mkdir -p ' + self.UESourceCodePath, '\$', 5)
		SSH.command('cd ' + self.UESourceCodePath, '\$', 5)
		SSH.command('if [ ! -e .git ]; then stdbuf -o0 git clone ' + full_ran_repo_name + ' .; else stdbuf -o0 git fetch --prune; fi', '\$', 600)
		# here add a check if git clone or git fetch went smoothly
		SSH.command('git config user.email "jenkins@openairinterface.org"', '\$', 5)
		SSH.command('git config user.name "OAI Jenkins"', '\$', 5)
		if self.clean_repository:
			SSH.command('ls *.txt', '\$', 5)
			result = re.search('LAST_BUILD_INFO', SSH.getBefore())
			if result is not None:
				mismatch = False
229
				SSH.command('grep --colour=never SRC_COMMIT LAST_BUILD_INFO.txt', '\$', 2)
230 231 232
				result = re.search(self.ranCommitID, SSH.getBefore())
				if result is None:
					mismatch = True
233
				SSH.command('grep --colour=never MERGED_W_TGT_BRANCH LAST_BUILD_INFO.txt', '\$', 2)
234 235 236 237
				if self.ranAllowMerge:
					result = re.search('YES', SSH.getBefore())
					if result is None:
						mismatch = True
238
					SSH.command('grep --colour=never TGT_BRANCH LAST_BUILD_INFO.txt', '\$', 2)
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
					if self.ranTargetBranch == '':
						result = re.search('develop', SSH.getBefore())
					else:
						result = re.search(self.ranTargetBranch, SSH.getBefore())
					if result is None:
						mismatch = True
				else:
					result = re.search('NO', SSH.getBefore())
					if result is None:
						mismatch = True
				if not mismatch:
					SSH.close()
					HTML.CreateHtmlTestRow(self.Build_OAI_UE_args, 'OK', CONST.ALL_PROCESSES_OK)
					return

			SSH.command('echo ' + self.UEPassword + ' | sudo -S git clean -x -d -ff', '\$', 30)

		# if the commit ID is provided use it to point to it
		if self.ranCommitID != '':
258
			SSH.command('git checkout -f ' + self.ranCommitID, '\$', 30)
259 260 261 262 263 264 265 266 267 268 269 270 271 272
		# if the branch is not develop, then it is a merge request and we need to do 
		# the potential merge. Note that merge conflicts should already been checked earlier
		if self.ranAllowMerge:
			if self.ranTargetBranch == '':
				if (self.ranBranch != 'develop') and (self.ranBranch != 'origin/develop'):
					SSH.command('git merge --ff origin/develop -m "Temporary merge for CI"', '\$', 5)
			else:
				logging.debug('Merging with the target branch: ' + self.ranTargetBranch)
				SSH.command('git merge --ff origin/' + self.ranTargetBranch + ' -m "Temporary merge for CI"', '\$', 5)
		SSH.command('source oaienv', '\$', 5)
		SSH.command('cd cmake_targets', '\$', 5)
		SSH.command('mkdir -p log', '\$', 5)
		SSH.command('chmod 777 log', '\$', 5)
		# no need to remove in log (git clean did the trick)
273
		SSH.command('stdbuf -o0 ./build_oai ' + self.Build_OAI_UE_args + ' 2>&1 | stdbuf -o0 tee compile_oai_ue.log', 'Bypassing the Tests|build have failed', 1200)
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
		SSH.command('ls ran_build/build', '\$', 3)
		SSH.command('ls ran_build/build', '\$', 3)
		buildStatus = True
		result = re.search(self.air_interface, SSH.getBefore())
		if result is None:
			buildStatus = False
		SSH.command('mkdir -p build_log_' + self.testCase_id, '\$', 5)
		SSH.command('mv log/* ' + 'build_log_' + self.testCase_id, '\$', 5)
		SSH.command('mv compile_oai_ue.log ' + 'build_log_' + self.testCase_id, '\$', 5)
		if buildStatus:
			# Generating a BUILD INFO file
			SSH.command('echo "SRC_BRANCH: ' + self.ranBranch + '" > ../LAST_BUILD_INFO.txt', '\$', 2)
			SSH.command('echo "SRC_COMMIT: ' + self.ranCommitID + '" >> ../LAST_BUILD_INFO.txt', '\$', 2)
			if self.ranAllowMerge:
				SSH.command('echo "MERGED_W_TGT_BRANCH: YES" >> ../LAST_BUILD_INFO.txt', '\$', 2)
				if self.ranTargetBranch == '':
					SSH.command('echo "TGT_BRANCH: develop" >> ../LAST_BUILD_INFO.txt', '\$', 2)
				else:
					SSH.command('echo "TGT_BRANCH: ' + self.ranTargetBranch + '" >> ../LAST_BUILD_INFO.txt', '\$', 2)
			else:
				SSH.command('echo "MERGED_W_TGT_BRANCH: NO" >> ../LAST_BUILD_INFO.txt', '\$', 2)
			SSH.close()
			HTML.CreateHtmlTestRow(self.Build_OAI_UE_args, 'OK', CONST.ALL_PROCESSES_OK, 'OAI UE')
		else:
			SSH.close()
			logging.error('\u001B[1m Building OAI UE Failed\u001B[0m')
			HTML.CreateHtmlTestRow(self.Build_OAI_UE_args, 'KO', CONST.ALL_PROCESSES_OK, 'OAI UE')
			HTML.CreateHtmlTabFooter(False)
302
			self.ConditionalExit()
303

304
	def CheckFlexranCtrlInstallation(self,RAN,EPC,CONTAINERS):
305 306
		if EPC.IPAddress == '' or EPC.UserName == '' or EPC.Password == '':
			return
hardy's avatar
hardy committed
307
		SSH = sshconnection.SSHConnection()
308 309 310 311 312
		SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
		SSH.command('ls -ls /opt/flexran_rtc/*/rt_controller', '\$', 5)
		result = re.search('/opt/flexran_rtc/build/rt_controller', SSH.getBefore())
		if result is not None:
			RAN.flexranCtrlInstalled=True
313
			RAN.flexranCtrlIpAddress=EPC.IPAddress
314
			logging.debug('Flexran Controller is installed')
315 316 317 318 319 320 321
		else:
			# Maybe flexran-rtc is deployed into a container
			SSH.command('docker inspect --format="FLEX_RTC_IP_ADDR = {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" prod-flexran-rtc', '\$', 5)
			result = re.search('FLEX_RTC_IP_ADDR = (?P<flex_ip_addr>[0-9\.]+)', SSH.getBefore())
			if result is not None:
				RAN.flexranCtrlDeployed=True
				RAN.flexranCtrlIpAddress=result.group('flex_ip_addr')
322 323
				CONTAINERS.flexranCtrlDeployed=True
				CONTAINERS.flexranCtrlIpAddress=result.group('flex_ip_addr')
324
				logging.debug('Flexran Controller is deployed: ' + RAN.flexranCtrlIpAddress)
325 326 327 328 329 330 331 332
		SSH.close()

	def InitializeFlexranCtrl(self, HTML,RAN,EPC):
		if RAN.flexranCtrlInstalled == False:
			return
		if EPC.IPAddress == '' or EPC.UserName == '' or EPC.Password == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
hardy's avatar
hardy committed
333
		SSH = sshconnection.SSHConnection()
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
		SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
		SSH.command('cd /opt/flexran_rtc', '\$', 5)
		SSH.command('echo ' + EPC.Password + ' | sudo -S rm -f log/*.log', '\$', 5)
		SSH.command('echo ' + EPC.Password + ' | sudo -S echo "build/rt_controller -c log_config/basic_log" > ./my-flexran-ctl.sh', '\$', 5)
		SSH.command('echo ' + EPC.Password + ' | sudo -S chmod 755 ./my-flexran-ctl.sh', '\$', 5)
		SSH.command('echo ' + EPC.Password + ' | sudo -S daemon --unsafe --name=flexran_rtc_daemon --chdir=/opt/flexran_rtc -o /opt/flexran_rtc/log/flexranctl_' + self.testCase_id + '.log ././my-flexran-ctl.sh', '\$', 5)
		SSH.command('ps -aux | grep --color=never rt_controller', '\$', 5)
		result = re.search('rt_controller -c ', SSH.getBefore())
		if result is not None:
			logging.debug('\u001B[1m Initialize FlexRan Controller Completed\u001B[0m')
			RAN.flexranCtrlStarted=True
		SSH.close()
		HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)
	
	def InitializeUE_common(self, device_id, idx,COTS_UE):
		try:
hardy's avatar
hardy committed
350
			SSH = sshconnection.SSHConnection()
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			if not self.ADBCentralized:
				# Reboot UE
				#SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesRebootCmd[idx], '\$', 60)
				# Wait
				#time.sleep(60)
				# Put in LTE-Mode only
				#SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "settings put global preferred_network_mode 11"\'', '\$', 60)
				#SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "settings put global preferred_network_mode1 11"\'', '\$', 60)
				#SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "settings put global preferred_network_mode2 11"\'', '\$', 60)
				#SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "settings put global preferred_network_mode3 11"\'', '\$', 60)
				# enable data service
				#SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "svc data enable"\'', '\$', 60)
				# we need to do radio on/off cycle to make sure of above changes
				# airplane mode off // radio on
				#SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesOnCmd[idx], '\$', 60)
				#time.sleep(10)
				# airplane mode on // radio off
				#SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesOffCmd[idx], '\$', 60)

				# normal procedure without reboot
				# enable data service
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "svc data enable"\'', '\$', 60)
				# airplane mode on // radio off
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesOffCmd[idx], '\$', 60)
				SSH.close()
				return

			#RH quick add-on to integrate cots control defined by yaml
			#if device_id exists in yaml dictionary, we execute the new procedure defined in cots_ue class
			#otherwise we use the legacy procedure
hardy's avatar
hardy committed
382
			logging.debug('Device id ' + str(device_id) + ', in COTS UE dict : ' + str(COTS_UE.Check_Exists(device_id)))
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
			if COTS_UE.Check_Exists(device_id):
				#switch device to Airplane mode ON (ie Radio OFF) 
				COTS_UE.Set_Airplane(device_id, 'ON')
			else:
				# enable data service
				SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "svc data enable"', '\$', 60)

				# The following commands are deprecated since we no longer work on Android 7+
				# SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell settings put global airplane_mode_on 1', '\$', 10)
				# SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true', '\$', 60)
				# a dedicated script has to be installed inside the UE
				# airplane mode on means call /data/local/tmp/off
				if device_id == '84B7N16418004022':
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "su - root -c /data/local/tmp/off"', '\$', 60)
				else:
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell /data/local/tmp/off', '\$', 60)
				#airplane mode off means call /data/local/tmp/on
				logging.debug('\u001B[1mUE (' + device_id + ') Initialize Completed\u001B[0m')
				SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

405
	def InitializeUE(self,HTML,RAN,EPC, COTS_UE, InfraUE,ue_trace,CONTAINERS):
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
		if self.ue_id=='':#no ID specified, then it is a COTS controlled by ADB
			if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
				HELP.GenericHelp(CONST.Version)
				sys.exit('Insufficient Parameter')
			multi_jobs = []
			i = 0
			for device_id in self.UEDevices:
				p = Process(target = self.InitializeUE_common, args = (device_id,i,COTS_UE,))
				p.daemon = True
				p.start()
				multi_jobs.append(p)
				i += 1
			for job in multi_jobs:
				job.join()
			HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)
		else: #if an ID is specified, it is a module from the yaml infrastructure file
			#RH
			Module_UE = cls_module_ue.Module_UE(InfraUE.ci_ue_infra[self.ue_id])
Remi Hardy's avatar
Remi Hardy committed
424
			Module_UE.ue_trace=ue_trace
425
			is_module=Module_UE.CheckCMProcess(EPC.Type)
426
			if is_module:
427 428
				Module_UE.EnableTrace()
				time.sleep(5)
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

				# Looping attach / detach / wait to be successful at least once
				cnt = 0
				status = -1
				while cnt < 4:
					Module_UE.Command("wup")
					logging.debug("Waiting for IP address to be assigned")
					time.sleep(20)
					logging.debug("Retrieve IP address")
					status=Module_UE.GetModuleIPAddress()
					if status==0:
						cnt = 10
					else:
						cnt += 1
						Module_UE.Command("detach")
						time.sleep(20)

				if cnt == 10 and status == 0:
hardy's avatar
hardy committed
447 448
					HTML.CreateHtmlTestRow(Module_UE.UEIPAddress, 'OK', CONST.ALL_PROCESSES_OK)	
					logging.debug('UE IP addresss : '+ Module_UE.UEIPAddress)
449 450
					#execute additional commands from yaml file after UE attach
					SSH = sshconnection.SSHConnection()
hardy's avatar
hardy committed
451
					SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
hardy's avatar
hardy committed
452
					if hasattr(Module_UE,'StartCommands'):
hardy's avatar
hardy committed
453
						for startcommand in Module_UE.StartCommands:
454 455
							cmd = 'echo ' + Module_UE.HostPassword + ' | ' + startcommand
							SSH.command(cmd,'\$',5)
456
					SSH.close()
hardy's avatar
hardy committed
457 458
					#check that the MTU is as expected / requested
					Module_UE.CheckModuleMTU()
hardy's avatar
hardy committed
459 460
				else: #status==-1 failed to retrieve IP address
					HTML.CreateHtmlTestRow('N/A', 'KO', CONST.UE_IP_ADDRESS_ISSUE)
461
					self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
hardy's avatar
hardy committed
462
					return
463
			
hardy's avatar
hardy committed
464

465

466
	def InitializeOAIUE(self,HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS):
467 468 469
		if self.UEIPAddress == '' or self.UEUserName == '' or self.UEPassword == '' or self.UESourceCodePath == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
470 471

			
472 473 474 475 476 477 478 479 480
		if self.air_interface == 'lte-uesoftmodem':
			result = re.search('--no-L2-connect', str(self.Initialize_OAI_UE_args))
			if result is None:
				check_eNB = True
				check_OAI_UE = False
				pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
				if (pStatus < 0):
					HTML.CreateHtmlTestRow(self.air_interface + ' ' + self.Initialize_OAI_UE_args, 'KO', pStatus)
					HTML.CreateHtmlTabFooter(False)
481
					self.ConditionalExit()
482 483 484
			UE_prefix = ''
		else:
			UE_prefix = 'NR '
hardy's avatar
hardy committed
485
		SSH = sshconnection.SSHConnection()
486 487
		SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
		# b2xx_fx3_utils reset procedure
488
		SSH.command('echo ' + self.UEPassword + ' | sudo -S uhd_find_devices', '\$', 180)
489 490 491 492 493
		result = re.search('type: b200', SSH.getBefore())
		if result is not None:
			logging.debug('Found a B2xx device --> resetting it')
			SSH.command('echo ' + self.UEPassword + ' | sudo -S b2xx_fx3_utils --reset-device', '\$', 10)
			# Reloading FGPA bin firmware
494
			SSH.command('echo ' + self.UEPassword + ' | sudo -S uhd_find_devices', '\$', 180)
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
		result = re.search('type: n3xx', str(SSH.getBefore()))
		if result is not None:
			logging.debug('Found a N3xx device --> resetting it')
		SSH.command('cd ' + self.UESourceCodePath, '\$', 5)
		# Initialize_OAI_UE_args usually start with -C and followed by the location in repository
		SSH.command('source oaienv', '\$', 5)
		SSH.command('cd cmake_targets/ran_build/build', '\$', 5)
		if self.air_interface == 'lte-uesoftmodem':
			result = re.search('--no-L2-connect', str(self.Initialize_OAI_UE_args))
			# We may have to regenerate the .u* files
			if result is None:
				SSH.command('ls /tmp/*.sed', '\$', 5)
				result = re.search('adapt_usim_parameters', SSH.getBefore())
				if result is not None:
					SSH.command('sed -f /tmp/adapt_usim_parameters.sed ../../../openair3/NAS/TOOLS/ue_eurecom_test_sfr.conf > ../../../openair3/NAS/TOOLS/ci-ue_eurecom_test_sfr.conf', '\$', 5)
				else:
					SSH.command('sed -e "s#93#92#" -e "s#8baf473f2f8fd09487cccbd7097c6862#fec86ba6eb707ed08905757b1bb44b8f#" -e "s#e734f8734007d6c5ce7a0508809e7e9c#C42449363BBAD02B66D16BC975D77CC1#" ../../../openair3/NAS/TOOLS/ue_eurecom_test_sfr.conf > ../../../openair3/NAS/TOOLS/ci-ue_eurecom_test_sfr.conf', '\$', 5)
				SSH.command('echo ' + self.UEPassword + ' | sudo -S rm -Rf .u*', '\$', 5)
				SSH.command('echo ' + self.UEPassword + ' | sudo -S ../../../targets/bin/conf2uedata -c ../../../openair3/NAS/TOOLS/ci-ue_eurecom_test_sfr.conf -o .', '\$', 5)
		else:
			SSH.command('if [ -e rbconfig.raw ]; then echo ' + self.UEPassword + ' | sudo -S rm rbconfig.raw; fi', '\$', 5)
			SSH.command('if [ -e reconfig.raw ]; then echo ' + self.UEPassword + ' | sudo -S rm reconfig.raw; fi', '\$', 5)
			# Copy the RAW files from gNB running directory (maybe on another machine)
			copyin_res = SSH.copyin(RAN.eNBIPAddress, RAN.eNBUserName, RAN.eNBPassword, RAN.eNBSourceCodePath + '/cmake_targets/rbconfig.raw', '.')
			if (copyin_res == 0):
				SSH.copyout(self.UEIPAddress, self.UEUserName, self.UEPassword, './rbconfig.raw', self.UESourceCodePath + '/cmake_targets/ran_build/build')
			copyin_res = SSH.copyin(RAN.eNBIPAddress, RAN.eNBUserName, RAN.eNBPassword, RAN.eNBSourceCodePath + '/cmake_targets/reconfig.raw', '.')
			if (copyin_res == 0):
				SSH.copyout(self.UEIPAddress, self.UEUserName, self.UEPassword, './reconfig.raw', self.UESourceCodePath + '/cmake_targets/ran_build/build')
		SSH.command('echo "ulimit -c unlimited && ./'+ self.air_interface +' ' + self.Initialize_OAI_UE_args + '" > ./my-lte-uesoftmodem-run' + str(self.UE_instance) + '.sh', '\$', 5)
		SSH.command('chmod 775 ./my-lte-uesoftmodem-run' + str(self.UE_instance) + '.sh', '\$', 5)
		SSH.command('echo ' + self.UEPassword + ' | sudo -S rm -Rf ' + self.UESourceCodePath + '/cmake_targets/ue_' + self.testCase_id + '.log', '\$', 5)
		self.UELogFile = 'ue_' + self.testCase_id + '.log'

		# We are now looping several times to hope we really sync w/ an eNB
		doOutterLoop = True
		outterLoopCounter = 5
		gotSyncStatus = True
		fullSyncStatus = True
		while (doOutterLoop):
			SSH.command('cd ' + self.UESourceCodePath + '/cmake_targets/ran_build/build', '\$', 5)
			SSH.command('echo ' + self.UEPassword + ' | sudo -S rm -Rf ' + self.UESourceCodePath + '/cmake_targets/ue_' + self.testCase_id + '.log', '\$', 5)
			SSH.command('echo $USER; nohup sudo -E ./my-lte-uesoftmodem-run' + str(self.UE_instance) + '.sh' + ' > ' + self.UESourceCodePath + '/cmake_targets/ue_' + self.testCase_id + '.log ' + ' 2>&1 &', self.UEUserName, 5)
			time.sleep(6)
			SSH.command('cd ../..', '\$', 5)
			doLoop = True
			loopCounter = 10
			gotSyncStatus = True
			# the 'got sync' message is for the UE threads synchronization
			while (doLoop):
				loopCounter = loopCounter - 1
				if (loopCounter == 0):
					# Here should never occur
					logging.error('"got sync" message never showed!')
					gotSyncStatus = False
					doLoop = False
					continue
				SSH.command('stdbuf -o0 cat ue_' + self.testCase_id + '.log | egrep --text --color=never -i "wait|sync"', '\$', 4)
				if self.air_interface == 'nr-uesoftmodem':
					result = re.search('Starting sync detection', SSH.getBefore())
				else:
					result = re.search('got sync', SSH.getBefore())
				if result is None:
					time.sleep(10)
				else:
					doLoop = False
					logging.debug('Found "got sync" message!')
			if gotSyncStatus == False:
				# we certainly need to stop the lte-uesoftmodem process if it is still running!
				SSH.command('ps -aux | grep --text --color=never softmodem | grep -v grep', '\$', 4)
				result = re.search('-uesoftmodem', SSH.getBefore())
				if result is not None:
					SSH.command('echo ' + self.UEPassword + ' | sudo -S killall --signal=SIGINT -r *-uesoftmodem', '\$', 4)
					time.sleep(3)
				outterLoopCounter = outterLoopCounter - 1
				if (outterLoopCounter == 0):
					doOutterLoop = False
				continue
			# We are now checking if sync w/ eNB DOES NOT OCCUR
			# Usually during the cell synchronization stage, the UE returns with No cell synchronization message
			# That is the case for LTE
			# In NR case, it's a positive message that will show if synchronization occurs
			doLoop = True
			if self.air_interface == 'nr-uesoftmodem':
				loopCounter = 10
			else:
				# We are now checking if sync w/ eNB DOES NOT OCCUR
				# Usually during the cell synchronization stage, the UE returns with No cell synchronization message
				loopCounter = 10
			while (doLoop):
				loopCounter = loopCounter - 1
				if (loopCounter == 0):
					if self.air_interface == 'nr-uesoftmodem':
						# Here we do have great chances that UE did NOT cell-sync w/ gNB
						doLoop = False
						fullSyncStatus = False
						logging.debug('Never seen the NR-Sync message (Measured Carrier Frequency) --> try again')
						time.sleep(6)
						# Stopping the NR-UE  
						SSH.command('ps -aux | grep --text --color=never softmodem | grep -v grep', '\$', 4)
						result = re.search('nr-uesoftmodem', SSH.getBefore())
						if result is not None:
							SSH.command('echo ' + self.UEPassword + ' | sudo -S killall --signal=SIGINT nr-uesoftmodem', '\$', 4)
						time.sleep(6)
					else:
						# Here we do have a great chance that the UE did cell-sync w/ eNB
						doLoop = False
						doOutterLoop = False
						fullSyncStatus = True
						continue
				SSH.command('stdbuf -o0 cat ue_' + self.testCase_id + '.log | egrep --text --color=never -i "wait|sync|Frequency"', '\$', 4)
				if self.air_interface == 'nr-uesoftmodem':
					# Positive messaging -->
					result = re.search('Measured Carrier Frequency', SSH.getBefore())
					if result is not None:
						doLoop = False
						doOutterLoop = False
						fullSyncStatus = True
					else:
						time.sleep(6)
				else:
					# Negative messaging -->
					result = re.search('No cell synchronization found', SSH.getBefore())
					if result is None:
						time.sleep(6)
					else:
						doLoop = False
						fullSyncStatus = False
						logging.debug('Found: "No cell synchronization" message! --> try again')
						time.sleep(6)
						SSH.command('ps -aux | grep --text --color=never softmodem | grep -v grep', '\$', 4)
						result = re.search('lte-uesoftmodem', SSH.getBefore())
						if result is not None:
							SSH.command('echo ' + self.UEPassword + ' | sudo -S killall --signal=SIGINT lte-uesoftmodem', '\$', 4)
			outterLoopCounter = outterLoopCounter - 1
			if (outterLoopCounter == 0):
				doOutterLoop = False

		if fullSyncStatus and gotSyncStatus:
			doInterfaceCheck = False
			if self.air_interface == 'lte-uesoftmodem':
				result = re.search('--no-L2-connect', str(self.Initialize_OAI_UE_args))
				if result is None:
					doInterfaceCheck = True
			# For the moment, only in explicit noS1 without kernel module (ie w/ tunnel interface)
			if self.air_interface == 'nr-uesoftmodem':
				result = re.search('--noS1 --nokrnmod 1', str(self.Initialize_OAI_UE_args))
				if result is not None:
					doInterfaceCheck = True
			if doInterfaceCheck:
				SSH.command('ifconfig oaitun_ue1', '\$', 4)
				SSH.command('ifconfig oaitun_ue1', '\$', 4)
				# ifconfig output is different between ubuntu 16 and ubuntu 18
648
				result = re.search('inet addr:[0-9]|inet [0-9]', SSH.getBefore())
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
				if result is not None:
					logging.debug('\u001B[1m oaitun_ue1 interface is mounted and configured\u001B[0m')
					tunnelInterfaceStatus = True
				else:
					logging.debug(SSH.getBefore())
					logging.error('\u001B[1m oaitun_ue1 interface is either NOT mounted or NOT configured\u001B[0m')
					tunnelInterfaceStatus = False
				if RAN.eNBmbmsEnables[0]:
					SSH.command('ifconfig oaitun_uem1', '\$', 4)
					result = re.search('inet addr', SSH.getBefore())
					if result is not None:
						logging.debug('\u001B[1m oaitun_uem1 interface is mounted and configured\u001B[0m')
						tunnelInterfaceStatus = tunnelInterfaceStatus and True
					else:
						logging.error('\u001B[1m oaitun_uem1 interface is either NOT mounted or NOT configured\u001B[0m')
						tunnelInterfaceStatus = False
			else:
				tunnelInterfaceStatus = True
		else:
			tunnelInterfaceStatus = True

		SSH.close()
		if fullSyncStatus and gotSyncStatus and tunnelInterfaceStatus:
			HTML.CreateHtmlTestRow(self.air_interface + ' ' + self.Initialize_OAI_UE_args, 'OK', CONST.ALL_PROCESSES_OK, 'OAI UE')
			logging.debug('\u001B[1m Initialize OAI UE Completed\u001B[0m')
			if (self.ADBIPAddress != 'none'):
				self.UEDevices = []
				self.UEDevices.append('OAI-UE')
				self.UEDevicesStatus = []
				self.UEDevicesStatus.append(CONST.UE_STATUS_DETACHED)
		else:
			if self.air_interface == 'lte-uesoftmodem':
				if RAN.eNBmbmsEnables[0]:
					HTML.htmlUEFailureMsg='oaitun_ue1/oaitun_uem1 interfaces are either NOT mounted or NOT configured'
				else:
					HTML.htmlUEFailureMsg='oaitun_ue1 interface is either NOT mounted or NOT configured'
				HTML.CreateHtmlTestRow(self.air_interface + ' ' + self.Initialize_OAI_UE_args, 'KO', CONST.OAI_UE_PROCESS_NO_TUNNEL_INTERFACE, 'OAI UE')
			else:
				HTML.htmlUEFailureMsg='nr-uesoftmodem did NOT synced'
				HTML.CreateHtmlTestRow(self.air_interface + ' ' +  self.Initialize_OAI_UE_args, 'KO', CONST.OAI_UE_PROCESS_COULD_NOT_SYNC, 'OAI UE')
			logging.error('\033[91mInitialize OAI UE Failed! \033[0m')
690
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
691 692

	def checkDevTTYisUnlocked(self):
hardy's avatar
hardy committed
693
		SSH = sshconnection.SSHConnection()
694 695 696
		SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
		count = 0
		while count < 5:
697
			SSH.command('echo ' + self.ADBPassword + ' | sudo -S lsof | grep --colour=never ttyUSB0', '\$', 10)
698 699 700 701 702 703 704 705 706 707 708 709
			result = re.search('picocom', SSH.getBefore())
			if result is None:
				count = 10
			else:
				time.sleep(5)
				count = count + 1
		SSH.close()

	def InitializeCatM(self,HTML):
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
hardy's avatar
hardy committed
710
		SSH = sshconnection.SSHConnection()
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
		SSH.enablePicocomClosure()
		SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
		# dummy call to start a sudo session. The picocom command does NOT handle well the `sudo -S`
		SSH.command('echo ' + self.ADBPassword + ' | sudo -S ls', '\$', 10)
		SSH.command('sudo picocom --baud 921600 --flow n --databits 8 /dev/ttyUSB0', 'Terminal ready', 10)
		time.sleep(1)
		# Calling twice AT to clear all buffers
		SSH.command('AT', 'OK|ERROR', 5)
		SSH.command('AT', 'OK', 5)
		# Doing a power cycle
		SSH.command('AT^RESET', 'SIMSTORE,READY', 15)
		SSH.command('AT', 'OK|ERROR', 5)
		SSH.command('AT', 'OK', 5)
		SSH.command('ATE1', 'OK', 5)
		# Disabling the Radio
		SSH.command('AT+CFUN=0', 'OK', 5)
		logging.debug('\u001B[1m Cellular Functionality disabled\u001B[0m')
		# Checking if auto-attach is enabled
		SSH.command('AT^AUTOATT?', 'OK', 5)
		result = re.search('AUTOATT: (?P<state>[0-9\-]+)', SSH.getBefore())
		if result is not None:
			if result.group('state') is not None:
				autoAttachState = int(result.group('state'))
				if autoAttachState is not None:
					if autoAttachState == 0:
						SSH.command('AT^AUTOATT=1', 'OK', 5)
					logging.debug('\u001B[1m Auto-Attach enabled\u001B[0m')
		else:
			logging.debug('\u001B[1;37;41m Could not check Auto-Attach! \u001B[0m')
		# Force closure of picocom but device might still be locked
		SSH.close()
		SSH.disablePicocomClosure()
		HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)
		self.checkDevTTYisUnlocked()

746
	def TerminateCatM(self,HTML):
747 748 749
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
hardy's avatar
hardy committed
750
		SSH = sshconnection.SSHConnection()
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
		SSH.enablePicocomClosure()
		SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
		# dummy call to start a sudo session. The picocom command does NOT handle well the `sudo -S`
		SSH.command('echo ' + self.ADBPassword + ' | sudo -S ls', '\$', 10)
		SSH.command('sudo picocom --baud 921600 --flow n --databits 8 /dev/ttyUSB0', 'Terminal ready', 10)
		time.sleep(1)
		# Calling twice AT to clear all buffers
		SSH.command('AT', 'OK|ERROR', 5)
		SSH.command('AT', 'OK', 5)
		# Disabling the Radio
		SSH.command('AT+CFUN=0', 'OK', 5)
		logging.debug('\u001B[1m Cellular Functionality disabled\u001B[0m')
		SSH.close()
		SSH.disablePicocomClosure()
		HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)
		self.checkDevTTYisUnlocked()

768
	def AttachCatM(self,HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS):
769 770 771
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
hardy's avatar
hardy committed
772
		SSH = sshconnection.SSHConnection()
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
		SSH.enablePicocomClosure()
		SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
		# dummy call to start a sudo session. The picocom command does NOT handle well the `sudo -S`
		SSH.command('echo ' + self.ADBPassword + ' | sudo -S ls', '\$', 10)
		SSH.command('sudo picocom --baud 921600 --flow n --databits 8 /dev/ttyUSB0', 'Terminal ready', 10)
		time.sleep(1)
		# Calling twice AT to clear all buffers
		SSH.command('AT', 'OK|ERROR', 5)
		SSH.command('AT', 'OK', 5)
		# Enabling the Radio
		SSH.command('AT+CFUN=1', 'SIMSTORE,READY', 5)
		logging.debug('\u001B[1m Cellular Functionality enabled\u001B[0m')
		time.sleep(4)
		# We should check if we register
		count = 0
		attach_cnt = 0
		attach_status = False
		while count < 5:
			SSH.command('AT+CEREG?', 'OK', 5)
			result = re.search('CEREG: 2,(?P<state>[0-9\-]+),', SSH.getBefore())
			if result is not None:
				mDataConnectionState = int(result.group('state'))
				if mDataConnectionState is not None:
					if mDataConnectionState == 1:
						count = 10
						attach_status = True
						result = re.search('CEREG: 2,1,"(?P<networky>[0-9A-Z]+)","(?P<networkz>[0-9A-Z]+)"', SSH.getBefore())
						if result is not None:
							networky = result.group('networky')
							networkz = result.group('networkz')
							logging.debug('\u001B[1m CAT-M module attached to eNB (' + str(networky) + '/' + str(networkz) + ')\u001B[0m')
						else:
							logging.debug('\u001B[1m CAT-M module attached to eNB\u001B[0m')
					else:
						logging.debug('+CEREG: 2,' + str(mDataConnectionState))
						attach_cnt = attach_cnt + 1
			else:
				logging.debug(SSH.getBefore())
				attach_cnt = attach_cnt + 1
			count = count + 1
			time.sleep(1)
		if attach_status:
			SSH.command('AT+CESQ', 'OK', 5)
			result = re.search('CESQ: 99,99,255,255,(?P<rsrq>[0-9]+),(?P<rsrp>[0-9]+)', SSH.getBefore())
			if result is not None:
				nRSRQ = int(result.group('rsrq'))
				nRSRP = int(result.group('rsrp'))
				if (nRSRQ is not None) and (nRSRP is not None):
					logging.debug('    RSRQ = ' + str(-20+(nRSRQ/2)) + ' dB')
					logging.debug('    RSRP = ' + str(-140+nRSRP) + ' dBm')
		SSH.close()
		SSH.disablePicocomClosure()
		html_queue = SimpleQueue()
		self.checkDevTTYisUnlocked()
		if attach_status:
			html_cell = '<pre style="background-color:white">CAT-M module Attachment Completed in ' + str(attach_cnt+4) + ' seconds'
			if (nRSRQ is not None) and (nRSRP is not None):
				html_cell += '\n   RSRQ = ' + str(-20+(nRSRQ/2)) + ' dB'
				html_cell += '\n   RSRP = ' + str(-140+nRSRP) + ' dBm</pre>'
			else:
				html_cell += '</pre>'
			html_queue.put(html_cell)
			HTML.CreateHtmlTestRowQueue('N/A', 'OK', 1, html_queue)
		else:
			logging.error('\u001B[1m CAT-M module Attachment Failed\u001B[0m')
			html_cell = '<pre style="background-color:white">CAT-M module Attachment Failed</pre>'
			html_queue.put(html_cell)
			HTML.CreateHtmlTestRowQueue('N/A', 'KO', 1, html_queue)
841
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
842

843
	def PingCatM(self,HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS):
844 845 846 847 848 849 850 851
		if EPC.IPAddress == '' or EPC.UserName == '' or EPC.Password == '' or EPC.SourceCodePath == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		check_eNB = True
		check_OAI_UE = False
		pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
		if (pStatus < 0):
			HTML.CreateHtmlTestRow(self.ping_args, 'KO', pStatus)
852
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
853 854 855 856
			return
		try:
			statusQueue = SimpleQueue()
			lock = Lock()
hardy's avatar
hardy committed
857
			SSH = sshconnection.SSHConnection()
858 859 860 861 862 863 864
			SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
			SSH.command('cd ' + EPC.SourceCodePath, '\$', 5)
			SSH.command('cd scripts', '\$', 5)
			if re.match('OAI', EPC.Type, re.IGNORECASE):
				logging.debug('Using the OAI EPC HSS: not implemented yet')
				HTML.CreateHtmlTestRow(self.ping_args, 'KO', pStatus)
				HTML.CreateHtmlTabFooter(False)
865
				self.ConditionalExit()
866 867 868 869 870 871 872
			else:
				SSH.command('egrep --color=never "Allocated ipv4 addr" /opt/ltebox/var/log/xGwLog.0', '\$', 5)
				result = re.search('Allocated ipv4 addr: (?P<ipaddr>[0-9\.]+) from Pool', SSH.getBefore())
				if result is not None:
					moduleIPAddr = result.group('ipaddr')
				else:
					HTML.CreateHtmlTestRow(self.ping_args, 'KO', pStatus)
873
					self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
					return
			ping_time = re.findall("-c (\d+)",str(self.ping_args))
			device_id = 'catm'
			ping_status = SSH.command('stdbuf -o0 ping ' + self.ping_args + ' ' + str(moduleIPAddr) + ' 2>&1 | stdbuf -o0 tee ping_' + self.testCase_id + '_' + device_id + '.log', '\$', int(ping_time[0])*1.5)
			# TIMEOUT CASE
			if ping_status < 0:
				message = 'Ping with UE (' + str(moduleIPAddr) + ') crashed due to TIMEOUT!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
				SSH.close()
				self.ping_iperf_wrong_exit(lock, moduleIPAddr, device_id, statusQueue, message)
				return
			result = re.search(', (?P<packetloss>[0-9\.]+)% packet loss, time [0-9\.]+ms', SSH.getBefore())
			if result is None:
				message = 'Packet Loss Not Found!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
				SSH.close()
				self.ping_iperf_wrong_exit(lock, moduleIPAddr, device_id, statusQueue, message)
				return
			packetloss = result.group('packetloss')
			if float(packetloss) == 100:
				message = 'Packet Loss is 100%'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
				SSH.close()
				self.ping_iperf_wrong_exit(lock, moduleIPAddr, device_id, statusQueue, message)
				return
			result = re.search('rtt min\/avg\/max\/mdev = (?P<rtt_min>[0-9\.]+)\/(?P<rtt_avg>[0-9\.]+)\/(?P<rtt_max>[0-9\.]+)\/[0-9\.]+ ms', SSH.getBefore())
			if result is None:
				message = 'Ping RTT_Min RTT_Avg RTT_Max Not Found!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
				SSH.close()
				self.ping_iperf_wrong_exit(lock, moduleIPAddr, device_id, statusQueue, message)
				return
			rtt_min = result.group('rtt_min')
			rtt_avg = result.group('rtt_avg')
			rtt_max = result.group('rtt_max')
			pal_msg = 'Packet Loss : ' + packetloss + '%'
			min_msg = 'RTT(Min)    : ' + rtt_min + ' ms'
			avg_msg = 'RTT(Avg)    : ' + rtt_avg + ' ms'
			max_msg = 'RTT(Max)    : ' + rtt_max + ' ms'
			lock.acquire()
			logging.debug('\u001B[1;37;44m ping result (' + moduleIPAddr + ') \u001B[0m')
			logging.debug('\u001B[1;34m    ' + pal_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + min_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + avg_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + max_msg + '\u001B[0m')
			qMsg = pal_msg + '\n' + min_msg + '\n' + avg_msg + '\n' + max_msg
			packetLossOK = True
			if packetloss is not None:
				if float(packetloss) > float(self.ping_packetloss_threshold):
					qMsg += '\nPacket Loss too high'
					logging.debug('\u001B[1;37;41m Packet Loss too high \u001B[0m')
					packetLossOK = False
				elif float(packetloss) > 0:
					qMsg += '\nPacket Loss is not 0%'
					logging.debug('\u001B[1;30;43m Packet Loss is not 0% \u001B[0m')
			lock.release()
			SSH.close()
			html_cell = '<pre style="background-color:white">CAT-M module\nIP Address  : ' + moduleIPAddr + '\n' + qMsg + '</pre>'
			statusQueue.put(html_cell)
			if (packetLossOK):
				HTML.CreateHtmlTestRowQueue(self.ping_args, 'OK', 1, statusQueue)
			else:
				HTML.CreateHtmlTestRowQueue(self.ping_args, 'KO', 1, statusQueue)
937
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
938 939 940 941 942
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

	def AttachUE_common(self, device_id, statusQueue, lock, idx,COTS_UE):
		try:
hardy's avatar
hardy committed
943
			SSH = sshconnection.SSHConnection()
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			if self.ADBCentralized:
				#RH quick add on to integrate cots control defined by yaml
				#if device Id exists in yaml dictionary, we execute the new procedure defined in cots_ue class
				#otherwise we use the legacy procedure 
				if COTS_UE.Check_Exists(device_id):
					#switch device to Airplane mode OFF (ie Radio ON)
					COTS_UE.Set_Airplane(device_id, 'OFF')
				elif device_id == '84B7N16418004022':
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "su - root -c /data/local/tmp/on"', '\$', 60)
				else:
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell /data/local/tmp/on', '\$', 60)
			else:
				# airplane mode off // radio on
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesOnCmd[idx], '\$', 60)
			time.sleep(2)
			max_count = 45
			count = max_count
			while count > 0:
				if self.ADBCentralized:
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "dumpsys telephony.registry" | grep -m 1 mDataConnectionState', '\$', 15)
				else:
					SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "dumpsys telephony.registry"\' | grep -m 1 mDataConnectionState', '\$', 60)
				result = re.search('mDataConnectionState.*=(?P<state>[0-9\-]+)', SSH.getBefore())
				if result is None:
					logging.debug('\u001B[1;37;41m mDataConnectionState Not Found! \u001B[0m')
					lock.acquire()
					statusQueue.put(-1)
					statusQueue.put(device_id)
					statusQueue.put('mDataConnectionState Not Found!')
					lock.release()
					break
				mDataConnectionState = int(result.group('state'))
				if mDataConnectionState == 2:
					logging.debug('\u001B[1mUE (' + device_id + ') Attach Completed\u001B[0m')
					lock.acquire()
					statusQueue.put(max_count - count)
					statusQueue.put(device_id)
					statusQueue.put('Attach Completed')
					lock.release()
					break
				count = count - 1
				if count == 15 or count == 30:
					logging.debug('\u001B[1;30;43m Retry UE (' + device_id + ') Flight Mode Off \u001B[0m')
					if self.ADBCentralized:
					#RH quick add on to intgrate cots control defined by yaml
					#if device id exists in yaml dictionary, we execute the new procedure defined in cots_ue class
					#otherwise we use the legacy procedure
						if COTS_UE.Check_Exists(device_id):
							#switch device to Airplane mode ON  (ie Radio OFF)
							COTS_UE.Set_Airplane(device_id, 'ON')
						elif device_id == '84B7N16418004022':
							SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "su - root -c /data/local/tmp/off"', '\$', 60)
						else:
							SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell /data/local/tmp/off', '\$', 60)
					else:
						SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesOffCmd[idx], '\$', 60)
					time.sleep(0.5)
					if self.ADBCentralized:
					#RH quick add on to integrate cots control defined by yaml
					#if device id exists in yaml dictionary, we execute the new procedre defined incots_ue class
					#otherwise we use the legacy procedure
						if COTS_UE.Check_Exists(device_id):
							#switch device to Airplane mode OFF (ie Radio ON)
							COTS_UE.Set_Airplane(device_id, 'OFF')
						elif device_id == '84B7N16418004022':
							SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "su - root -c /data/local/tmp/on"', '\$', 60)
						else:
							SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell /data/local/tmp/on', '\$', 60)
					else:
						SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesOnCmd[idx], '\$', 60)
					time.sleep(0.5)
				logging.debug('\u001B[1mWait UE (' + device_id + ') a second until mDataConnectionState=2 (' + str(max_count-count) + ' times)\u001B[0m')
				time.sleep(1)
			if count == 0:
				logging.debug('\u001B[1;37;41m UE (' + device_id + ') Attach Failed \u001B[0m')
				lock.acquire()
				statusQueue.put(-1)
				statusQueue.put(device_id)
				statusQueue.put('Attach Failed')
				lock.release()
			SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

1029
	def AttachUE(self,HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS):
1030 1031 1032 1033 1034 1035 1036 1037 1038
		if self.ue_id=='':#no ID specified, then it is a COTS controlled by ADB
			if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
				HELP.GenericHelp(CONST.Version)
				sys.exit('Insufficient Parameter')
			check_eNB = True
			check_OAI_UE = False
			pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
			if (pStatus < 0):
				HTML.CreateHtmlTestRow('N/A', 'KO', pStatus)
1039
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
				return
			multi_jobs = []
			status_queue = SimpleQueue()
			lock = Lock()
			nb_ue_to_connect = 0
			for device_id in self.UEDevices:
				if (self.nbMaxUEtoAttach == -1) or (nb_ue_to_connect < self.nbMaxUEtoAttach):
					self.UEDevicesStatus[nb_ue_to_connect] = CONST.UE_STATUS_ATTACHING
					p = Process(target = self.AttachUE_common, args = (device_id, status_queue, lock,nb_ue_to_connect,COTS_UE,))
					p.daemon = True
					p.start()
					multi_jobs.append(p)
				nb_ue_to_connect = nb_ue_to_connect + 1
			for job in multi_jobs:
				job.join()
1055

1056 1057
			if (status_queue.empty()):
				HTML.CreateHtmlTestRow('N/A', 'KO', CONST.ALL_PROCESSES_OK)
1058
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1059
				return
1060
			else:
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
				attach_status = True
				html_queue = SimpleQueue()
				while (not status_queue.empty()):
					count = status_queue.get()
					if (count < 0):
						attach_status = False
					device_id = status_queue.get()
					message = status_queue.get()
					if (count < 0):
						html_cell = '<pre style="background-color:white">UE (' + device_id + ')\n' + message + '</pre>'
					else:
						html_cell = '<pre style="background-color:white">UE (' + device_id + ')\n' + message + ' in ' + str(count + 2) + ' seconds</pre>'
					html_queue.put(html_cell)
				if (attach_status):
					cnt = 0
					while cnt < len(self.UEDevices):
						if self.UEDevicesStatus[cnt] == CONST.UE_STATUS_ATTACHING:
							self.UEDevicesStatus[cnt] = CONST.UE_STATUS_ATTACHED
						cnt += 1
					HTML.CreateHtmlTestRowQueue('N/A', 'OK', len(self.UEDevices), html_queue)
					result = re.search('T_stdout', str(RAN.Initialize_eNB_args))
					if result is not None:
						logging.debug('Waiting 5 seconds to fill up record file')
						time.sleep(5)
				else:
					HTML.CreateHtmlTestRowQueue('N/A', 'KO', len(self.UEDevices), html_queue)
1087
					self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1088 1089 1090 1091 1092

		else: #if an ID is specified, it is a module from the yaml infrastructure file
			#Attention, as opposed to InitializeUE, the connect manager process is not checked as it is supposed to be active already
			#only 1- module wakeup, 2- check IP address
			Module_UE = cls_module_ue.Module_UE(InfraUE.ci_ue_infra[self.ue_id])
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
			status = -1
			cnt = 0
			while cnt < 4:
				Module_UE.Command("wup")
				logging.debug("Waiting for IP address to be assigned")
				time.sleep(20)
				logging.debug("Retrieve IP address")
				status=Module_UE.GetModuleIPAddress()
				if status==0:
					cnt = 10
				else:
					cnt += 1
					Module_UE.Command("detach")
					time.sleep(20)

			if cnt == 10 and status == 0:
1109 1110
				HTML.CreateHtmlTestRow(Module_UE.UEIPAddress, 'OK', CONST.ALL_PROCESSES_OK)	
				logging.debug('UE IP addresss : '+ Module_UE.UEIPAddress)
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
				#execute additional commands from yaml file after UE attach
				SSH = sshconnection.SSHConnection()
				SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
				if hasattr(Module_UE,'StartCommands'):
					for startcommand in Module_UE.StartCommands:
						cmd = 'echo ' + Module_UE.HostPassword + ' | ' + startcommand
						SSH.command(cmd,'\$',5)
				SSH.close()
				#check that the MTU is as expected / requested
				Module_UE.CheckModuleMTU()
1121 1122
			else: #status==-1 failed to retrieve IP address
				HTML.CreateHtmlTestRow('N/A', 'KO', CONST.UE_IP_ADDRESS_ISSUE)
1123
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1124
				return					
1125 1126 1127

	def DetachUE_common(self, device_id, idx,COTS_UE):
		try:
hardy's avatar
hardy committed
1128
			SSH = sshconnection.SSHConnection()
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			if self.ADBCentralized:
				#RH quick add on to  integrate cots control defined by yaml
				#if device id exists in yaml dictionary, we execute the new procedure defined in cots_ue class
				#otherwise we use the legacy procedure
				if COTS_UE.Check_Exists(device_id):
					#switch device to Airplane mode ON (ie Radio OFF)
					COTS_UE.Set_Airplane(device_id,'ON')
				elif device_id == '84B7N16418004022':
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "su - root -c /data/local/tmp/off"', '\$', 60)
				else:
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell /data/local/tmp/off', '\$', 60)
			else:
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesOffCmd[idx], '\$', 60)
			logging.debug('\u001B[1mUE (' + device_id + ') Detach Completed\u001B[0m')
			SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

1148
	def DetachUE(self,HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS):
1149 1150 1151 1152 1153 1154 1155 1156 1157
		if self.ue_id=='':#no ID specified, then it is a COTS controlled by ADB
			if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
				HELP.GenericHelp(CONST.Version)
				sys.exit('Insufficient Parameter')
			check_eNB = True
			check_OAI_UE = False
			pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
			if (pStatus < 0):
				HTML.CreateHtmlTestRow('N/A', 'KO', pStatus)
1158
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
				return
			multi_jobs = []
			cnt = 0
			for device_id in self.UEDevices:
				self.UEDevicesStatus[cnt] = CONST.UE_STATUS_DETACHING
				p = Process(target = self.DetachUE_common, args = (device_id,cnt,COTS_UE,))
				p.daemon = True
				p.start()
				multi_jobs.append(p)
				cnt += 1
			for job in multi_jobs:
				job.join()
			HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)
			result = re.search('T_stdout', str(RAN.Initialize_eNB_args))
			if result is not None:
				logging.debug('Waiting 5 seconds to fill up record file')
				time.sleep(5)
			cnt = 0
			while cnt < len(self.UEDevices):
				self.UEDevicesStatus[cnt] = CONST.UE_STATUS_DETACHED
				cnt += 1
		else:#if an ID is specified, it is a module from the yaml infrastructure file
			Module_UE = cls_module_ue.Module_UE(InfraUE.ci_ue_infra[self.ue_id])
hardy's avatar
hardy committed
1182
			Module_UE.Command("detach")
1183
			HTML.CreateHtmlTestRow('NA', 'OK', CONST.ALL_PROCESSES_OK)	
hardy's avatar
hardy committed
1184 1185
				
							
1186 1187 1188

	def RebootUE_common(self, device_id):
		try:
hardy's avatar
hardy committed
1189
			SSH = sshconnection.SSHConnection()
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			previousmDataConnectionStates = []
			# Save mDataConnectionState
			SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell dumpsys telephony.registry | grep mDataConnectionState', '\$', 15)
			SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell dumpsys telephony.registry | grep mDataConnectionState', '\$', 15)
			result = re.search('mDataConnectionState.*=(?P<state>[0-9\-]+)', SSH.getBefore())
			if result is None:
				logging.debug('\u001B[1;37;41m mDataConnectionState Not Found! \u001B[0m')
				sys.exit(1)
			previousmDataConnectionStates.append(int(result.group('state')))
			# Reboot UE
			SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell reboot', '\$', 10)
			time.sleep(60)
			previousmDataConnectionState = previousmDataConnectionStates.pop(0)
			count = 180
			while count > 0:
				count = count - 1
				SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell dumpsys telephony.registry | grep mDataConnectionState', '\$', 15)
				result = re.search('mDataConnectionState.*=(?P<state>[0-9\-]+)', SSH.getBefore())
				if result is None:
					mDataConnectionState = None
				else:
					mDataConnectionState = int(result.group('state'))
					logging.debug('mDataConnectionState = ' + result.group('state'))
				if mDataConnectionState is None or (previousmDataConnectionState == 2 and mDataConnectionState != 2):
					logging.debug('\u001B[1mWait UE (' + device_id + ') a second until reboot completion (' + str(180-count) + ' times)\u001B[0m')
					time.sleep(1)
				else:
					logging.debug('\u001B[1mUE (' + device_id + ') Reboot Completed\u001B[0m')
					break
			if count == 0:
				logging.debug('\u001B[1;37;41m UE (' + device_id + ') Reboot Failed \u001B[0m')
				sys.exit(1)
			SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

	def RebootUE(self,HTML,RAN,EPC):
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		check_eNB = True
		check_OAI_UE = False
		pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
		if (pStatus < 0):
			HTML.CreateHtmlTestRow('N/A', 'KO', pStatus)
			HTML.CreateHtmlTabFooter(False)
1237
			self.ConditionalExit()
1238 1239
		multi_jobs = []
		for device_id in self.UEDevices:
hardy's avatar
hardy committed
1240
			p = Process(target = self.RebootUE_common, args = (device_id,))
1241 1242 1243 1244 1245 1246 1247 1248 1249
			p.daemon = True
			p.start()
			multi_jobs.append(p)
		for job in multi_jobs:
			job.join()
		HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)

	def DataDisableUE_common(self, device_id, idx):
		try:
hardy's avatar
hardy committed
1250
			SSH = sshconnection.SSHConnection()
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			# disable data service
			if self.ADBCentralized:
				SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "svc data disable"', '\$', 60)
			else:
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "svc data disable"\'', '\$', 60)
			logging.debug('\u001B[1mUE (' + device_id + ') Disabled Data Service\u001B[0m')
			SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

	def DataDisableUE(self,HTML):
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		multi_jobs = []
		i = 0
		for device_id in self.UEDevices:
1269
			p = Process(target = self.DataDisableUE_common, args = (device_id,i,))
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
			p.daemon = True
			p.start()
			multi_jobs.append(p)
			i += 1
		for job in multi_jobs:
			job.join()
		HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)

	def DataEnableUE_common(self, device_id, idx):
		try:
hardy's avatar
hardy committed
1280
			SSH = sshconnection.SSHConnection()
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			# enable data service
			if self.ADBCentralized:
				SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "svc data enable"', '\$', 60)
			else:
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "svc data enable"\'', '\$', 60)
			logging.debug('\u001B[1mUE (' + device_id + ') Enabled Data Service\u001B[0m')
			SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

	def DataEnableUE(self,HTML):
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		multi_jobs = []
		i = 0
		for device_id in self.UEDevices:
hardy's avatar
hardy committed
1299
			p = Process(target = self.DataEnableUE_common, args = (device_id,i,))
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
			p.daemon = True
			p.start()
			multi_jobs.append(p)
			i += 1
		for job in multi_jobs:
			job.join()
		HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)

	def GetAllUEDevices(self, terminate_ue_flag):
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
hardy's avatar
hardy committed
1312
		SSH = sshconnection.SSHConnection()
1313 1314 1315 1316
		SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
		if self.ADBCentralized:
			SSH.command('adb devices', '\$', 15)
			self.UEDevices = re.findall("\\\\r\\\\n([A-Za-z0-9]+)\\\\tdevice",SSH.getBefore())
1317 1318 1319
			#report number and id of devices found
			msg = "UEDevices found by GetAllUEDevices : " + " ".join(self.UEDevices)
			logging.debug(msg)
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
			SSH.close()
		else:
			if (os.path.isfile('./phones_list.txt')):
				os.remove('./phones_list.txt')
			SSH.command('ls /etc/*/phones*.txt', '\$', 5)
			result = re.search('/etc/ci/phones_list.txt', SSH.getBefore())
			SSH.close()
			if (result is not None) and (len(self.UEDevices) == 0):
				SSH.copyin(self.ADBIPAddress, self.ADBUserName, self.ADBPassword, '/etc/ci/phones_list.txt', '.')
				if (os.path.isfile('./phones_list.txt')):
					phone_list_file = open('./phones_list.txt', 'r')
					for line in phone_list_file.readlines():
						line = line.strip()
						result = re.search('^#', line)
						if result is not None:
							continue
						comma_split = line.split(",")
						self.UEDevices.append(comma_split[0])
						self.UEDevicesRemoteServer.append(comma_split[1])
						self.UEDevicesRemoteUser.append(comma_split[2])
						self.UEDevicesOffCmd.append(comma_split[3])
						self.UEDevicesOnCmd.append(comma_split[4])
						self.UEDevicesRebootCmd.append(comma_split[5])
					phone_list_file.close()

1345 1346
		# better handling of the case when no UE detected
		# Sys-exit is now dealt by the calling function
1347 1348 1349
		if terminate_ue_flag == True:
			if len(self.UEDevices) == 0:
				logging.debug('\u001B[1;37;41m UE Not Found! \u001B[0m')
1350
				return False
1351 1352 1353 1354 1355
		if len(self.UEDevicesStatus) == 0:
			cnt = 0
			while cnt < len(self.UEDevices):
				self.UEDevicesStatus.append(CONST.UE_STATUS_DETACHED)
				cnt += 1
1356
		return True
1357 1358 1359 1360 1361

	def GetAllCatMDevices(self, terminate_ue_flag):
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
hardy's avatar
hardy committed
1362
		SSH = sshconnection.SSHConnection()
1363 1364
		SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
		if self.ADBCentralized:
1365
			SSH.command('lsusb | egrep --colour=never "Future Technology Devices International, Ltd FT2232C" | sed -e "s#:.*##" -e "s# #_#g"', '\$', 15)
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
			#self.CatMDevices = re.findall("\\\\r\\\\n([A-Za-z0-9_]+)",SSH.getBefore())
			self.CatMDevices = re.findall("\\\\r\\\\n([A-Za-z0-9_]+)",SSH.getBefore())
		else:
			if (os.path.isfile('./modules_list.txt')):
				os.remove('./modules_list.txt')
			SSH.command('ls /etc/*/modules*.txt', '\$', 5)
			result = re.search('/etc/ci/modules_list.txt', SSH.getBefore())
			SSH.close()
			if result is not None:
				logging.debug('Found a module list file on ADB server')
		if terminate_ue_flag == True:
			if len(self.CatMDevices) == 0:
				logging.debug('\u001B[1;37;41m CAT-M UE Not Found! \u001B[0m')
				sys.exit(1)
		SSH.close()

	def CheckUEStatus_common(self, lock, device_id, statusQueue, idx):
		try:
hardy's avatar
hardy committed
1384
			SSH = sshconnection.SSHConnection()
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			if self.ADBCentralized:
				SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "dumpsys telephony.registry"', '\$', 15)
			else:
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "dumpsys telephony.registry"\'', '\$', 60)
			result = re.search('mServiceState=(?P<serviceState>[0-9]+)', SSH.getBefore())
			serviceState = 'Service State: UNKNOWN'
			if result is not None:
				lServiceState = int(result.group('serviceState'))
				if lServiceState == 3:
					serviceState = 'Service State: RADIO_POWERED_OFF'
				if lServiceState == 1:
					serviceState = 'Service State: OUT_OF_SERVICE'
				if lServiceState == 0:
					serviceState = 'Service State: IN_SERVICE'
				if lServiceState == 2:
					serviceState = 'Service State: EMERGENCY_ONLY'
			result = re.search('mDataConnectionState=(?P<dataConnectionState>[0-9]+)', SSH.getBefore())
			dataConnectionState = 'Data State:    UNKNOWN'
			if result is not None:
				lDataConnectionState = int(result.group('dataConnectionState'))
				if lDataConnectionState == 0:
					dataConnectionState = 'Data State:    DISCONNECTED'
				if lDataConnectionState == 1:
					dataConnectionState = 'Data State:    CONNECTING'
				if lDataConnectionState == 2:
					dataConnectionState = 'Data State:    CONNECTED'
				if lDataConnectionState == 3:
					dataConnectionState = 'Data State:    SUSPENDED'
			result = re.search('mDataConnectionReason=(?P<dataConnectionReason>[0-9a-zA-Z_]+)', SSH.getBefore())
1415 1416
			time.sleep(1)
			SSH.close()
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
			dataConnectionReason = 'Data Reason:   UNKNOWN'
			if result is not None:
				dataConnectionReason = 'Data Reason:   ' + result.group('dataConnectionReason')
			lock.acquire()
			logging.debug('\u001B[1;37;44m Status Check (' + str(device_id) + ') \u001B[0m')
			logging.debug('\u001B[1;34m    ' + serviceState + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + dataConnectionState + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + dataConnectionReason + '\u001B[0m')
			statusQueue.put(0)
			statusQueue.put(device_id)
			qMsg = serviceState + '\n' + dataConnectionState + '\n' + dataConnectionReason
			statusQueue.put(qMsg)
			lock.release()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

1433
	def CheckStatusUE(self,HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS):
1434 1435 1436 1437 1438 1439 1440 1441 1442
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		check_eNB = True
		check_OAI_UE = False
		pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
		if (pStatus < 0):
			HTML.CreateHtmlTestRow('N/A', 'KO', pStatus)
			HTML.CreateHtmlTabFooter(False)
1443
			self.ConditionalExit()
1444 1445 1446 1447 1448
		multi_jobs = []
		lock = Lock()
		status_queue = SimpleQueue()
		i = 0
		for device_id in self.UEDevices:
hardy's avatar
hardy committed
1449
			p = Process(target = self.CheckUEStatus_common, args = (lock,device_id,status_queue,i,))
1450 1451 1452 1453 1454 1455
			p.daemon = True
			p.start()
			multi_jobs.append(p)
			i += 1
		for job in multi_jobs:
			job.join()
1456
		if (RAN.flexranCtrlInstalled and RAN.flexranCtrlStarted) or RAN.flexranCtrlDeployed:
hardy's avatar
hardy committed
1457
			SSH = sshconnection.SSHConnection()
1458
			SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
1459 1460 1461
			SSH.command('cd ' + EPC.SourceCodePath + '/scripts', '\$', 5)
			SSH.command('curl http://' + RAN.flexranCtrlIpAddress + ':9999/stats | jq \'.\' > check_status_' + self.testCase_id + '.log 2>&1', '\$', 5)
			SSH.command('cat check_status_' + self.testCase_id + '.log | jq \'.eNB_config[0].UE\' | grep -c rnti | sed -e "s#^#Nb Connected UE = #"', '\$', 5)
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
			result = re.search('Nb Connected UE = (?P<nb_ues>[0-9]+)', SSH.getBefore())
			passStatus = True
			if result is not None:
				nb_ues = int(result.group('nb_ues'))
				htmlOptions = 'Nb Connected UE(s) to eNB = ' + str(nb_ues)
				logging.debug('\u001B[1;37;44m ' + htmlOptions + ' \u001B[0m')
				if self.expectedNbOfConnectedUEs > -1:
					if nb_ues != self.expectedNbOfConnectedUEs:
						passStatus = False
			else:
				htmlOptions = 'N/A'
			SSH.close()
		else:
			passStatus = True
			htmlOptions = 'N/A'

		if (status_queue.empty()):
			HTML.CreateHtmlTestRow(htmlOptions, 'KO', CONST.ALL_PROCESSES_OK)
1480
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
		else:
			check_status = True
			html_queue = SimpleQueue()
			while (not status_queue.empty()):
				count = status_queue.get()
				if (count < 0):
					check_status = False
				device_id = status_queue.get()
				message = status_queue.get()
				html_cell = '<pre style="background-color:white">UE (' + device_id + ')\n' + message + '</pre>'
				html_queue.put(html_cell)
			if check_status and passStatus:
				HTML.CreateHtmlTestRowQueue(htmlOptions, 'OK', len(self.UEDevices), html_queue)
			else:
				HTML.CreateHtmlTestRowQueue(htmlOptions, 'KO', len(self.UEDevices), html_queue)
1496
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1497 1498

	def GetAllUEIPAddresses(self):
1499
		SSH = sshconnection.SSHConnection()
1500 1501 1502 1503 1504 1505 1506 1507 1508
		if self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		ue_ip_status = 0
		self.UEIPAddresses = []
		if (len(self.UEDevices) == 1) and (self.UEDevices[0] == 'OAI-UE'):
			if self.UEIPAddress == '' or self.UEUserName == '' or self.UEPassword == '' or self.UESourceCodePath == '':
				HELP.GenericHelp(CONST.Version)
				sys.exit('Insufficient Parameter')
1509

1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
			SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
			SSH.command('ifconfig oaitun_ue1', '\$', 4)
			result = re.search('inet addr:(?P<ueipaddress>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)|inet (?P<ueipaddress2>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)', SSH.getBefore())
			if result is not None:
				if result.group('ueipaddress') is not None:
					UE_IPAddress = result.group('ueipaddress')
				else:
					UE_IPAddress = result.group('ueipaddress2')
				logging.debug('\u001B[1mUE (' + self.UEDevices[0] + ') IP Address is ' + UE_IPAddress + '\u001B[0m')
				self.UEIPAddresses.append(UE_IPAddress)
			else:
				logging.debug('\u001B[1;37;41m UE IP Address Not Found! \u001B[0m')
				ue_ip_status -= 1
			SSH.close()
			return ue_ip_status
		SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
		idx = 0
		for device_id in self.UEDevices:
			if self.UEDevicesStatus[idx] != CONST.UE_STATUS_ATTACHED:
				idx += 1
				continue
			count = 0
			while count < 4:
				if self.ADBCentralized:
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "ip addr show | grep rmnet"', '\$', 15)
				else:
					SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "ip addr show | grep rmnet"\'', '\$', 60)
				result = re.search('inet (?P<ueipaddress>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/[0-9]+[0-9a-zA-Z\.\s]+', SSH.getBefore())
				if result is None:
					logging.debug('\u001B[1;37;41m UE IP Address Not Found! \u001B[0m')
					time.sleep(1)
					count += 1
				else:
					count = 10
			if count < 9:
				ue_ip_status -= 1
				continue
			UE_IPAddress = result.group('ueipaddress')
			logging.debug('\u001B[1mUE (' + device_id + ') IP Address is ' + UE_IPAddress + '\u001B[0m')
			for ueipaddress in self.UEIPAddresses:
				if ueipaddress == UE_IPAddress:
					logging.debug('\u001B[1mUE (' + device_id + ') IP Address ' + UE_IPAddress + ': has already been allocated to another device !' + '\u001B[0m')
					ue_ip_status -= 1
					continue
			self.UEIPAddresses.append(UE_IPAddress)
			idx += 1
		SSH.close()
		return ue_ip_status

	def ping_iperf_wrong_exit(self, lock, UE_IPAddress, device_id, statusQueue, message):
		lock.acquire()
		statusQueue.put(-1)
		statusQueue.put(device_id)
		statusQueue.put(UE_IPAddress)
		statusQueue.put(message)
		lock.release()

hardy's avatar
hardy committed
1567
	def Ping_common(self, lock, UE_IPAddress, device_id, statusQueue,EPC, Module_UE,RAN):
1568
		try:
hardy's avatar
hardy committed
1569
			SSH = sshconnection.SSHConnection()
1570 1571 1572
			# Launch ping on the EPC side (true for ltebox and old open-air-cn)
			# But for OAI-Rel14-CUPS, we launch from python executor
			launchFromEpc = True
1573
			launchFromModule = False
1574 1575
			if re.match('OAI-Rel14-CUPS', EPC.Type, re.IGNORECASE):
				launchFromEpc = False
1576 1577 1578 1579 1580
			#if module, ping from module to EPC
			if self.ue_id!='':
				launchFromEpc = False
				launchfromModule = True

1581 1582 1583 1584 1585 1586
			ping_time = re.findall("-c (\d+)",str(self.ping_args))

			if launchFromEpc:
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				SSH.command('cd ' + EPC.SourceCodePath, '\$', 5)
				SSH.command('cd scripts', '\$', 5)
1587 1588
				# In case of a docker-based deployment, we need to ping from the trf-gen container
				launchFromTrfContainer = False
hardy's avatar
hardy committed
1589
				if (re.match('OAI-Rel14-Docker', EPC.Type, re.IGNORECASE)) or (re.match('OAICN5G', EPC.Type, re.IGNORECASE)):
1590 1591
					launchFromTrfContainer = True
				if launchFromTrfContainer:
Remi Hardy's avatar
Remi Hardy committed
1592
					ping_status = SSH.command('docker exec -it prod-trf-gen /bin/bash -c "ping ' + self.ping_args + ' ' + UE_IPAddress + '" 2>&1 | tee ping_' + self.testCase_id + '_' + device_id + '.log', '\$', int(ping_time[0])*1.5)				
1593 1594
				else:
					ping_status = SSH.command('stdbuf -o0 ping ' + self.ping_args + ' ' + UE_IPAddress + ' 2>&1 | stdbuf -o0 tee ping_' + self.testCase_id + '_' + device_id + '.log', '\$', int(ping_time[0])*1.5)
hardy's avatar
hardy committed
1595
				ping_log_file='ping_' + self.testCase_id + '_' + device_id + '.log'
Remi Hardy's avatar
Remi Hardy committed
1596 1597
				#copy the ping log file to have it locally for analysis (ping stats)
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, EPC.SourceCodePath + '/scripts/ping_' + self.testCase_id + '_' + device_id + '.log', '.')				
1598
			else:
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
				if launchfromModule == False:
					#ping log file is on the python executor
					cmd = 'ping ' + self.ping_args + ' ' + UE_IPAddress + ' 2>&1 > ping_' + self.testCase_id + '_' + device_id + '.log' 
					message = cmd + '\n'
					logging.debug(cmd)
					ret = subprocess.run(cmd, shell=True)
					ping_status = ret.returncode
					#copy the ping log file to an other folder for log collection (source and destination are EPC)
					SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'ping_' + self.testCase_id + '_' + device_id + '.log', EPC.SourceCodePath + '/scripts')
                	#copy the ping log file to have it locally for analysis (ping stats)
					logging.debug(EPC.SourceCodePath + 'ping_' + self.testCase_id + '_' + device_id + '.log')
					SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, EPC.SourceCodePath  +'/scripts/ping_' + self.testCase_id + '_' + device_id + '.log', '.')

					SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
					#cat is executed on EPC
					SSH.command('cat ' + EPC.SourceCodePath + '/scripts/ping_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
hardy's avatar
hardy committed
1615
					ping_log_file='/scripts/ping_' + self.testCase_id + '_' + device_id + '.log'
1616 1617
				else: #launch from Module
					SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
1618 1619 1620
					#target address is different depending on EPC type
					if re.match('OAI-Rel14-Docker', EPC.Type, re.IGNORECASE):
						Target = EPC.MmeIPAddress
hardy's avatar
hardy committed
1621
					elif re.match('OAICN5G', EPC.Type, re.IGNORECASE):
1622
						Target = EPC.MmeIPAddress
1623 1624
					else:
						Target = EPC.IPAddress
1625
					#ping from module NIC rather than IP address to make sure round trip is over the air	
1626
					cmd = 'ping -I ' + Module_UE.UENetwork  + ' ' + self.ping_args + ' ' +  Target  + ' 2>&1 > ping_' + self.testCase_id + '_' + self.ue_id + '.log' 
1627 1628 1629 1630 1631 1632
					SSH.command(cmd,'\$',int(ping_time[0])*1.5)
					#copy the ping log file to have it locally for analysis (ping stats)
					SSH.copyin(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword, 'ping_' + self.testCase_id + '_' + self.ue_id + '.log', '.')

					#cat is executed locally 
					SSH.command('cat ping_' + self.testCase_id + '_' + self.ue_id + '.log', '\$', 5)
1633
					ping_log_file='ping_' + self.testCase_id + '_' + self.ue_id + '.log'
1634
					ping_status=0
Remi Hardy's avatar
Remi Hardy committed
1635

1636 1637 1638 1639 1640 1641 1642
			# TIMEOUT CASE
			if ping_status < 0:
				message = 'Ping with UE (' + str(UE_IPAddress) + ') crashed due to TIMEOUT!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
				SSH.close()
				self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, message)
				return
Remi Hardy's avatar
Remi Hardy committed
1643
			#search is done on cat result
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
			result = re.search(', (?P<packetloss>[0-9\.]+)% packet loss, time [0-9\.]+ms', SSH.getBefore())
			if result is None:
				message = 'Packet Loss Not Found!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
				SSH.close()
				self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, message)
				return
			packetloss = result.group('packetloss')
			if float(packetloss) == 100:
				message = 'Packet Loss is 100%'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
				SSH.close()
				self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, message)
				return
			result = re.search('rtt min\/avg\/max\/mdev = (?P<rtt_min>[0-9\.]+)\/(?P<rtt_avg>[0-9\.]+)\/(?P<rtt_max>[0-9\.]+)\/[0-9\.]+ ms', SSH.getBefore())
			if result is None:
				message = 'Ping RTT_Min RTT_Avg RTT_Max Not Found!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
				SSH.close()
				self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, message)
				return
			rtt_min = result.group('rtt_min')
			rtt_avg = result.group('rtt_avg')
			rtt_max = result.group('rtt_max')
			pal_msg = 'Packet Loss : ' + packetloss + '%'
			min_msg = 'RTT(Min)    : ' + rtt_min + ' ms'
			avg_msg = 'RTT(Avg)    : ' + rtt_avg + ' ms'
			max_msg = 'RTT(Max)    : ' + rtt_max + ' ms'
1672

1673 1674 1675 1676 1677 1678
			lock.acquire()
			logging.debug('\u001B[1;37;44m ping result (' + UE_IPAddress + ') \u001B[0m')
			logging.debug('\u001B[1;34m    ' + pal_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + min_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + avg_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + max_msg + '\u001B[0m')
Remi Hardy's avatar
Remi Hardy committed
1679 1680

			#adding extra ping stats from local file
1681
			#ping_log_file variable is defined above in this function, depending on device/ue
Remi Hardy's avatar
Remi Hardy committed
1682
			logging.debug('Analyzing Ping log file : ' + os.getcwd() + '/' + ping_log_file)
hardy's avatar
hardy committed
1683
			ping_stat=GetPingTimeAnalysis(RAN,ping_log_file,self.ping_rttavg_threshold)
Remi Hardy's avatar
Remi Hardy committed
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
			ping_stat_msg=''
			if (ping_stat!=-1) and (len(ping_stat)!=0):
				ping_stat_msg+='Ping stats before removing largest value : \n'
				ping_stat_msg+='RTT(Min)    : ' + str("{:.2f}".format(ping_stat['min_0'])) + 'ms \n'
				ping_stat_msg+='RTT(Mean)   : ' + str("{:.2f}".format(ping_stat['mean_0'])) + 'ms \n'
				ping_stat_msg+='RTT(Median) : ' + str("{:.2f}".format(ping_stat['median_0'])) + 'ms \n'
				ping_stat_msg+='RTT(Max)    : ' + str("{:.2f}".format(ping_stat['max_0'])) + 'ms \n'
				ping_stat_msg+='Max Index   : ' + str(ping_stat['max_loc']) + '\n'
				ping_stat_msg+='Ping stats after removing largest value : \n'
				ping_stat_msg+='RTT(Min)    : ' + str("{:.2f}".format(ping_stat['min_1'])) + 'ms \n'
				ping_stat_msg+='RTT(Mean)   : ' + str("{:.2f}".format(ping_stat['mean_1'])) + 'ms \n'
				ping_stat_msg+='RTT(Median) : ' + str("{:.2f}".format(ping_stat['median_1'])) + 'ms \n'
				ping_stat_msg+='RTT(Max)    : ' + str("{:.2f}".format(ping_stat['max_1'])) + 'ms \n'

			#building html message
1699 1700 1701
			qMsg = pal_msg + '\n' + min_msg + '\n' + avg_msg + '\n' + max_msg + '\n'  + ping_stat_msg

			#checking packet loss compliance
1702 1703 1704 1705
			packetLossOK = True
			if packetloss is not None:
				if float(packetloss) > float(self.ping_packetloss_threshold):
					qMsg += '\nPacket Loss too high'
1706
					logging.debug('\u001B[1;37;41m Packet Loss too high; Target: '+ self.ping_packetloss_threshold + '%\u001B[0m')
1707 1708 1709 1710
					packetLossOK = False
				elif float(packetloss) > 0:
					qMsg += '\nPacket Loss is not 0%'
					logging.debug('\u001B[1;30;43m Packet Loss is not 0% \u001B[0m')
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721

			#checking RTT avg compliance
			rttavgOK = True
			if self.ping_rttavg_threshold != '':
				if float(rtt_avg)>float(self.ping_rttavg_threshold):
					ping_rttavg_error_msg = 'RTT(Avg) too high: ' + rtt_avg + ' ms; Target: '+ self.ping_rttavg_threshold+ ' ms'
					qMsg += '\n'+ping_rttavg_error_msg
					logging.debug('\u001B[1;37;41m'+ ping_rttavg_error_msg +' \u001B[0m')
					rttavgOK = False

			if packetLossOK and rttavgOK:
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
				statusQueue.put(0)
			else:
				statusQueue.put(-1)
			statusQueue.put(device_id)
			statusQueue.put(UE_IPAddress)
			statusQueue.put(qMsg)
			lock.release()
			SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

1733
	def PingNoS1_wrong_exit(self, qMsg,HTML):
1734 1735 1736 1737 1738
		html_queue = SimpleQueue()
		html_cell = '<pre style="background-color:white">OAI UE ping result\n' + qMsg + '</pre>'
		html_queue.put(html_cell)
		HTML.CreateHtmlTestRowQueue(self.ping_args, 'KO', len(self.UEDevices), html_queue)

1739
	def PingNoS1(self,HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS):
hardy's avatar
hardy committed
1740
		SSH=sshconnection.SSHConnection()
1741 1742 1743 1744 1745
		check_eNB = True
		check_OAI_UE = True
		pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
		if (pStatus < 0):
			HTML.CreateHtmlTestRow(self.ping_args, 'KO', pStatus)
1746
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
			return
		ping_from_eNB = re.search('oaitun_enb1', str(self.ping_args))
		if ping_from_eNB is not None:
			if RAN.eNBIPAddress == '' or RAN.eNBUserName == '' or RAN.eNBPassword == '':
				HELP.GenericHelp(CONST.Version)
				sys.exit('Insufficient Parameter')
		else:
			if self.UEIPAddress == '' or self.UEUserName == '' or self.UEPassword == '':
				HELP.GenericHelp(CONST.Version)
				sys.exit('Insufficient Parameter')
		try:
			if ping_from_eNB is not None:
				SSH.open(RAN.eNBIPAddress, RAN.eNBUserName, RAN.eNBPassword)
				SSH.command('cd ' + RAN.eNBSourceCodePath + '/cmake_targets/', '\$', 5)
			else:
				SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
				SSH.command('cd ' + self.UESourceCodePath + '/cmake_targets/', '\$', 5)
			ping_time = re.findall("-c (\d+)",str(self.ping_args))
			ping_status = SSH.command('stdbuf -o0 ping ' + self.ping_args + ' 2>&1 | stdbuf -o0 tee ping_' + self.testCase_id + '.log', '\$', int(ping_time[0])*1.5)
			# TIMEOUT CASE
			if ping_status < 0:
				message = 'Ping with OAI UE crashed due to TIMEOUT!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
1770
				self.PingNoS1_wrong_exit(message,HTML)
1771 1772 1773 1774 1775
				return
			result = re.search(', (?P<packetloss>[0-9\.]+)% packet loss, time [0-9\.]+ms', SSH.getBefore())
			if result is None:
				message = 'Packet Loss Not Found!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
1776
				self.PingNoS1_wrong_exit(message,HTML)
1777 1778 1779 1780 1781
				return
			packetloss = result.group('packetloss')
			if float(packetloss) == 100:
				message = 'Packet Loss is 100%'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
1782
				self.PingNoS1_wrong_exit(message,HTML)
1783 1784 1785 1786 1787
				return
			result = re.search('rtt min\/avg\/max\/mdev = (?P<rtt_min>[0-9\.]+)\/(?P<rtt_avg>[0-9\.]+)\/(?P<rtt_max>[0-9\.]+)\/[0-9\.]+ ms', SSH.getBefore())
			if result is None:
				message = 'Ping RTT_Min RTT_Avg RTT_Max Not Found!'
				logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
1788
				self.PingNoS1_wrong_exit(message,HTML)
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
				return
			rtt_min = result.group('rtt_min')
			rtt_avg = result.group('rtt_avg')
			rtt_max = result.group('rtt_max')
			pal_msg = 'Packet Loss : ' + packetloss + '%'
			min_msg = 'RTT(Min)    : ' + rtt_min + ' ms'
			avg_msg = 'RTT(Avg)    : ' + rtt_avg + ' ms'
			max_msg = 'RTT(Max)    : ' + rtt_max + ' ms'
			logging.debug('\u001B[1;37;44m OAI UE ping result \u001B[0m')
			logging.debug('\u001B[1;34m    ' + pal_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + min_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + avg_msg + '\u001B[0m')
			logging.debug('\u001B[1;34m    ' + max_msg + '\u001B[0m')
			qMsg = pal_msg + '\n' + min_msg + '\n' + avg_msg + '\n' + max_msg
			packetLossOK = True
			if packetloss is not None:
				if float(packetloss) > float(self.ping_packetloss_threshold):
					qMsg += '\nPacket Loss too high'
					logging.debug('\u001B[1;37;41m Packet Loss too high \u001B[0m')
					packetLossOK = False
				elif float(packetloss) > 0:
					qMsg += '\nPacket Loss is not 0%'
					logging.debug('\u001B[1;30;43m Packet Loss is not 0% \u001B[0m')
			SSH.close()
			html_queue = SimpleQueue()
			ip_addr = 'TBD'
			html_cell = '<pre style="background-color:white">OAI UE ping result\n' + qMsg + '</pre>'
			html_queue.put(html_cell)
			if packetLossOK:
				HTML.CreateHtmlTestRowQueue(self.ping_args, 'OK', len(self.UEDevices), html_queue)
			else:
				HTML.CreateHtmlTestRowQueue(self.ping_args, 'KO', len(self.UEDevices), html_queue)

			# copying on the EPC server for logCollection
			if ping_from_eNB is not None:
				copyin_res = SSH.copyin(RAN.eNBIPAddress, RAN.eNBUserName, RAN.eNBPassword, RAN.eNBSourceCodePath + '/cmake_targets/ping_' + self.testCase_id + '.log', '.')
			else:
				copyin_res = SSH.copyin(self.UEIPAddress, self.UEUserName, self.UEPassword, self.UESourceCodePath + '/cmake_targets/ping_' + self.testCase_id + '.log', '.')
			if (copyin_res == 0):
				SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'ping_' + self.testCase_id + '.log', EPC.SourceCodePath + '/scripts')
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

1832
	def Ping(self,HTML,RAN,EPC,COTS_UE, InfraUE, CONTAINERS):
1833 1834
		result = re.search('noS1', str(RAN.Initialize_eNB_args))
		if result is not None:
1835
			self.PingNoS1(HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS)
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
			return
		if EPC.IPAddress == '' or EPC.UserName == '' or EPC.Password == '' or EPC.SourceCodePath == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		check_eNB = True
		if (len(self.UEDevices) == 1) and (self.UEDevices[0] == 'OAI-UE'):
			check_OAI_UE = True
		else:
			check_OAI_UE = False
		pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
		if (pStatus < 0):
			HTML.CreateHtmlTestRow(self.ping_args, 'KO', pStatus)
1848
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1849
			return
1850 1851

		if self.ue_id=="":
hardy's avatar
hardy committed
1852
			Module_UE = cls_module_ue.Module_UE(InfraUE.ci_ue_infra['dummy']) #RH, temporary, we need a dummy Module_UE object to pass to Ping_common
1853 1854 1855
			ueIpStatus = self.GetAllUEIPAddresses()
			if (ueIpStatus < 0):
				HTML.CreateHtmlTestRow(self.ping_args, 'KO', CONST.UE_IP_ADDRESS_ISSUE)
1856
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1857 1858
				return
		else:
1859
			self.UEIPAddresses=[]
1860 1861
			Module_UE = cls_module_ue.Module_UE(InfraUE.ci_ue_infra[self.ue_id])
			Module_UE.GetModuleIPAddress()
1862
			self.UEIPAddresses.append(Module_UE.UEIPAddress)
1863
		logging.debug(self.UEIPAddresses)
1864 1865 1866 1867 1868
		multi_jobs = []
		i = 0
		lock = Lock()
		status_queue = SimpleQueue()
		for UE_IPAddress in self.UEIPAddresses:
1869 1870 1871
			if self.ue_id=="":
				device_id = self.UEDevices[i]
			else:
Remi Hardy's avatar
Remi Hardy committed
1872
				device_id = Module_UE.ID + "-" + Module_UE.Kind 
hardy's avatar
hardy committed
1873
			p = Process(target = self.Ping_common, args = (lock,UE_IPAddress,device_id,status_queue,EPC,Module_UE,RAN,))
1874 1875 1876 1877 1878 1879 1880 1881 1882
			p.daemon = True
			p.start()
			multi_jobs.append(p)
			i = i + 1
		for job in multi_jobs:
			job.join()

		if (status_queue.empty()):
			HTML.CreateHtmlTestRow(self.ping_args, 'KO', CONST.ALL_PROCESSES_OK)
1883
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
		else:
			ping_status = True
			html_queue = SimpleQueue()
			while (not status_queue.empty()):
				count = status_queue.get()
				if (count < 0):
					ping_status = False
				device_id = status_queue.get()
				ip_addr = status_queue.get()
				message = status_queue.get()
				html_cell = '<pre style="background-color:white">UE (' + device_id + ')\nIP Address  : ' + ip_addr + '\n' + message + '</pre>'
				html_queue.put(html_cell)
			if (ping_status):
				HTML.CreateHtmlTestRowQueue(self.ping_args, 'OK', len(self.UEDevices), html_queue)
			else:
				HTML.CreateHtmlTestRowQueue(self.ping_args, 'KO', len(self.UEDevices), html_queue)
1900
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933

	def Iperf_ComputeTime(self):
		result = re.search('-t (?P<iperf_time>\d+)', str(self.iperf_args))
		if result is None:
			logging.debug('\u001B[1;37;41m Iperf time Not Found! \u001B[0m')
			sys.exit(1)
		return result.group('iperf_time')

	def Iperf_ComputeModifiedBW(self, idx, ue_num):
		result = re.search('-b (?P<iperf_bandwidth>[0-9\.]+)[KMG]', str(self.iperf_args))
		if result is None:
			logging.debug('\u001B[1;37;41m Iperf bandwidth Not Found! \u001B[0m')
			sys.exit(1)
		iperf_bandwidth = result.group('iperf_bandwidth')
		if self.iperf_profile == 'balanced':
			iperf_bandwidth_new = float(iperf_bandwidth)/ue_num
		if self.iperf_profile == 'single-ue':
			iperf_bandwidth_new = float(iperf_bandwidth)
		if self.iperf_profile == 'unbalanced':
			# residual is 2% of max bw
			residualBW = float(iperf_bandwidth) / 50
			if idx == 0:
				iperf_bandwidth_new = float(iperf_bandwidth) - ((ue_num - 1) * residualBW)
			else:
				iperf_bandwidth_new = residualBW
		iperf_bandwidth_str = '-b ' + iperf_bandwidth
		iperf_bandwidth_str_new = '-b ' + ('%.2f' % iperf_bandwidth_new)
		result = re.sub(iperf_bandwidth_str, iperf_bandwidth_str_new, str(self.iperf_args))
		if result is None:
			logging.debug('\u001B[1;37;41m Calculate Iperf bandwidth Failed! \u001B[0m')
			sys.exit(1)
		return result

1934
	def Iperf_analyzeV2TCPOutput(self, lock, UE_IPAddress, device_id, statusQueue, iperf_real_options,EPC,SSH):
1935

1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
		SSH.command('awk -f /tmp/tcp_iperf_stats.awk ' + EPC.SourceCodePath + '/scripts/iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
		result = re.search('Avg Bitrate : (?P<average>[0-9\.]+ Mbits\/sec) Max Bitrate : (?P<maximum>[0-9\.]+ Mbits\/sec) Min Bitrate : (?P<minimum>[0-9\.]+ Mbits\/sec)', SSH.getBefore())
		if result is not None:
			avgbitrate = result.group('average')
			maxbitrate = result.group('maximum')
			minbitrate = result.group('minimum')
			lock.acquire()
			logging.debug('\u001B[1;37;44m TCP iperf result (' + UE_IPAddress + ') \u001B[0m')
			msg = 'TCP Stats   :\n'
			if avgbitrate is not None:
				logging.debug('\u001B[1;34m    Avg Bitrate : ' + avgbitrate + '\u001B[0m')
				msg += 'Avg Bitrate : ' + avgbitrate + '\n'
			if maxbitrate is not None:
				logging.debug('\u001B[1;34m    Max Bitrate : ' + maxbitrate + '\u001B[0m')
				msg += 'Max Bitrate : ' + maxbitrate + '\n'
			if minbitrate is not None:
				logging.debug('\u001B[1;34m    Min Bitrate : ' + minbitrate + '\u001B[0m')
				msg += 'Min Bitrate : ' + minbitrate + '\n'
			statusQueue.put(0)
			statusQueue.put(device_id)
			statusQueue.put(UE_IPAddress)
			statusQueue.put(msg)
			lock.release()
1959

1960 1961
		return 0

1962 1963
	def Iperf_analyzeV2Output(self, lock, UE_IPAddress, device_id, statusQueue, iperf_real_options,EPC,SSH):

1964 1965
		result = re.search('-u', str(iperf_real_options))
		if result is None:
hardy's avatar
hardy committed
1966
			logging.debug('Into Iperf_analyzeV2TCPOutput client')
1967
			response = self.Iperf_analyzeV2TCPOutput(lock, UE_IPAddress, device_id, statusQueue, iperf_real_options,EPC,SSH)
hardy's avatar
hardy committed
1968 1969
			logging.debug('Iperf_analyzeV2TCPOutput response returned value = ' + str(response))
			return response
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047

		result = re.search('Server Report:', SSH.getBefore())
		if result is None:
			result = re.search('read failed: Connection refused', SSH.getBefore())
			if result is not None:
				logging.debug('\u001B[1;37;41m Could not connect to iperf server! \u001B[0m')
			else:
				logging.debug('\u001B[1;37;41m Server Report and Connection refused Not Found! \u001B[0m')
			return -1
		# Computing the requested bandwidth in float
		result = re.search('-b (?P<iperf_bandwidth>[0-9\.]+)[KMG]', str(iperf_real_options))
		if result is not None:
			req_bandwidth = result.group('iperf_bandwidth')
			req_bw = float(req_bandwidth)
			result = re.search('-b [0-9\.]+K', str(iperf_real_options))
			if result is not None:
				req_bandwidth = '%.1f Kbits/sec' % req_bw
				req_bw = req_bw * 1000
			result = re.search('-b [0-9\.]+M', str(iperf_real_options))
			if result is not None:
				req_bandwidth = '%.1f Mbits/sec' % req_bw
				req_bw = req_bw * 1000000
			result = re.search('-b [0-9\.]+G', str(iperf_real_options))
			if result is not None:
				req_bandwidth = '%.1f Gbits/sec' % req_bw
				req_bw = req_bw * 1000000000

		result = re.search('Server Report:\\\\r\\\\n(?:|\[ *\d+\].*) (?P<bitrate>[0-9\.]+ [KMG]bits\/sec) +(?P<jitter>[0-9\.]+ ms) +(\d+\/..\d+) +(\((?P<packetloss>[0-9\.]+)%\))', SSH.getBefore())
		if result is not None:
			bitrate = result.group('bitrate')
			packetloss = result.group('packetloss')
			jitter = result.group('jitter')
			lock.acquire()
			logging.debug('\u001B[1;37;44m iperf result (' + UE_IPAddress + ') \u001B[0m')
			iperfStatus = True
			msg = 'Req Bitrate : ' + req_bandwidth + '\n'
			logging.debug('\u001B[1;34m    Req Bitrate : ' + req_bandwidth + '\u001B[0m')
			if bitrate is not None:
				msg += 'Bitrate     : ' + bitrate + '\n'
				logging.debug('\u001B[1;34m    Bitrate     : ' + bitrate + '\u001B[0m')
				result = re.search('(?P<real_bw>[0-9\.]+) [KMG]bits/sec', str(bitrate))
				if result is not None:
					actual_bw = float(str(result.group('real_bw')))
					result = re.search('[0-9\.]+ K', bitrate)
					if result is not None:
						actual_bw = actual_bw * 1000
					result = re.search('[0-9\.]+ M', bitrate)
					if result is not None:
						actual_bw = actual_bw * 1000000
					result = re.search('[0-9\.]+ G', bitrate)
					if result is not None:
						actual_bw = actual_bw * 1000000000
					br_loss = 100 * actual_bw / req_bw
					bitperf = '%.2f ' % br_loss
					msg += 'Bitrate Perf: ' + bitperf + '%\n'
					logging.debug('\u001B[1;34m    Bitrate Perf: ' + bitperf + '%\u001B[0m')
			if packetloss is not None:
				msg += 'Packet Loss : ' + packetloss + '%\n'
				logging.debug('\u001B[1;34m    Packet Loss : ' + packetloss + '%\u001B[0m')
				if float(packetloss) > float(self.iperf_packetloss_threshold):
					msg += 'Packet Loss too high!\n'
					logging.debug('\u001B[1;37;41m Packet Loss too high \u001B[0m')
					iperfStatus = False
			if jitter is not None:
				msg += 'Jitter      : ' + jitter + '\n'
				logging.debug('\u001B[1;34m    Jitter      : ' + jitter + '\u001B[0m')
			if (iperfStatus):
				statusQueue.put(0)
			else:
				statusQueue.put(-1)
			statusQueue.put(device_id)
			statusQueue.put(UE_IPAddress)
			statusQueue.put(msg)
			lock.release()
			return 0
		else:
			return -2

2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076

	def Iperf_analyzeV2BIDIR(self, lock, UE_IPAddress, device_id, statusQueue,server_filename,client_filename):
		#server file is unused for the moment
		if (not os.path.isfile(client_filename)):
			self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, 'Bidir TCP : Could not analyze from client log')
			return
		report=[]
		report_msg='Client Report:\n'
		with open(client_filename, 'r') as f_client:
			for line in f_client.readlines():
				result = re.search(rf'^\[\s+\d+\](?P<direction>\[.+\]).*\s+(?P<bitrate>[0-9\.]+ [KMG]bits\/sec).*\s+(?P<role>\bsender|receiver\b)', str(line))
				if result is not None:
					report.append(str(line))
					report_msg+=result.group('role') + ' ' + result.group('direction')+ '\t = ' +result.group('bitrate')+'\n'

		if len(report)>0:
			lock.acquire()
			statusQueue.put(0)
			statusQueue.put(device_id)
			statusQueue.put(UE_IPAddress)
			statusQueue.put(report_msg)
			logging.debug('\u001B[1;37;45m TCP Bidir Iperf Result (' + UE_IPAddress + ') \u001B[0m')
			logging.debug('\u001B[1;35m    ' + report_msg + '\u001B[0m')
			lock.release()
		else:
			self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, 'Bidir TCP : Could not analyze from client log')



2077 2078
	def Iperf_analyzeV2Server(self, lock, UE_IPAddress, device_id, statusQueue, iperf_real_options, filename,type):
		if (not os.path.isfile(filename)):
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
			self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, 'Could not analyze from server log')
			return
		# Computing the requested bandwidth in float
		result = re.search('-b (?P<iperf_bandwidth>[0-9\.]+)[KMG]', str(iperf_real_options))
		if result is None:
			logging.debug('Iperf bandwidth Not Found!')
			self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, 'Could not compute Iperf bandwidth!')
			return
		else:
			req_bandwidth = result.group('iperf_bandwidth')
			req_bw = float(req_bandwidth)
			result = re.search('-b [0-9\.]+K', str(iperf_real_options))
			if result is not None:
				req_bandwidth = '%.1f Kbits/sec' % req_bw
				req_bw = req_bw * 1000
			result = re.search('-b [0-9\.]+M', str(iperf_real_options))
			if result is not None:
				req_bandwidth = '%.1f Mbits/sec' % req_bw
				req_bw = req_bw * 1000000
			result = re.search('-b [0-9\.]+G', str(iperf_real_options))
			if result is not None:
				req_bandwidth = '%.1f Gbits/sec' % req_bw
				req_bw = req_bw * 1000000000

2103
		server_file = open(filename, 'r')
2104 2105 2106 2107 2108 2109
		br_sum = 0.0
		ji_sum = 0.0
		pl_sum = 0
		ps_sum = 0
		row_idx = 0
		for line in server_file.readlines():
2110 2111 2112
			if type==0:
				result = re.search('(?P<bitrate>[0-9\.]+ [KMG]bits\/sec) +(?P<jitter>[0-9\.]+ ms) +(?P<lostPack>[0-9]+)/ +(?P<sentPack>[0-9]+)', str(line))
			else:
hardy's avatar
hardy committed
2113
				result = re.search('^\[\s+\d\].+  (?P<bitrate>[0-9\.]+ [KMG]bits\/sec) +(?P<jitter>[0-9\.]+ ms) +(?P<lostPack>[0-9]+)\/\s*(?P<sentPack>[0-9]+)', str(line))
2114

2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
			if result is not None:
				bitrate = result.group('bitrate')
				jitter = result.group('jitter')
				packetlost = result.group('lostPack')
				packetsent = result.group('sentPack')
				br = bitrate.split(' ')
				ji = jitter.split(' ')
				row_idx = row_idx + 1
				curr_br = float(br[0])
				pl_sum = pl_sum + int(packetlost)
				ps_sum = ps_sum + int(packetsent)
				if (br[1] == 'Kbits/sec'):
					curr_br = curr_br * 1000
				if (br[1] == 'Mbits/sec'):
					curr_br = curr_br * 1000 * 1000
				br_sum = curr_br + br_sum
				ji_sum = float(ji[0]) + ji_sum
2132

2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
		if (row_idx > 0):
			br_sum = br_sum / row_idx
			ji_sum = ji_sum / row_idx
			br_loss = 100 * br_sum / req_bw
			if (br_sum > 1000):
				br_sum = br_sum / 1000
				if (br_sum > 1000):
					br_sum = br_sum / 1000
					bitrate = '%.2f Mbits/sec' % br_sum
				else:
					bitrate = '%.2f Kbits/sec' % br_sum
			else:
				bitrate = '%.2f bits/sec' % br_sum
			bitperf = '%.2f ' % br_loss
			bitperf += '%'
			jitter = '%.2f ms' % (ji_sum)
			if (ps_sum > 0):
				pl = float(100 * pl_sum / ps_sum)
				packetloss = '%2.1f ' % (pl)
				packetloss += '%'
hardy's avatar
hardy committed
2153
				#checking packet loss compliance
2154
				if float(pl) > float(self.iperf_packetloss_threshold):
2155
					pal_too_high_msg = 'Packet Loss too high :  tested = '+packetloss+', target = '+self.iperf_packetloss_threshold+'%'
2156
				else:
2157
					pal_too_high_msg='Packet Loss value is within acceptance range'
hardy's avatar
hardy committed
2158 2159
				#checking bitrate perf compliance
				if float(br_loss) < float(self.iperf_bitrate_threshold):
2160
					bit_too_low_msg = 'Bitrate too low :  tested = '+bitperf+', target = '+self.iperf_bitrate_threshold+'%'
hardy's avatar
hardy committed
2161
				else:
2162
					bit_too_low_msg='Bitrate perf value is within acceptance range'
2163
			lock.acquire()
2164
			if (float(br_loss) < float(self.iperf_bitrate_threshold)) and (float(pl) > float(self.iperf_packetloss_threshold)):
hardy's avatar
hardy committed
2165
				statusQueue.put(-1)
2166 2167
			elif (float(br_loss) < float(self.iperf_bitrate_threshold)) or (float(pl) > float(self.iperf_packetloss_threshold)): 
				statusQueue.put(1)
2168 2169 2170 2171 2172 2173 2174 2175 2176
			else:
				statusQueue.put(0)
			statusQueue.put(device_id)
			statusQueue.put(UE_IPAddress)
			req_msg = 'Req Bitrate : ' + req_bandwidth
			bir_msg = 'Bitrate     : ' + bitrate
			brl_msg = 'Bitrate Perf: ' + bitperf
			jit_msg = 'Jitter      : ' + jitter
			pal_msg = 'Packet Loss : ' + packetloss
hardy's avatar
hardy committed
2177
			statusQueue.put(req_msg + '\n' + bir_msg + '\n' + brl_msg + '\n' + jit_msg + '\n' + pal_msg + '\n' + pal_too_high_msg + '\n' + bit_too_low_msg + '\n')
2178 2179 2180 2181 2182 2183
			logging.debug('\u001B[1;37;45m iperf result (' + UE_IPAddress + ') \u001B[0m')
			logging.debug('\u001B[1;35m    ' + req_msg + '\u001B[0m')
			logging.debug('\u001B[1;35m    ' + bir_msg + '\u001B[0m')
			logging.debug('\u001B[1;35m    ' + brl_msg + '\u001B[0m')
			logging.debug('\u001B[1;35m    ' + jit_msg + '\u001B[0m')
			logging.debug('\u001B[1;35m    ' + pal_msg + '\u001B[0m')
2184
			logging.debug('\u001B[1;35m    ' + pal_too_high_msg + '\u001B[0m')
hardy's avatar
hardy committed
2185
			logging.debug('\u001B[1;35m    ' + bit_too_low_msg + '\u001B[0m')
2186 2187 2188 2189 2190 2191 2192
			lock.release()
		else:
			self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, 'Could not analyze from server log')

		server_file.close()


2193 2194
	def Iperf_analyzeV3Output(self, lock, UE_IPAddress, device_id, statusQueue,SSH):

2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
		result = re.search('(?P<bitrate>[0-9\.]+ [KMG]bits\/sec) +(?:|[0-9\.]+ ms +\d+\/\d+ \((?P<packetloss>[0-9\.]+)%\)) +(?:|receiver)\\\\r\\\\n(?:|\[ *\d+\] Sent \d+ datagrams)\\\\r\\\\niperf Done\.', SSH.getBefore())
		if result is None:
			result = re.search('(?P<error>iperf: error - [a-zA-Z0-9 :]+)', SSH.getBefore())
			lock.acquire()
			statusQueue.put(-1)
			statusQueue.put(device_id)
			statusQueue.put(UE_IPAddress)
			if result is not None:
				logging.debug('\u001B[1;37;41m ' + result.group('error') + ' \u001B[0m')
				statusQueue.put(result.group('error'))
			else:
				logging.debug('\u001B[1;37;41m Bitrate and/or Packet Loss Not Found! \u001B[0m')
				statusQueue.put('Bitrate and/or Packet Loss Not Found!')
			lock.release()

		bitrate = result.group('bitrate')
		packetloss = result.group('packetloss')
		lock.acquire()
		logging.debug('\u001B[1;37;44m iperf result (' + UE_IPAddress + ') \u001B[0m')
		logging.debug('\u001B[1;34m    Bitrate     : ' + bitrate + '\u001B[0m')
		msg = 'Bitrate     : ' + bitrate + '\n'
		iperfStatus = True
		if packetloss is not None:
			logging.debug('\u001B[1;34m    Packet Loss : ' + packetloss + '%\u001B[0m')
			msg += 'Packet Loss : ' + packetloss + '%\n'
			if float(packetloss) > float(self.iperf_packetloss_threshold):
				logging.debug('\u001B[1;37;41m Packet Loss too high \u001B[0m')
				msg += 'Packet Loss too high!\n'
				iperfStatus = False
		if (iperfStatus):
			statusQueue.put(0)
		else:
			statusQueue.put(-1)
		statusQueue.put(device_id)
		statusQueue.put(UE_IPAddress)
		statusQueue.put(msg)
		lock.release()

2233
	def Iperf_UL_common(self, lock, UE_IPAddress, device_id, idx, ue_num, statusQueue,EPC):
hardy's avatar
hardy committed
2234
		SSH = sshconnection.SSHConnection()
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
		udpIperf = True
		result = re.search('-u', str(self.iperf_args))
		if result is None:
			udpIperf = False
		ipnumbers = UE_IPAddress.split('.')
		if (len(ipnumbers) == 4):
			ipnumbers[3] = '1'
		EPC_Iperf_UE_IPAddress = ipnumbers[0] + '.' + ipnumbers[1] + '.' + ipnumbers[2] + '.' + ipnumbers[3]

		# Launch iperf server on EPC side (true for ltebox and old open-air-cn0
		# But for OAI-Rel14-CUPS, we launch from python executor and we are using its IP address as iperf client address
		launchFromEpc = True
		if re.match('OAI-Rel14-CUPS', EPC.Type, re.IGNORECASE):
			launchFromEpc = False
			cmd = 'hostname -I'
			ret = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, encoding='utf-8')
			if ret.stdout is not None:
				EPC_Iperf_UE_IPAddress = ret.stdout.strip()
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
		# When using a docker-based deployment, IPERF client shall be launched from trf container
		launchFromTrfContainer = False
		if re.match('OAI-Rel14-Docker', EPC.Type, re.IGNORECASE):
			launchFromTrfContainer = True
			SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
			SSH.command('docker inspect --format="TRF_IP_ADDR = {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" prod-trf-gen', '\$', 5)
			result = re.search('TRF_IP_ADDR = (?P<trf_ip_addr>[0-9\.]+)', SSH.getBefore())
			if result is not None:
				EPC_Iperf_UE_IPAddress = result.group('trf_ip_addr')
			SSH.close()
2263
		port = 5001 + idx
2264 2265 2266
		udpOptions = ''
		if udpIperf:
			udpOptions = '-u '
2267 2268 2269 2270
		if launchFromEpc:
			SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
			SSH.command('cd ' + EPC.SourceCodePath + '/scripts', '\$', 5)
			SSH.command('rm -f iperf_server_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
2271 2272 2273 2274 2275 2276 2277 2278
			if launchFromTrfContainer:
				if self.ueIperfVersion == self.dummyIperfVersion:
					prefix = ''
				else:
					prefix = ''
					if self.ueIperfVersion == '2.0.5':
						prefix = '/iperf-2.0.5/bin/'
				SSH.command('docker exec -d prod-trf-gen /bin/bash -c "nohup ' + prefix + 'iperf ' + udpOptions + '-s -i 1 -p ' + str(port) + ' > iperf_server_' + self.testCase_id + '_' + device_id + '.log &"', '\$', 5)
2279
			else:
2280
				SSH.command('echo $USER; nohup iperf ' + udpOptions + '-s -i 1 -p ' + str(port) + ' > iperf_server_' + self.testCase_id + '_' + device_id + '.log &', EPC.UserName, 5)
2281 2282 2283 2284 2285 2286 2287 2288
			SSH.close()
		else:
			if self.ueIperfVersion == self.dummyIperfVersion:
				prefix = ''
			else:
				prefix = ''
				if self.ueIperfVersion == '2.0.5':
					prefix = '/opt/iperf-2.0.5/bin/'
2289
			cmd = 'nohup ' + prefix + 'iperf ' + udpOptions + '-s -i 1 -p ' + str(port) + ' > iperf_server_' + self.testCase_id + '_' + device_id + '.log 2>&1 &'
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
			logging.debug(cmd)
			subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, encoding='utf-8')
		time.sleep(0.5)

		# Launch iperf client on UE
		if (device_id == 'OAI-UE'):
			SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
			SSH.command('cd ' + self.UESourceCodePath + '/cmake_targets', '\$', 5)
		else:
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			SSH.command('cd ' + EPC.SourceCodePath+ '/scripts', '\$', 5)
		iperf_time = self.Iperf_ComputeTime()
		time.sleep(0.5)

		if udpIperf:
			modified_options = self.Iperf_ComputeModifiedBW(idx, ue_num)
		else:
			modified_options = str(self.iperf_args)
		modified_options = modified_options.replace('-R','')
		time.sleep(0.5)

		SSH.command('rm -f iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
		if (device_id == 'OAI-UE'):
			iperf_status = SSH.command('iperf -c ' + EPC_Iperf_UE_IPAddress + ' ' + modified_options + ' -p ' + str(port) + ' -B ' + UE_IPAddress + ' 2>&1 | stdbuf -o0 tee iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', int(iperf_time)*5.0)
		else:
			if self.ADBCentralized:
				iperf_status = SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "/data/local/tmp/iperf -c ' + EPC_Iperf_UE_IPAddress + ' ' + modified_options + ' -p ' + str(port) + '" 2>&1 | stdbuf -o0 tee iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', int(iperf_time)*5.0)
			else:
				iperf_status = SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "/data/local/tmp/iperf -c ' + EPC_Iperf_UE_IPAddress + ' ' + modified_options + ' -p ' + str(port) + '"\' 2>&1 > iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', int(iperf_time)*5.0)
				SSH.command('fromdos -o iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
				SSH.command('cat iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
		# TIMEOUT Case
		if iperf_status < 0:
			SSH.close()
			message = 'iperf on UE (' + str(UE_IPAddress) + ') crashed due to TIMEOUT !'
			logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
			SSH.close()
			self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, message)
			return
2329
		clientStatus = self.Iperf_analyzeV2Output(lock, UE_IPAddress, device_id, statusQueue, modified_options,EPC,SSH)
2330 2331 2332 2333 2334
		SSH.close()

		# Kill iperf server on EPC side
		if launchFromEpc:
			SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
2335 2336 2337 2338
			if launchFromTrfContainer:
				SSH.command('docker exec -it prod-trf-gen /bin/bash -c "killall --signal SIGKILL iperf"', '\$', 5)
			else:
				SSH.command('killall --signal SIGKILL iperf', EPC.UserName, 5)
2339 2340 2341 2342 2343
			SSH.close()
		else:
			cmd = 'killall --signal SIGKILL iperf'
			logging.debug(cmd)
			subprocess.run(cmd, shell=True)
2344
			time.sleep(1)
2345 2346 2347 2348 2349 2350 2351
			SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_server_' + self.testCase_id + '_' + device_id + '.log', EPC.SourceCodePath + '/scripts')
		# in case of failure, retrieve server log
		if (clientStatus == -1) or (clientStatus == -2):
			if launchFromEpc:
				time.sleep(1)
				if (os.path.isfile('iperf_server_' + self.testCase_id + '_' + device_id + '.log')):
					os.remove('iperf_server_' + self.testCase_id + '_' + device_id + '.log')
2352 2353 2354 2355
				if launchFromTrfContainer:
					SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
					SSH.command('docker cp prod-trf-gen:/iperf-2.0.5/iperf_server_' + self.testCase_id + '_' + device_id + '.log ' + EPC.SourceCodePath + '/scripts', '\$', 5)
					SSH.close()
2356
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, EPC.SourceCodePath+ '/scripts/iperf_server_' + self.testCase_id + '_' + device_id + '.log', '.')
2357 2358
			filename='iperf_server_' + self.testCase_id + '_' + device_id + '.log'
			self.Iperf_analyzeV2Server(lock, UE_IPAddress, device_id, statusQueue, modified_options,filename,0)
2359 2360 2361 2362 2363
		# in case of OAI-UE 
		if (device_id == 'OAI-UE'):
			SSH.copyin(self.UEIPAddress, self.UEUserName, self.UEPassword, self.UESourceCodePath + '/cmake_targets/iperf_' + self.testCase_id + '_' + device_id + '.log', '.')
			SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_' + self.testCase_id + '_' + device_id + '.log', EPC.SourceCodePath + '/scripts')

2364

hardy's avatar
hardy committed
2365
	def Iperf_Module(self, lock, UE_IPAddress, device_id, idx, ue_num, statusQueue,EPC, Module_UE):
2366
		if (re.match('OAI-Rel14-Docker', EPC.Type, re.IGNORECASE)) or (re.match('OAICN5G', EPC.Type, re.IGNORECASE)):
hardy's avatar
hardy committed
2367 2368 2369 2370 2371 2372
			#retrieve trf-gen container IP address
			SSH = sshconnection.SSHConnection()
			SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
			SSH.command('docker inspect --format="TRF_IP_ADDR = {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" prod-trf-gen', '\$', 5)
			result = re.search('TRF_IP_ADDR = (?P<trf_ip_addr>[0-9\.]+)', SSH.getBefore())
			if result is not None:
hardy's avatar
hardy committed
2373
				trf_gen_IP = result.group('trf_ip_addr')
2374 2375 2376
			#kill iperf processes on EPC side
			SSH.command('docker exec -it prod-trf-gen /bin/bash -c "killall --signal SIGKILL iperf"', '\$', 5)
			SSH.command('docker exec -it prod-trf-gen /bin/bash -c "killall --signal SIGKILL iperf3"', '\$', 5)
hardy's avatar
hardy committed
2377 2378 2379 2380 2381
			SSH.close()
			#kill iperf processes on UE side before (in case there are still some remaining)
			SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
			cmd = 'killall --signal=SIGKILL iperf'
			SSH.command(cmd,'\$',5)
2382 2383
			cmd = 'killall --signal=SIGKILL iperf3'
			SSH.command(cmd,'\$',5)
hardy's avatar
hardy committed
2384 2385
			SSH.close()

2386
			iperf_time = self.Iperf_ComputeTime()
hardy's avatar
hardy committed
2387 2388 2389 2390 2391 2392 2393
			if self.iperf_direction=="DL":
				logging.debug("Iperf for Module in DL mode detected")
				#server side UE
				server_filename='iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log'
				SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
				cmd = 'rm ' + server_filename
				SSH.command(cmd,'\$',5)
hardy's avatar
hardy committed
2394
				cmd = 'echo $USER; nohup iperf -s -B ' + UE_IPAddress + ' -u 2>&1 > ' + server_filename + ' &'
hardy's avatar
hardy committed
2395 2396 2397 2398 2399
				SSH.command(cmd,'\$',5)
				SSH.close()
				#client side EPC
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				client_filename = 'iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log'
2400

hardy's avatar
hardy committed
2401 2402 2403
				iperf_cmd = 'bin/iperf -c ' + UE_IPAddress + ' ' + self.iperf_args + ' 2>&1 > ' + client_filename
				cmd = 'docker exec -it prod-trf-gen /bin/bash -c \"' + iperf_cmd + '\"' 
				SSH.command(cmd,'\$',int(iperf_time)*5.0)
hardy's avatar
fix  
hardy committed
2404
				SSH.command('docker cp prod-trf-gen:/iperf-2.0.13/'+ client_filename + ' ' + EPC.SourceCodePath, '\$', 5)
hardy's avatar
hardy committed
2405 2406
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, EPC.SourceCodePath + '/' + client_filename, '.')
				SSH.close()
hardy's avatar
hardy committed
2407

hardy's avatar
hardy committed
2408 2409 2410 2411 2412 2413
				#copy the 2 resulting files locally
				SSH.copyin(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword, server_filename, '.')
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, client_filename, '.')
				#send for analysis
				self.Iperf_analyzeV2Server(lock, UE_IPAddress, device_id, statusQueue, self.iperf_args,server_filename,1)	

hardy's avatar
hardy committed
2414 2415 2416 2417 2418
			elif self.iperf_direction=="UL":
				logging.debug("Iperf for Module in UL mode detected")
				#server side EPC
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				server_filename = 'iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log'
2419

hardy's avatar
hardy committed
2420
				iperf_cmd = 'echo $USER; nohup bin/iperf -s -u 2>&1 > ' + server_filename
2421
				cmd = 'docker exec -d prod-trf-gen /bin/bash -c \"' + iperf_cmd + '\"' 
hardy's avatar
hardy committed
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
				SSH.command(cmd,'\$',5)
				SSH.close()

				#client side UE
				SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
				client_filename = 'iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log'
				cmd = 'rm '+ client_filename
				SSH.command(cmd,'\$',5)
				SSH.command('iperf -B ' + UE_IPAddress + ' -c ' +  trf_gen_IP + ' '  + self.iperf_args + ' 2>&1 > ' + client_filename, '\$', int(iperf_time)*5.0)
				SSH.close()

				#once client is done, retrieve the server file from container to EPC Host
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
hardy's avatar
fix  
hardy committed
2435
				SSH.command('docker cp prod-trf-gen:/iperf-2.0.13/' + server_filename + ' ' + EPC.SourceCodePath, '\$', 5)
hardy's avatar
hardy committed
2436 2437 2438 2439 2440 2441 2442 2443
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, EPC.SourceCodePath + '/' + server_filename, '.')
				SSH.close()

				#copy the 2 resulting files locally 
				SSH.copyin(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword, client_filename, '.')
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, server_filename, '.')
				#send for analysis
				self.Iperf_analyzeV2Server(lock, UE_IPAddress, device_id, statusQueue, self.iperf_args,server_filename,1)
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475

			elif self.iperf_direction=="BIDIR":
				logging.debug("Iperf for Module in BIDIR mode detected")
				#server side EPC
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				server_filename = 'iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log'

				iperf_cmd = 'echo $USER; nohup /usr/local/bin/iperf3 -s 2>&1 > ' + server_filename
				cmd = 'docker exec -d prod-trf-gen /bin/bash -c \"' + iperf_cmd + '\"' 
				SSH.command(cmd,'\$',5)
				SSH.close()

				#client side UE
				SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
				client_filename = 'iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log'
				cmd = 'rm '+ client_filename
				SSH.command(cmd,'\$',5)
				SSH.command('iperf3 -B ' + UE_IPAddress + ' -c ' +  trf_gen_IP + ' '  + self.iperf_args + ' 2>&1 > ' + client_filename, '\$', int(iperf_time)*5.0)
				SSH.close()

				#once client is done, retrieve the server file from container to EPC Host
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				SSH.command('docker cp prod-trf-gen:/iperf-2.0.13/' + server_filename + ' ' + EPC.SourceCodePath, '\$', 5)
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, EPC.SourceCodePath + '/' + server_filename, '.')
				SSH.close()

				#copy the 2 resulting files locally 
				SSH.copyin(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword, client_filename, '.')
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, server_filename, '.')
				#send for analysis
				self.Iperf_analyzeV2BIDIR(lock, UE_IPAddress, device_id, statusQueue, server_filename, client_filename)

hardy's avatar
hardy committed
2476 2477 2478 2479 2480
			else :
				logging.debug("Incorrect or missing IPERF direction in XML")

		else: 		#default is ltebox

hardy's avatar
hardy committed
2481
			SSH = sshconnection.SSHConnection()
hardy's avatar
hardy committed
2482

hardy's avatar
hardy committed
2483
			#kill iperf processes before (in case there are still some remaining)
2484
			SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
hardy's avatar
hardy committed
2485
			cmd = 'killall --signal=SIGKILL iperf'
2486
			SSH.command(cmd,'\$',5)
hardy's avatar
hardy committed
2487
			SSH.close()
hardy's avatar
hardy committed
2488
			SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
hardy's avatar
hardy committed
2489
			cmd = 'killall --signal=SIGKILL iperf'
2490
			SSH.command(cmd,'\$',5)
hardy's avatar
hardy committed
2491
			SSH.close()
2492

hardy's avatar
hardy committed
2493 2494 2495 2496 2497 2498 2499 2500

			iperf_time = self.Iperf_ComputeTime()	
			if self.iperf_direction=="DL":
				logging.debug("Iperf for Module in DL mode detected")
				#server side UE
				SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
				cmd = 'rm iperf_server_' +  self.testCase_id + '_' + self.ue_id + '.log'
				SSH.command(cmd,'\$',5)
hardy's avatar
hardy committed
2501
				cmd = 'echo $USER; nohup /opt/iperf-2.0.10/iperf -s -B ' + UE_IPAddress + ' -u 2>&1 > iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log &' 
hardy's avatar
hardy committed
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
				SSH.command(cmd,'\$',5)
				SSH.close()
				#client side EPC
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				cmd = 'rm iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log'
				SSH.command(cmd,'\$',5)
				cmd = 'iperf -c ' + UE_IPAddress + ' ' + self.iperf_args + ' 2>&1 > iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log' 
				SSH.command(cmd,'\$',int(iperf_time)*5.0)
				SSH.close()
				#copy the 2 resulting files locally
				SSH.copyin(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword, 'iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log', '.')
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log', '.')
				#send for analysis
				filename='iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log'
				self.Iperf_analyzeV2Server(lock, UE_IPAddress, device_id, statusQueue, self.iperf_args,filename,1)	

hardy's avatar
hardy committed
2518
			elif self.iperf_direction=="UL":
hardy's avatar
hardy committed
2519 2520 2521 2522 2523
				logging.debug("Iperf for Module in UL mode detected")
				#server side EPC
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				cmd = 'rm iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log'
				SSH.command(cmd,'\$',5)
2524
				cmd = 'echo $USER; nohup iperf -s -u 2>&1 > iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log  &'
hardy's avatar
hardy committed
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
				SSH.command(cmd,'\$',5)
				SSH.close()

				#client side UE
				SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
				cmd = 'rm iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log'
				SSH.command(cmd,'\$',5)
				SSH.command('/opt/iperf-2.0.10/iperf -c 192.172.0.1 ' + self.iperf_args + ' 2>&1 > iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log', '\$', int(iperf_time)*5.0)
				SSH.close()

				#copy the 2 resulting files locally
				SSH.copyin(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword, 'iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log', '.')
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log', '.')
				#send for analysis
				filename='iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log'
				self.Iperf_analyzeV2Server(lock, UE_IPAddress, device_id, statusQueue, self.iperf_args,filename,1)
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
			elif self.iperf_direction=="BIDIR":
				logging.debug("Iperf for Module in BIDIR mode detected")
				#server side EPC
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				server_filename = 'iperf_server_' + self.testCase_id + '_' + self.ue_id + '.log'
				cmd = 'rm ' + server_filename
				SSH.command(cmd,'\$',5)
				cmd = 'echo $USER; nohup iperf3 -s 2>&1 > '+server_filename+' &'
				SSH.command(cmd,'\$',5)
				SSH.close()

				#client side UE
				SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
				client_filename = 'iperf_client_' + self.testCase_id + '_' + self.ue_id + '.log'
				cmd = 'rm ' + client_filename
				SSH.command(cmd,'\$',5)
				SSH.command('iperf3 -c 192.172.0.1 ' + self.iperf_args + ' 2>&1 > '+client_filename, '\$', int(iperf_time)*5.0)
				SSH.close()

				#copy the 2 resulting files locally
				SSH.copyin(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword, client_filename, '.')
				SSH.copyin(EPC.IPAddress, EPC.UserName, EPC.Password, server_filename, '.')
				#send for analysis
				self.Iperf_analyzeV2BIDIR(lock, UE_IPAddress, device_id, statusQueue, server_filename, client_filename)
hardy's avatar
hardy committed
2565 2566 2567 2568
			else :
				logging.debug("Incorrect or missing IPERF direction in XML")

			#kill iperf processes after to be clean
hardy's avatar
hardy committed
2569
			SSH.open(Module_UE.HostIPAddress, Module_UE.HostUsername, Module_UE.HostPassword)
hardy's avatar
hardy committed
2570
			cmd = 'killall --signal=SIGKILL iperf'
2571
			SSH.command(cmd,'\$',5)
hardy's avatar
hardy committed
2572
			SSH.close()
hardy's avatar
hardy committed
2573 2574 2575 2576 2577
			SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
			cmd = 'killall --signal=SIGKILL iperf'
			SSH.command(cmd,'\$',5)
			SSH.close()
			return
2578

hardy's avatar
hardy committed
2579
	def Iperf_common(self, lock, UE_IPAddress, device_id, idx, ue_num, statusQueue,EPC):
2580
		try:
hardy's avatar
hardy committed
2581
			SSH = sshconnection.SSHConnection()
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
			# Single-UE profile -- iperf only on one UE
			if self.iperf_profile == 'single-ue' and idx != 0:
				return
			useIperf3 = False
			udpIperf = True

			self.ueIperfVersion = '2.0.5'
			if (device_id != 'OAI-UE'):
				SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
				# if by chance ADB server and EPC are on the same remote host, at least log collection will take care of it
				SSH.command('if [ ! -d ' + EPC.SourceCodePath + '/scripts ]; then mkdir -p ' + EPC.SourceCodePath + '/scripts ; fi', '\$', 5)
				SSH.command('cd ' + EPC.SourceCodePath + '/scripts', '\$', 5)
				# Checking if iperf / iperf3 are installed
				if self.ADBCentralized:
					SSH.command('adb -s ' + device_id + ' shell "ls /data/local/tmp"', '\$', 5)
				else:
					SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "ls /data/local/tmp"\'', '\$', 60)
2599 2600
				# DEBUG: disabling iperf3 usage for the moment
				result = re.search('iperf4', SSH.getBefore())
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
				if result is None:
					result = re.search('iperf', SSH.getBefore())
					if result is None:
						message = 'Neither iperf nor iperf3 installed on UE!'
						logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
						SSH.close()
						self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, message)
						return
					else:
						if self.ADBCentralized:
							SSH.command('adb -s ' + device_id + ' shell "/data/local/tmp/iperf --version"', '\$', 5)
						else:
							SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "/data/local/tmp/iperf --version"\'', '\$', 60)
						result = re.search('iperf version 2.0.5', SSH.getBefore())
						if result is not None:
							self.ueIperfVersion = '2.0.5'
						result = re.search('iperf version 2.0.10', SSH.getBefore())
						if result is not None:
							self.ueIperfVersion = '2.0.10'
				else:
					useIperf3 = True
				SSH.close()
			else:
				SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
				SSH.command('iperf --version', '\$', 5)
				result = re.search('iperf version 2.0.5', SSH.getBefore())
				if result is not None:
					self.ueIperfVersion = '2.0.5'
				result = re.search('iperf version 2.0.10', SSH.getBefore())
				if result is not None:
					self.ueIperfVersion = '2.0.10'
				SSH.close()
			# in case of iperf, UL has its own function
			if (not useIperf3):
				result = re.search('-R', str(self.iperf_args))
				if result is not None:
2637
					self.Iperf_UL_common(lock, UE_IPAddress, device_id, idx, ue_num, statusQueue,EPC)
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
					return

			# Launch the IPERF server on the UE side for DL
			if (device_id == 'OAI-UE'):
				SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
				SSH.command('cd ' + self.UESourceCodePath + '/cmake_targets', '\$', 5)
				SSH.command('rm -f iperf_server_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
				result = re.search('-u', str(self.iperf_args))
				if result is None:
					SSH.command('echo $USER; nohup iperf -B ' + UE_IPAddress + ' -s -i 1 > iperf_server_' + self.testCase_id + '_' + device_id + '.log &', self.UEUserName, 5)
					udpIperf = False
				else:
					SSH.command('echo $USER; nohup iperf -B ' + UE_IPAddress + ' -u -s -i 1 > iperf_server_' + self.testCase_id + '_' + device_id + '.log &', self.UEUserName, 5)
			else:
				SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
				SSH.command('cd ' + EPC.SourceCodePath + '/scripts', '\$', 5)
				if self.ADBCentralized:
					if (useIperf3):
						SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell /data/local/tmp/iperf3 -s &', '\$', 5)
					else:
						SSH.command('rm -f iperf_server_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
						result = re.search('-u', str(self.iperf_args))
						if result is None:
							SSH.command('echo $USER; nohup adb -s ' + device_id + ' shell "/data/local/tmp/iperf -s -i 1" > iperf_server_' + self.testCase_id + '_' + device_id + '.log &', self.ADBUserName, 5)
							udpIperf = False
						else:
							SSH.command('echo $USER; nohup adb -s ' + device_id + ' shell "/data/local/tmp/iperf -u -s -i 1" > iperf_server_' + self.testCase_id + '_' + device_id + '.log &', self.ADBUserName, 5)
				else:
					SSH.command('rm -f iperf_server_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
					SSH.command('echo $USER; nohup ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "/data/local/tmp/iperf -u -s -i 1" \' 2>&1 > iperf_server_' + self.testCase_id + '_' + device_id + '.log &', self.ADBUserName, 60)

			time.sleep(0.5)
			SSH.close()

			# Launch the IPERF client on the EPC side for DL (true for ltebox and old open-air-cn
			# But for OAI-Rel14-CUPS, we launch from python executor
			launchFromEpc = True
2675
			launchFromModule = False
2676 2677
			if re.match('OAI-Rel14-CUPS', EPC.Type, re.IGNORECASE):
				launchFromEpc = False
2678 2679 2680 2681
			#if module
			if self.ue_id!='' and self.iperf :
				launchFromEpc = False
				launchfromModule = True
2682 2683 2684 2685
			# When using a docker-based deployment, IPERF client shall be launched from trf container
			launchFromTrfContainer = False
			if re.match('OAI-Rel14-Docker', EPC.Type, re.IGNORECASE):
				launchFromTrfContainer = True
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
			if launchFromEpc:
				SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
				SSH.command('cd ' + EPC.SourceCodePath + '/scripts', '\$', 5)
			iperf_time = self.Iperf_ComputeTime()
			time.sleep(0.5)

			if udpIperf:
				modified_options = self.Iperf_ComputeModifiedBW(idx, ue_num)
			else:
				modified_options = str(self.iperf_args)
			time.sleep(0.5)

			if launchFromEpc:
				SSH.command('rm -f iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
			else:
				if (os.path.isfile('iperf_' + self.testCase_id + '_' + device_id + '.log')):
					os.remove('iperf_' + self.testCase_id + '_' + device_id + '.log')
			if (useIperf3):
				SSH.command('stdbuf -o0 iperf3 -c ' + UE_IPAddress + ' ' + modified_options + ' 2>&1 | stdbuf -o0 tee iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', int(iperf_time)*5.0)

				clientStatus = 0
2707
				self.Iperf_analyzeV3Output(lock, UE_IPAddress, device_id, statusQueue,SSH)
2708 2709
			else:
				if launchFromEpc:
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
					if launchFromTrfContainer:
						if self.ueIperfVersion == self.dummyIperfVersion:
							prefix = ''
						else:
							prefix = ''
							if self.ueIperfVersion == '2.0.5':
								prefix = '/iperf-2.0.5/bin/'
						iperf_status = SSH.command('docker exec -it prod-trf-gen /bin/bash -c "' + prefix + 'iperf -c ' + UE_IPAddress + ' ' + modified_options + '" 2>&1 | tee iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', int(iperf_time)*5.0)
					else:
						iperf_status = SSH.command('stdbuf -o0 iperf -c ' + UE_IPAddress + ' ' + modified_options + ' 2>&1 | stdbuf -o0 tee iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', int(iperf_time)*5.0)
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
				else:
					if self.ueIperfVersion == self.dummyIperfVersion:
						prefix = ''
					else:
						prefix = ''
						if self.ueIperfVersion == '2.0.5':
							prefix = '/opt/iperf-2.0.5/bin/'
					cmd = prefix + 'iperf -c ' + UE_IPAddress + ' ' + modified_options + ' 2>&1 > iperf_' + self.testCase_id + '_' + device_id + '.log'
					message = cmd + '\n'
					logging.debug(cmd)
					ret = subprocess.run(cmd, shell=True)
					iperf_status = ret.returncode
2732
					SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_' + self.testCase_id + '_' + device_id + '.log', EPC.SourceCodePath + '/scripts')					
2733 2734 2735 2736 2737 2738 2739 2740 2741
					SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
					SSH.command('cat ' + EPC.SourceCodePath + '/scripts/iperf_' + self.testCase_id + '_' + device_id + '.log', '\$', 5)
				if iperf_status < 0:
					if launchFromEpc:
						SSH.close()
					message = 'iperf on UE (' + str(UE_IPAddress) + ') crashed due to TIMEOUT !'
					logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
					self.ping_iperf_wrong_exit(lock, UE_IPAddress, device_id, statusQueue, message)
					return
hardy's avatar
hardy committed
2742
				logging.debug('Into Iperf_analyzeV2Output client')
2743
				clientStatus = self.Iperf_analyzeV2Output(lock, UE_IPAddress, device_id, statusQueue, modified_options, EPC,SSH)
hardy's avatar
hardy committed
2744
				logging.debug('Iperf_analyzeV2Output clientStatus returned value = ' + str(clientStatus))
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
			SSH.close()

			# Kill the IPERF server that runs in background
			if (device_id == 'OAI-UE'):
				SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
				SSH.command('killall iperf', '\$', 5)
			else:
				SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
				if self.ADBCentralized:
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell ps | grep --color=never iperf | grep -v grep', '\$', 5)
				else:
					SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "ps" | grep --color=never iperf | grep -v grep\'', '\$', 60)
				result = re.search('shell +(?P<pid>\d+)', SSH.getBefore())
				if result is not None:
					pid_iperf = result.group('pid')
					if self.ADBCentralized:
						SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell kill -KILL ' + pid_iperf, '\$', 5)
					else:
						SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "kill -KILL ' + pid_iperf + '"\'', '\$', 60)
			SSH.close()
			# if the client report is absent, try to analyze the server log file
			if (clientStatus == -1):
				time.sleep(1)
				if (os.path.isfile('iperf_server_' + self.testCase_id + '_' + device_id + '.log')):
					os.remove('iperf_server_' + self.testCase_id + '_' + device_id + '.log')
				if (device_id == 'OAI-UE'):
					SSH.copyin(self.UEIPAddress, self.UEUserName, self.UEPassword, self.UESourceCodePath + '/cmake_targets/iperf_server_' + self.testCase_id + '_' + device_id + '.log', '.')
				else:
					SSH.copyin(self.ADBIPAddress, self.ADBUserName, self.ADBPassword, EPC.SourceCodePath + '/scripts/iperf_server_' + self.testCase_id + '_' + device_id + '.log', '.')
				# fromdos has to be called on the python executor not on ADB server
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
				cmd = 'fromdos -o iperf_server_' + self.testCase_id + '_' + device_id + '.log 2>&1 > /dev/null'
				try:
					subprocess.run(cmd, shell=True)
				except:
					pass
				cmd = 'dos2unix -o iperf_server_' + self.testCase_id + '_' + device_id + '.log 2>&1 > /dev/null'
				try:
					subprocess.run(cmd, shell=True)
				except:
					pass
2785 2786
				filename='iperf_server_' + self.testCase_id + '_' + device_id + '.log'
				self.Iperf_analyzeV2Server(lock, UE_IPAddress, device_id, statusQueue, modified_options,filename,0)
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798

			# in case of OAI UE: 
			if (device_id == 'OAI-UE'):
				if (os.path.isfile('iperf_server_' + self.testCase_id + '_' + device_id + '.log')):
					if not launchFromEpc:
						SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_server_' + self.testCase_id + '_' + device_id + '.log', EPC.SourceCodePath + '/scripts')
				else:
					SSH.copyin(self.UEIPAddress, self.UEUserName, self.UEPassword, self.UESourceCodePath + '/cmake_targets/iperf_server_' + self.testCase_id + '_' + device_id + '.log', '.')
					SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_server_' + self.testCase_id + '_' + device_id + '.log', EPC.SourceCodePath + '/scripts')
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

2799
	def IperfNoS1(self,HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS):
hardy's avatar
hardy committed
2800
		SSH = sshconnection.SSHConnection()
2801 2802 2803 2804 2805 2806 2807 2808
		if RAN.eNBIPAddress == '' or RAN.eNBUserName == '' or RAN.eNBPassword == '' or self.UEIPAddress == '' or self.UEUserName == '' or self.UEPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		check_eNB = True
		check_OAI_UE = True
		pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
		if (pStatus < 0):
			HTML.CreateHtmlTestRow(self.iperf_args, 'KO', pStatus)
2809
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
			return
		server_on_enb = re.search('-R', str(self.iperf_args))
		if server_on_enb is not None:
			iServerIPAddr = RAN.eNBIPAddress
			iServerUser = RAN.eNBUserName
			iServerPasswd = RAN.eNBPassword
			iClientIPAddr = self.UEIPAddress
			iClientUser = self.UEUserName
			iClientPasswd = self.UEPassword
		else:
			iServerIPAddr = self.UEIPAddress
			iServerUser = self.UEUserName
			iServerPasswd = self.UEPassword
			iClientIPAddr = RAN.eNBIPAddress
			iClientUser = RAN.eNBUserName
			iClientPasswd = RAN.eNBPassword
		if self.iperf_options != 'sink':
			# Starting the iperf server
			SSH.open(iServerIPAddr, iServerUser, iServerPasswd)
			# args SHALL be "-c client -u any"
			# -c 10.0.1.2 -u -b 1M -t 30 -i 1 -fm -B 10.0.1.1
			# -B 10.0.1.1 -u -s -i 1 -fm
			server_options = re.sub('-u.*$', '-u -s -i 1 -fm', str(self.iperf_args))
			server_options = server_options.replace('-c','-B')
			SSH.command('rm -f /tmp/tmp_iperf_server_' + self.testCase_id + '.log', '\$', 5)
			SSH.command('echo $USER; nohup iperf ' + server_options + ' > /tmp/tmp_iperf_server_' + self.testCase_id + '.log 2>&1 &', iServerUser, 5)
			time.sleep(0.5)
			SSH.close()

		# Starting the iperf client
		modified_options = self.Iperf_ComputeModifiedBW(0, 1)
		modified_options = modified_options.replace('-R','')
		iperf_time = self.Iperf_ComputeTime()
		SSH.open(iClientIPAddr, iClientUser, iClientPasswd)
		SSH.command('rm -f /tmp/tmp_iperf_' + self.testCase_id + '.log', '\$', 5)
		iperf_status = SSH.command('stdbuf -o0 iperf ' + modified_options + ' 2>&1 | stdbuf -o0 tee /tmp/tmp_iperf_' + self.testCase_id + '.log', '\$', int(iperf_time)*5.0)
		status_queue = SimpleQueue()
		lock = Lock()
		if iperf_status < 0:
			message = 'iperf on OAI UE crashed due to TIMEOUT !'
			logging.debug('\u001B[1;37;41m ' + message + ' \u001B[0m')
			clientStatus = -2
		else:
			if self.iperf_options == 'sink':
				clientStatus = 0
				status_queue.put(0)
				status_queue.put('OAI-UE')
				status_queue.put('10.0.1.2')
				status_queue.put('Sink Test : no check')
			else:
2860
				clientStatus = self.Iperf_analyzeV2Output(lock, '10.0.1.2', 'OAI-UE', status_queue, modified_options, EPC,SSH)
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
		SSH.close()

		# Stopping the iperf server
		if self.iperf_options != 'sink':
			SSH.open(iServerIPAddr, iServerUser, iServerPasswd)
			SSH.command('killall --signal SIGKILL iperf', '\$', 5)
			time.sleep(0.5)
			SSH.close()

		if (clientStatus == -1):
			if (os.path.isfile('iperf_server_' + self.testCase_id + '.log')):
				os.remove('iperf_server_' + self.testCase_id + '.log')
			SSH.copyin(iServerIPAddr, iServerUser, iServerPasswd, '/tmp/tmp_iperf_server_' + self.testCase_id + '.log', 'iperf_server_' + self.testCase_id + '_OAI-UE.log')
2874
			filename='iperf_server_' + self.testCase_id + '_OAI-UE.log'
2875
			self.Iperf_analyzeV2Server(lock, '10.0.1.2', 'OAI-UE', status_queue, modified_options,filename,0)
2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907

		# copying on the EPC server for logCollection
		if (clientStatus == -1):
			copyin_res = SSH.copyin(iServerIPAddr, iServerUser, iServerPasswd, '/tmp/tmp_iperf_server_' + self.testCase_id + '.log', 'iperf_server_' + self.testCase_id + '_OAI-UE.log')
			if (copyin_res == 0):
				SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_server_' + self.testCase_id + '_OAI-UE.log', EPC.SourceCodePath + '/scripts')
		copyin_res = SSH.copyin(iClientIPAddr, iClientUser, iClientPasswd, '/tmp/tmp_iperf_' + self.testCase_id + '.log', 'iperf_' + self.testCase_id + '_OAI-UE.log')
		if (copyin_res == 0):
			SSH.copyout(EPC.IPAddress, EPC.UserName, EPC.Password, 'iperf_' + self.testCase_id + '_OAI-UE.log', EPC.SourceCodePath + '/scripts')
		iperf_noperf = False
		if status_queue.empty():
			iperf_status = False
		else:
			iperf_status = True
		html_queue = SimpleQueue()
		while (not status_queue.empty()):
			count = status_queue.get()
			if (count < 0):
				iperf_status = False
			if (count > 0):
				iperf_noperf = True
			device_id = status_queue.get()
			ip_addr = status_queue.get()
			message = status_queue.get()
			html_cell = '<pre style="background-color:white">UE (' + device_id + ')\nIP Address  : ' + ip_addr + '\n' + message + '</pre>'
			html_queue.put(html_cell)
		if (iperf_noperf and iperf_status):
			HTML.CreateHtmlTestRowQueue(self.iperf_args, 'PERF NOT MET', len(self.UEDevices), html_queue)
		elif (iperf_status):
			HTML.CreateHtmlTestRowQueue(self.iperf_args, 'OK', len(self.UEDevices), html_queue)
		else:
			HTML.CreateHtmlTestRowQueue(self.iperf_args, 'KO', len(self.UEDevices), html_queue)
2908
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
2909

2910
	def Iperf(self,HTML,RAN,EPC,COTS_UE, InfraUE,CONTAINERS):
2911 2912
		result = re.search('noS1', str(RAN.Initialize_eNB_args))
		if result is not None:
2913
			self.IperfNoS1(HTML,RAN,EPC,COTS_UE,InfraUE,CONTAINERS)
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
			return
		if EPC.IPAddress == '' or EPC.UserName == '' or EPC.Password == '' or EPC.SourceCodePath == '' or self.ADBIPAddress == '' or self.ADBUserName == '' or self.ADBPassword == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
		check_eNB = True
		if (len(self.UEDevices) == 1) and (self.UEDevices[0] == 'OAI-UE'):
			check_OAI_UE = True
		else:
			check_OAI_UE = False
		pStatus = self.CheckProcessExist(check_eNB, check_OAI_UE,RAN,EPC)
		if (pStatus < 0):
			HTML.CreateHtmlTestRow(self.iperf_args, 'KO', pStatus)
2926
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
2927 2928
			return

2929
		if self.ue_id=="":#is not a module, follow legacy code
2930 2931 2932
			ueIpStatus = self.GetAllUEIPAddresses()
			if (ueIpStatus < 0):
				HTML.CreateHtmlTestRow(self.iperf_args, 'KO', CONST.UE_IP_ADDRESS_ISSUE)
2933
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
2934
				return
2935
		else: #is a module
2936
			self.UEIPAddresses=[]
2937 2938
			Module_UE = cls_module_ue.Module_UE(InfraUE.ci_ue_infra[self.ue_id])
			Module_UE.GetModuleIPAddress()
2939
			self.UEIPAddresses.append(Module_UE.UEIPAddress)
2940 2941 2942 2943




2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959
		self.dummyIperfVersion = '2.0.10'
		#cmd = 'iperf --version'
		#logging.debug(cmd + '\n')
		#iperfStdout = subprocess.check_output(cmd, shell=True, universal_newlines=True)
		#result = re.search('iperf version 2.0.5', str(iperfStdout.strip()))
		#if result is not None:
		#	dummyIperfVersion = '2.0.5'
		#result = re.search('iperf version 2.0.10', str(iperfStdout.strip()))
		#if result is not None:
		#	dummyIperfVersion = '2.0.10'

		multi_jobs = []
		i = 0
		ue_num = len(self.UEIPAddresses)
		lock = Lock()
		status_queue = SimpleQueue()
2960
		logging.debug(self.UEIPAddresses)
2961 2962
		for UE_IPAddress in self.UEIPAddresses:
			device_id = self.UEDevices[i]
2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
        	#special quick and dirty treatment for modules, iperf to be restructured
			if self.ue_id!="": #is module
				device_id = Module_UE.ID + "-" + Module_UE.Kind
				p = Process(target = self.Iperf_Module ,args = (lock, UE_IPAddress, device_id, i, ue_num, status_queue, EPC, Module_UE,))
			else: #legacy code
				p = Process(target = self.Iperf_common, args = (lock, UE_IPAddress, device_id, i, ue_num, status_queue, EPC, ))
			p.daemon = True
			p.start()
			multi_jobs.append(p)
			i = i + 1
2973 2974 2975 2976 2977
		for job in multi_jobs:
			job.join()

		if (status_queue.empty()):
			HTML.CreateHtmlTestRow(self.iperf_args, 'KO', CONST.ALL_PROCESSES_OK)
2978
			self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999
		else:
			iperf_status = True
			iperf_noperf = False
			html_queue = SimpleQueue()
			while (not status_queue.empty()):
				count = status_queue.get()
				if (count < 0):
					iperf_status = False
				if (count > 0):
					iperf_noperf = True
				device_id = status_queue.get()
				ip_addr = status_queue.get()
				message = status_queue.get()
				html_cell = '<pre style="background-color:white">UE (' + device_id + ')\nIP Address  : ' + ip_addr + '\n' + message + '</pre>'
				html_queue.put(html_cell)
			if (iperf_noperf and iperf_status):
				HTML.CreateHtmlTestRowQueue(self.iperf_args, 'PERF NOT MET', len(self.UEDevices), html_queue)
			elif (iperf_status):
				HTML.CreateHtmlTestRowQueue(self.iperf_args, 'OK', len(self.UEDevices), html_queue)
			else:
				HTML.CreateHtmlTestRowQueue(self.iperf_args, 'KO', len(self.UEDevices), html_queue)
3000
				self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
3001 3002 3003 3004 3005 3006 3007 3008

	def CheckProcessExist(self, check_eNB, check_OAI_UE,RAN,EPC):
		multi_jobs = []
		status_queue = SimpleQueue()
		# in noS1 config, no need to check status from EPC
		# in gNB also currently no need to check
		result = re.search('noS1|band78', str(RAN.Initialize_eNB_args))
		if result is None:
hardy's avatar
hardy committed
3009
			p = Process(target = EPC.CheckHSSProcess, args = (status_queue,))
3010 3011 3012
			p.daemon = True
			p.start()
			multi_jobs.append(p)
hardy's avatar
hardy committed
3013
			p = Process(target = EPC.CheckMMEProcess, args = (status_queue,))
3014 3015 3016
			p.daemon = True
			p.start()
			multi_jobs.append(p)
hardy's avatar
hardy committed
3017
			p = Process(target = EPC.CheckSPGWProcess, args = (status_queue,))
3018 3019 3020 3021 3022 3023 3024
			p.daemon = True
			p.start()
			multi_jobs.append(p)
		else:
			if (check_eNB == False) and (check_OAI_UE == False):
				return 0
		if check_eNB:
hardy's avatar
hardy committed
3025
			p = Process(target = RAN.CheckeNBProcess, args = (status_queue,))
3026 3027 3028 3029
			p.daemon = True
			p.start()
			multi_jobs.append(p)
		if check_OAI_UE:
hardy's avatar
hardy committed
3030
			p = Process(target = self.CheckOAIUEProcess, args = (status_queue,))
3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
			p.daemon = True
			p.start()
			multi_jobs.append(p)
		for job in multi_jobs:
			job.join()

		if (status_queue.empty()):
			return -15
		else:
			result = 0
			while (not status_queue.empty()):
				status = status_queue.get()
				if (status < 0):
					result = status
			if result == CONST.ENB_PROCESS_FAILED:
				fileCheck = re.search('enb_', str(RAN.eNBLogFiles[0]))
				if fileCheck is not None:
					SSH.copyin(RAN.eNBIPAddress, RAN.eNBUserName, RAN.eNBPassword, RAN.eNBSourceCodePath + '/cmake_targets/' + RAN.eNBLogFiles[0], '.')
					logStatus = RAN.AnalyzeLogFile_eNB(RAN.eNBLogFiles[0])
					if logStatus < 0:
						result = logStatus
					RAN.eNBLogFiles[0]=''
				if RAN.flexranCtrlInstalled and RAN.flexranCtrlStarted:
					self.TerminateFlexranCtrl()
			return result

3057
	def CheckOAIUEProcessExist(self, initialize_OAI_UE_flag,HTML,RAN):
3058 3059 3060
		multi_jobs = []
		status_queue = SimpleQueue()
		if initialize_OAI_UE_flag == False:
hardy's avatar
hardy committed
3061
			p = Process(target = self.CheckOAIUEProcess, args = (status_queue,))
3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
			p.daemon = True
			p.start()
			multi_jobs.append(p)
		for job in multi_jobs:
			job.join()

		if (status_queue.empty()):
			return -15
		else:
			result = 0
			while (not status_queue.empty()):
				status = status_queue.get()
				if (status < 0):
					result = status
			if result == CONST.OAI_UE_PROCESS_FAILED:
				fileCheck = re.search('ue_', str(self.UELogFile))
				if fileCheck is not None:
					SSH.copyin(self.UEIPAddress, self.UEUserName, self.UEPassword, self.UESourceCodePath + '/cmake_targets/' + self.UELogFile, '.')
3080
					logStatus = self.AnalyzeLogFile_UE(self.UELogFile,HTML,RAN)
3081 3082 3083 3084 3085 3086
					if logStatus < 0:
						result = logStatus
			return result

	def CheckOAIUEProcess(self, status_queue):
		try:
hardy's avatar
hardy committed
3087
			SSH = sshconnection.SSHConnection()
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100
			SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
			SSH.command('stdbuf -o0 ps -aux | grep --color=never ' + self.air_interface + ' | grep -v grep', '\$', 5)
			result = re.search(self.air_interface, SSH.getBefore())
			if result is None:
				logging.debug('\u001B[1;37;41m OAI UE Process Not Found! \u001B[0m')
				status_queue.put(CONST.OAI_UE_PROCESS_FAILED)
			else:
				status_queue.put(CONST.OAI_UE_PROCESS_OK)
			SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)


3101
	def AnalyzeLogFile_UE(self, UElogFile,HTML,RAN):
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
		if (not os.path.isfile('./' + UElogFile)):
			return -1
		ue_log_file = open('./' + UElogFile, 'r')
		exitSignalReceived = False
		foundAssertion = False
		msgAssertion = ''
		msgLine = 0
		foundSegFault = False
		foundRealTimeIssue = False
		uciStatMsgCount = 0
		pdcpDataReqFailedCount = 0
		badDciCount = 0
		f1aRetransmissionCount = 0
		fatalErrorCount = 0
		macBsrTimerExpiredCount = 0
		rrcConnectionRecfgComplete = 0
		no_cell_sync_found = False
		mib_found = False
		frequency_found = False
		plmn_found = False
		nrUEFlag = False
		nrDecodeMib = 0
		nrFoundDCI = 0
		nrCRCOK = 0
		mbms_messages = 0
		HTML.htmlUEFailureMsg=''
		global_status = CONST.ALL_PROCESSES_OK
		for line in ue_log_file.readlines():
			result = re.search('nr_synchro_time', str(line))
			if result is not None:
				nrUEFlag = True
			if nrUEFlag:
				result = re.search('decode mib', str(line))
				if result is not None:
					nrDecodeMib += 1
				result = re.search('found 1 DCIs', str(line))
				if result is not None:
					nrFoundDCI += 1
				result = re.search('CRC OK', str(line))
				if result is not None:
					nrCRCOK += 1
			result = re.search('Exiting OAI softmodem', str(line))
			if result is not None:
				exitSignalReceived = True
			result = re.search('System error|[Ss]egmentation [Ff]ault|======= Backtrace: =========|======= Memory map: ========', str(line))
			if result is not None and not exitSignalReceived:
				foundSegFault = True
			result = re.search('[Cc]ore [dD]ump', str(line))
			if result is not None and not exitSignalReceived:
				foundSegFault = True
			result = re.search('[Aa]ssertion', str(line))
			if result is not None and not exitSignalReceived:
				foundAssertion = True
			result = re.search('LLL', str(line))
			if result is not None and not exitSignalReceived:
				foundRealTimeIssue = True
			if foundAssertion and (msgLine < 3):
				msgLine += 1
				msgAssertion += str(line)
			result = re.search('uci->stat', str(line))
			if result is not None and not exitSignalReceived:
				uciStatMsgCount += 1
			result = re.search('PDCP data request failed', str(line))
			if result is not None and not exitSignalReceived:
				pdcpDataReqFailedCount += 1
			result = re.search('bad DCI 1', str(line))
			if result is not None and not exitSignalReceived:
				badDciCount += 1
			result = re.search('Format1A Retransmission but TBS are different', str(line))
			if result is not None and not exitSignalReceived:
				f1aRetransmissionCount += 1
			result = re.search('FATAL ERROR', str(line))
			if result is not None and not exitSignalReceived:
				fatalErrorCount += 1
			result = re.search('MAC BSR Triggered ReTxBSR Timer expiry', str(line))
			if result is not None and not exitSignalReceived:
				macBsrTimerExpiredCount += 1
			result = re.search('Generating RRCConnectionReconfigurationComplete', str(line))
			if result is not None:
				rrcConnectionRecfgComplete += 1
			# No cell synchronization found, abandoning
			result = re.search('No cell synchronization found, abandoning', str(line))
			if result is not None:
				no_cell_sync_found = True
			if RAN.eNBmbmsEnables[0]:
				result = re.search('TRIED TO PUSH MBMS DATA', str(line))
				if result is not None:
					mbms_messages += 1
			result = re.search("MIB Information => ([a-zA-Z]{1,10}), ([a-zA-Z]{1,10}), NidCell (?P<nidcell>\d{1,3}), N_RB_DL (?P<n_rb_dl>\d{1,3}), PHICH DURATION (?P<phich_duration>\d), PHICH RESOURCE (?P<phich_resource>.{1,4}), TX_ANT (?P<tx_ant>\d)", str(line))
			if result is not None and (not mib_found):
				try:
					mibMsg = "MIB Information: " + result.group(1) + ', ' + result.group(2)
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg + '\n'
					logging.debug('\033[94m' + mibMsg + '\033[0m')
					mibMsg = "    nidcell = " + result.group('nidcell')
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg
					logging.debug('\033[94m' + mibMsg + '\033[0m')
					mibMsg = "    n_rb_dl = " + result.group('n_rb_dl')
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg + '\n'
					logging.debug('\033[94m' + mibMsg + '\033[0m')
					mibMsg = "    phich_duration = " + result.group('phich_duration')
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg
					logging.debug('\033[94m' + mibMsg + '\033[0m')
					mibMsg = "    phich_resource = " + result.group('phich_resource')
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg + '\n'
					logging.debug('\033[94m' + mibMsg + '\033[0m')
					mibMsg = "    tx_ant = " + result.group('tx_ant')
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg + '\n'
					logging.debug('\033[94m' + mibMsg + '\033[0m')
					mib_found = True
				except Exception as e:
					logging.error('\033[91m' + "MIB marker was not found" + '\033[0m')
			result = re.search("Measured Carrier Frequency (?P<measured_carrier_frequency>\d{1,15}) Hz", str(line))
			if result is not None and (not frequency_found):
				try:
					mibMsg = "Measured Carrier Frequency = " + result.group('measured_carrier_frequency') + ' Hz'
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg + '\n'
					logging.debug('\033[94m' + mibMsg + '\033[0m')
					frequency_found = True
				except Exception as e:
					logging.error('\033[91m' + "Measured Carrier Frequency not found" + '\033[0m')
			result = re.search("PLMN MCC (?P<mcc>\d{1,3}), MNC (?P<mnc>\d{1,3}), TAC", str(line))
			if result is not None and (not plmn_found):
				try:
					mibMsg = 'PLMN MCC = ' + result.group('mcc') + ' MNC = ' + result.group('mnc')
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg + '\n'
					logging.debug('\033[94m' + mibMsg + '\033[0m')
					plmn_found = True
				except Exception as e:
					logging.error('\033[91m' + "PLMN not found" + '\033[0m')
			result = re.search("Found (?P<operator>[\w,\s]{1,15}) \(name from internal table\)", str(line))
			if result is not None:
				try:
					mibMsg = "The operator is: " + result.group('operator')
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg + '\n'
					logging.debug('\033[94m' + mibMsg + '\033[0m')
				except Exception as e:
					logging.error('\033[91m' + "Operator name not found" + '\033[0m')
			result = re.search("SIB5 InterFreqCarrierFreq element (.{1,4})/(.{1,4})", str(line))
			if result is not None:
				try:
					mibMsg = "SIB5 InterFreqCarrierFreq element " + result.group(1) + '/' + result.group(2)
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + mibMsg + ' -> '
					logging.debug('\033[94m' + mibMsg + '\033[0m')
				except Exception as e:
					logging.error('\033[91m' + "SIB5 InterFreqCarrierFreq element not found" + '\033[0m')
			result = re.search("DL Carrier Frequency/ARFCN : \-*(?P<carrier_frequency>\d{1,15}/\d{1,4})", str(line))
			if result is not None:
				try:
					freq = result.group('carrier_frequency')
					new_freq = re.sub('/[0-9]+','',freq)
					float_freq = float(new_freq) / 1000000
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + 'DL Freq: ' + ('%.1f' % float_freq) + ' MHz'
					logging.debug('\033[94m' + "    DL Carrier Frequency is: " + str(freq) + '\033[0m')
				except Exception as e:
					logging.error('\033[91m' + "    DL Carrier Frequency not found" + '\033[0m')
			result = re.search("AllowedMeasBandwidth : (?P<allowed_bandwidth>\d{1,7})", str(line))
			if result is not None:
				try:
					prb = result.group('allowed_bandwidth')
					HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + ' -- PRB: ' + prb + '\n'
					logging.debug('\033[94m' + "    AllowedMeasBandwidth: " + prb + '\033[0m')
				except Exception as e:
					logging.error('\033[91m' + "    AllowedMeasBandwidth not found" + '\033[0m')
		ue_log_file.close()
		if rrcConnectionRecfgComplete > 0:
			statMsg = 'UE connected to eNB (' + str(rrcConnectionRecfgComplete) + ' RRCConnectionReconfigurationComplete message(s) generated)'
			logging.debug('\033[94m' + statMsg + '\033[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if nrUEFlag:
			if nrDecodeMib > 0:
				statMsg = 'UE showed ' + str(nrDecodeMib) + ' MIB decode message(s)'
				logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
				HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
			if nrFoundDCI > 0:
				statMsg = 'UE showed ' + str(nrFoundDCI) + ' DCI found message(s)'
				logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
				HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
			if nrCRCOK > 0:
				statMsg = 'UE showed ' + str(nrCRCOK) + ' PDSCH decoding message(s)'
				logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
				HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
			if not frequency_found:
				statMsg = 'NR-UE could NOT synch!'
				logging.error('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
				HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if uciStatMsgCount > 0:
			statMsg = 'UE showed ' + str(uciStatMsgCount) + ' "uci->stat" message(s)'
			logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if pdcpDataReqFailedCount > 0:
			statMsg = 'UE showed ' + str(pdcpDataReqFailedCount) + ' "PDCP data request failed" message(s)'
			logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if badDciCount > 0:
			statMsg = 'UE showed ' + str(badDciCount) + ' "bad DCI 1(A)" message(s)'
			logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if f1aRetransmissionCount > 0:
			statMsg = 'UE showed ' + str(f1aRetransmissionCount) + ' "Format1A Retransmission but TBS are different" message(s)'
			logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if fatalErrorCount > 0:
			statMsg = 'UE showed ' + str(fatalErrorCount) + ' "FATAL ERROR:" message(s)'
			logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if macBsrTimerExpiredCount > 0:
			statMsg = 'UE showed ' + str(fatalErrorCount) + ' "MAC BSR Triggered ReTxBSR Timer expiry" message(s)'
			logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if RAN.eNBmbmsEnables[0]:
			if mbms_messages > 0:
				statMsg = 'UE showed ' + str(mbms_messages) + ' "TRIED TO PUSH MBMS DATA" message(s)'
				logging.debug('\u001B[1;30;43m ' + statMsg + ' \u001B[0m')
			else:
				statMsg = 'UE did NOT SHOW "TRIED TO PUSH MBMS DATA" message(s)'
				logging.debug('\u001B[1;30;41m ' + statMsg + ' \u001B[0m')
				global_status = CONST.OAI_UE_PROCESS_NO_MBMS_MSGS
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + statMsg + '\n'
		if foundSegFault:
			logging.debug('\u001B[1;37;41m UE ended with a Segmentation Fault! \u001B[0m')
			if not nrUEFlag:
				global_status = CONST.OAI_UE_PROCESS_SEG_FAULT
			else:
				if not frequency_found:
					global_status = CONST.OAI_UE_PROCESS_SEG_FAULT
		if foundAssertion:
			logging.debug('\u001B[1;30;43m UE showed an assertion! \u001B[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + 'UE showed an assertion!\n'
			if not nrUEFlag:
				if not mib_found or not frequency_found:
					global_status = CONST.OAI_UE_PROCESS_ASSERTION
			else:
				if not frequency_found:
					global_status = CONST.OAI_UE_PROCESS_ASSERTION
		if foundRealTimeIssue:
			logging.debug('\u001B[1;37;41m UE faced real time issues! \u001B[0m')
			HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + 'UE faced real time issues!\n'
		if nrUEFlag:
			if not frequency_found:
				global_status = CONST.OAI_UE_PROCESS_COULD_NOT_SYNC
		else:
			if no_cell_sync_found and not mib_found:
				logging.debug('\u001B[1;37;41m UE could not synchronize ! \u001B[0m')
				HTML.htmlUEFailureMsg=HTML.htmlUEFailureMsg + 'UE could not synchronize!\n'
				global_status = CONST.OAI_UE_PROCESS_COULD_NOT_SYNC
		return global_status


	def TerminateFlexranCtrl(self,HTML,RAN,EPC):
		if RAN.flexranCtrlInstalled == False or RAN.flexranCtrlStarted == False:
			return
		if EPC.IPAddress == '' or EPC.UserName == '' or EPC.Password == '':
			HELP.GenericHelp(CONST.Version)
			sys.exit('Insufficient Parameter')
hardy's avatar
hardy committed
3357
		SSH = sshconnection.SSHConnection()
3358 3359 3360 3361 3362 3363 3364 3365 3366
		SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
		SSH.command('echo ' + EPC.Password + ' | sudo -S daemon --name=flexran_rtc_daemon --stop', '\$', 5)
		time.sleep(1)
		SSH.command('echo ' + EPC.Password + ' | sudo -S killall --signal SIGKILL rt_controller', '\$', 5)
		time.sleep(1)
		SSH.close()
		RAN.flexranCtrlStarted=False
		HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)

3367
	def TerminateUE_common(self, device_id, idx,COTS_UE):
3368
		try:
hardy's avatar
hardy committed
3369
			SSH = sshconnection.SSHConnection()
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401
			SSH.open(self.ADBIPAddress, self.ADBUserName, self.ADBPassword)
			# back in airplane mode on (ie radio off)
			if self.ADBCentralized:
				#RH quick add on to intgrate cots control defined by yaml
				#if device Id exists in yaml dictionary, we execute the new procedure defined in cots_ue class
				#otherwise we use the legacy procedure 
				if COTS_UE.Check_Exists(device_id):
					#switch device to Airplane mode ON (ie Radio OFF)
					COTS_UE.Set_Airplane(device_id, 'ON')
				elif device_id == '84B7N16418004022':
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "su - root -c /data/local/tmp/off"', '\$', 60)
				else:
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell /data/local/tmp/off', '\$', 60)
			else:
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' ' + self.UEDevicesOffCmd[idx], '\$', 60)
			logging.debug('\u001B[1mUE (' + device_id + ') Detach Completed\u001B[0m')

			if self.ADBCentralized:
				SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "ps | grep --color=never iperf | grep -v grep"', '\$', 5)
			else:
				SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "ps | grep --color=never iperf | grep -v grep"\'', '\$', 60)
			result = re.search('shell +(?P<pid>\d+)', SSH.getBefore())
			if result is not None:
				pid_iperf = result.group('pid')
				if self.ADBCentralized:
					SSH.command('stdbuf -o0 adb -s ' + device_id + ' shell "kill -KILL ' + pid_iperf + '"', '\$', 5)
				else:
					SSH.command('ssh ' + self.UEDevicesRemoteUser[idx] + '@' + self.UEDevicesRemoteServer[idx] + ' \'adb -s ' + device_id + ' shell "kill -KILL ' + pid_iperf + '"\'', '\$', 60)
			SSH.close()
		except:
			os.kill(os.getppid(),signal.SIGUSR1)

Remi Hardy's avatar
Remi Hardy committed
3402
	def TerminateUE(self,HTML,COTS_UE,InfraUE,ue_trace):
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
		if self.ue_id=='':#no ID specified, then it is a COTS controlled by ADB
			terminate_ue_flag = False
			self.GetAllUEDevices(terminate_ue_flag)
			multi_jobs = []
			i = 0
			for device_id in self.UEDevices:
				p = Process(target= self.TerminateUE_common, args = (device_id,i,COTS_UE,))
				p.daemon = True
				p.start()
				multi_jobs.append(p)
				i += 1
			for job in multi_jobs:
				job.join()
			HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)
		else: #if an ID is specified, it is a module from the yaml infrastructure file
			Module_UE = cls_module_ue.Module_UE(InfraUE.ci_ue_infra[self.ue_id])
Remi Hardy's avatar
Remi Hardy committed
3419
			Module_UE.ue_trace=ue_trace
3420 3421 3422 3423
			Module_UE.Command("detach")	
			Module_UE.DisableTrace()
			Module_UE.DisableCM()
			archive_destination=Module_UE.LogCollect()
Remi Hardy's avatar
Remi Hardy committed
3424 3425 3426 3427
			if Module_UE.ue_trace=='yes':
				HTML.CreateHtmlTestRow('QLog at : '+archive_destination, 'OK', CONST.ALL_PROCESSES_OK)
			else:
				HTML.CreateHtmlTestRow('QLog trace is disabled', 'OK', CONST.ALL_PROCESSES_OK)			
3428

3429
	def TerminateOAIUE(self,HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS):
hardy's avatar
hardy committed
3430
		SSH = sshconnection.SSHConnection()
3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
		SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
		SSH.command('cd ' + self.UESourceCodePath + '/cmake_targets', '\$', 5)
		SSH.command('ps -aux | grep --color=never softmodem | grep -v grep', '\$', 5)
		result = re.search('-uesoftmodem', SSH.getBefore())
		if result is not None:
			SSH.command('echo ' + self.UEPassword + ' | sudo -S killall --signal SIGINT -r .*-uesoftmodem || true', '\$', 5)
			time.sleep(10)
			SSH.command('ps -aux | grep --color=never softmodem | grep -v grep', '\$', 5)
			result = re.search('-uesoftmodem', SSH.getBefore())
			if result is not None:
				SSH.command('echo ' + self.UEPassword + ' | sudo -S killall --signal SIGKILL -r .*-uesoftmodem || true', '\$', 5)
				time.sleep(5)
		SSH.command('rm -f my-lte-uesoftmodem-run' + str(self.UE_instance) + '.sh', '\$', 5)
		SSH.close()
		result = re.search('ue_', str(self.UELogFile))
		if result is not None:
			copyin_res = SSH.copyin(self.UEIPAddress, self.UEUserName, self.UEPassword, self.UESourceCodePath + '/cmake_targets/' + self.UELogFile, '.')
			if (copyin_res == -1):
				logging.debug('\u001B[1;37;41m Could not copy UE logfile to analyze it! \u001B[0m')
				HTML.htmlUEFailureMsg='Could not copy UE logfile to analyze it!'
				HTML.CreateHtmlTestRow('N/A', 'KO', CONST.OAI_UE_PROCESS_NOLOGFILE_TO_ANALYZE, 'UE')
				self.UELogFile = ''
				return
			logging.debug('\u001B[1m Analyzing UE logfile \u001B[0m')
3455
			logStatus = self.AnalyzeLogFile_UE(self.UELogFile,HTML,RAN)
3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469
			result = re.search('--no-L2-connect', str(self.Initialize_OAI_UE_args))
			if result is not None:
				ueAction = 'Sniffing'
			else:
				ueAction = 'Connection'
			if (logStatus < 0):
				logging.debug('\u001B[1m' + ueAction + ' Failed \u001B[0m')
				HTML.htmlUEFailureMsg='<b>' + ueAction + ' Failed</b>\n' + HTML.htmlUEFailureMsg
				HTML.CreateHtmlTestRow('N/A', 'KO', logStatus, 'UE')
				if self.air_interface == 'lte-uesoftmodem':
					# In case of sniffing on commercial eNBs we have random results
					# Not an error then
					if (logStatus != CONST.OAI_UE_PROCESS_COULD_NOT_SYNC) or (ueAction != 'Sniffing'):
						self.Initialize_OAI_UE_args = ''
3470
						self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
3471 3472 3473
				else:
					if (logStatus == CONST.OAI_UE_PROCESS_COULD_NOT_SYNC):
						self.Initialize_OAI_UE_args = ''
3474
						self.AutoTerminateUEandeNB(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
3475 3476 3477 3478 3479 3480 3481 3482
			else:
				logging.debug('\u001B[1m' + ueAction + ' Completed \u001B[0m')
				HTML.htmlUEFailureMsg='<b>' + ueAction + ' Completed</b>\n' + HTML.htmlUEFailureMsg
				HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)
			self.UELogFile = ''
		else:
			HTML.CreateHtmlTestRow('N/A', 'OK', CONST.ALL_PROCESSES_OK)

3483
	def AutoTerminateUEandeNB(self,HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS):
3484 3485
		if (self.ADBIPAddress != 'none'):
			self.testCase_id = 'AUTO-KILL-UE'
3486
			HTML.testCase_id = self.testCase_id
3487
			self.desc = 'Automatic Termination of UE'
3488
			HTML.desc = self.desc
3489
			self.ShowTestID()
Remi Hardy's avatar
Remi Hardy committed
3490
			self.TerminateUE(HTML,COTS_UE,InfraUE,self.ue_trace)
3491 3492
		if (self.Initialize_OAI_UE_args != ''):
			self.testCase_id = 'AUTO-KILL-OAI-UE'
3493
			HTML.testCase_id = self.testCase_id
3494
			self.desc = 'Automatic Termination of OAI-UE'
3495
			HTML.desc = self.desc
3496
			self.ShowTestID()
hardy's avatar
hardy committed
3497
			self.TerminateOAIUE(HTML,RAN,COTS_UE,EPC,InfraUE,CONTAINERS)
3498
		if (RAN.Initialize_eNB_args != ''):
3499
			self.testCase_id = 'AUTO-KILL-RAN'
3500
			HTML.testCase_id = self.testCase_id
3501
			self.desc = 'Automatic Termination of all RAN nodes'
3502
			HTML.desc = self.desc
3503
			self.ShowTestID()
3504 3505
			#terminate all RAN nodes eNB/gNB/OCP
			for instance in range(0, len(RAN.air_interface)):
3506
				if RAN.air_interface[instance]!='':
3507 3508
					logging.debug('Auto Termination of Instance ' + str(instance) + ' : ' + RAN.air_interface[instance])
					RAN.eNB_instance=instance
Raphael Defosseux's avatar
Raphael Defosseux committed
3509
					RAN.TerminateeNB(HTML,EPC)
3510 3511
		if RAN.flexranCtrlInstalled and RAN.flexranCtrlStarted:
			self.testCase_id = 'AUTO-KILL-flexran-ctl'
3512
			HTML.testCase_id = self.testCase_id
3513
			self.desc = 'Automatic Termination of FlexRan CTL'
3514
			HTML.desc = self.desc
3515
			self.ShowTestID()
3516
			self.TerminateFlexranCtrl(HTML,RAN,EPC)
3517 3518 3519 3520 3521 3522 3523 3524 3525 3526
		if CONTAINERS.yamlPath[0] != '':
			self.testCase_id = 'AUTO-KILL-CONTAINERS'
			HTML.testCase_id = self.testCase_id
			self.desc = 'Automatic Termination of all RAN containers'
			HTML.desc = self.desc
			self.ShowTestID()
			for instance in range(0, len(CONTAINERS.yamlPath)):
				if CONTAINERS.yamlPath[instance]!='':
					CONTAINERS.eNB_instance=instance
					CONTAINERS.UndeployObject(HTML,RAN)
3527 3528
		RAN.prematureExit=True

hardy's avatar
hardy committed
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
	#this function is called only if eNB/gNB fails to start
	#RH to be re-factored
	def AutoTerminateeNB(self,HTML,RAN,EPC,CONTAINERS):
		if (RAN.Initialize_eNB_args != ''):
			self.testCase_id = 'AUTO-KILL-RAN'
			HTML.testCase_id = self.testCase_id
			self.desc = 'Automatic Termination of all RAN nodes'
			HTML.desc = self.desc
			self.ShowTestID()
			#terminate all RAN nodes eNB/gNB/OCP
			for instance in range(0, len(RAN.air_interface)):
				if RAN.air_interface[instance]!='':
					logging.debug('Auto Termination of Instance ' + str(instance) + ' : ' + RAN.air_interface[instance])
					RAN.eNB_instance=instance
					RAN.TerminateeNB(HTML,EPC)
		if RAN.flexranCtrlInstalled and RAN.flexranCtrlStarted:
			self.testCase_id = 'AUTO-KILL-flexran-ctl'
			HTML.testCase_id = self.testCase_id
			self.desc = 'Automatic Termination of FlexRan CTL'
			HTML.desc = self.desc
			self.ShowTestID()
			self.TerminateFlexranCtrl(HTML,RAN,EPC)
		if CONTAINERS.yamlPath[0] != '':
			self.testCase_id = 'AUTO-KILL-CONTAINERS'
			HTML.testCase_id = self.testCase_id
			self.desc = 'Automatic Termination of all RAN containers'
			HTML.desc = self.desc
			self.ShowTestID()
			for instance in range(0, len(CONTAINERS.yamlPath)):
				if CONTAINERS.yamlPath[instance]!='':
					CONTAINERS.eNB_instance=instance
					CONTAINERS.UndeployObject(HTML,RAN)
		RAN.prematureExit=True


3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
	def IdleSleep(self,HTML):
		time.sleep(self.idle_sleep_time)
		HTML.CreateHtmlTestRow(str(self.idle_sleep_time) + ' sec', 'OK', CONST.ALL_PROCESSES_OK)

	def X2_Status(self, idx, fileName):
		cmd = "curl --silent http://" + EPC.IPAddress + ":9999/stats | jq '.' > " + fileName
		message = cmd + '\n'
		logging.debug(cmd)
		subprocess.run(cmd, shell=True)
		if idx == 0:
			cmd = "jq '.mac_stats | length' " + fileName
			strNbEnbs = subprocess.check_output(cmd, shell=True, universal_newlines=True)
			self.x2NbENBs = int(strNbEnbs.strip())
		cnt = 0
		while cnt < self.x2NbENBs:
			cmd = "jq '.mac_stats[" + str(cnt) + "].bs_id' " + fileName
			bs_id = subprocess.check_output(cmd, shell=True, universal_newlines=True)
			self.x2ENBBsIds[idx].append(bs_id.strip())
			cmd = "jq '.mac_stats[" + str(cnt) + "].ue_mac_stats | length' " + fileName
			stNbUEs = subprocess.check_output(cmd, shell=True, universal_newlines=True)
			nbUEs = int(stNbUEs.strip())
			ueIdx = 0
			self.x2ENBConnectedUEs[idx].append([])
			while ueIdx < nbUEs:
				cmd = "jq '.mac_stats[" + str(cnt) + "].ue_mac_stats[" + str(ueIdx) + "].rnti' " + fileName
				rnti = subprocess.check_output(cmd, shell=True, universal_newlines=True)
				self.x2ENBConnectedUEs[idx][cnt].append(rnti.strip())
				ueIdx += 1
			cnt += 1

		msg = "FlexRan Controller is connected to " + str(self.x2NbENBs) + " eNB(s)"
		logging.debug(msg)
		message += msg + '\n'
		cnt = 0
		while cnt < self.x2NbENBs:
			msg = "   -- eNB: " + str(self.x2ENBBsIds[idx][cnt]) + " is connected to " + str(len(self.x2ENBConnectedUEs[idx][cnt])) + " UE(s)"
			logging.debug(msg)
			message += msg + '\n'
			ueIdx = 0
			while ueIdx < len(self.x2ENBConnectedUEs[idx][cnt]):
				msg = "      -- UE rnti: " + str(self.x2ENBConnectedUEs[idx][cnt][ueIdx])
				logging.debug(msg)
				message += msg + '\n'
				ueIdx += 1
			cnt += 1
		return message

	def Perform_X2_Handover(self,HTML,RAN,EPC):
		html_queue = SimpleQueue()
		fullMessage = '<pre style="background-color:white">'
		msg = 'Doing X2 Handover w/ option ' + self.x2_ho_options
		logging.debug(msg)
		fullMessage += msg + '\n'
		if self.x2_ho_options == 'network':
			if RAN.flexranCtrlInstalled and RAN.flexranCtrlStarted:
				self.x2ENBBsIds = []
				self.x2ENBConnectedUEs = []
				self.x2ENBBsIds.append([])
				self.x2ENBBsIds.append([])
				self.x2ENBConnectedUEs.append([])
				self.x2ENBConnectedUEs.append([])
				fullMessage += self.X2_Status(0, self.testCase_id + '_pre_ho.json') 

				msg = "Activating the X2 Net control on each eNB"
				logging.debug(msg)
				fullMessage += msg + '\n'
				eNB_cnt = self.x2NbENBs
				cnt = 0
				while cnt < eNB_cnt:
					cmd = "curl -XPOST http://" + EPC.IPAddress + ":9999/rrc/x2_ho_net_control/enb/" + str(self.x2ENBBsIds[0][cnt]) + "/1"
					logging.debug(cmd)
					fullMessage += cmd + '\n'
					subprocess.run(cmd, shell=True)
					cnt += 1
				# Waiting for the activation to be active
				time.sleep(10)
				msg = "Switching UE(s) from eNB to eNB"
				logging.debug(msg)
				fullMessage += msg + '\n'
				cnt = 0
				while cnt < eNB_cnt:
					ueIdx = 0
					while ueIdx < len(self.x2ENBConnectedUEs[0][cnt]):
						cmd = "curl -XPOST http://" + EPC.IPAddress() + ":9999/rrc/ho/senb/" + str(self.x2ENBBsIds[0][cnt]) + "/ue/" + str(self.x2ENBConnectedUEs[0][cnt][ueIdx]) + "/tenb/" + str(self.x2ENBBsIds[0][eNB_cnt - cnt - 1])
						logging.debug(cmd)
						fullMessage += cmd + '\n'
						subprocess.run(cmd, shell=True)
						ueIdx += 1
					cnt += 1
				time.sleep(10)
				# check
				logging.debug("Checking the Status after X2 Handover")
				fullMessage += self.X2_Status(1, self.testCase_id + '_post_ho.json') 
				cnt = 0
				x2Status = True
				while cnt < eNB_cnt:
					if len(self.x2ENBConnectedUEs[0][cnt]) == len(self.x2ENBConnectedUEs[1][cnt]):
						x2Status = False
					cnt += 1
				if x2Status:
					msg = "X2 Handover was successful"
					logging.debug(msg)
					fullMessage += msg + '</pre>'
					html_queue.put(fullMessage)
					HTML.CreateHtmlTestRowQueue('N/A', 'OK', len(self.UEDevices), html_queue)
				else:
					msg = "X2 Handover FAILED"
					logging.error(msg)
					fullMessage += msg + '</pre>'
					html_queue.put(fullMessage)
					HTML.CreateHtmlTestRowQueue('N/A', 'OK', len(self.UEDevices), html_queue)
			else:
				HTML.CreateHtmlTestRow('Cannot perform requested X2 Handover', 'KO', CONST.ALL_PROCESSES_OK)

	def LogCollectBuild(self,RAN):
hardy's avatar
hardy committed
3679
		SSH = sshconnection.SSHConnection()
3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695
		if (RAN.eNBIPAddress != '' and RAN.eNBUserName != '' and RAN.eNBPassword != ''):
			IPAddress = RAN.eNBIPAddress
			UserName = RAN.eNBUserName
			Password = RAN.eNBPassword
			SourceCodePath = RAN.eNBSourceCodePath
		elif (self.UEIPAddress != '' and self.UEUserName != '' and self.UEPassword != ''):
			IPAddress = self.UEIPAddress
			UserName = self.UEUserName
			Password = self.UEPassword
			SourceCodePath = self.UESourceCodePath
		else:
			sys.exit('Insufficient Parameter')
		SSH.open(IPAddress, UserName, Password)
		SSH.command('cd ' + SourceCodePath, '\$', 5)
		SSH.command('cd cmake_targets', '\$', 5)
		SSH.command('rm -f build.log.zip', '\$', 5)
3696
		SSH.command('zip -r build.log.zip build_log_*/*', '\$', 60)
3697
		SSH.close()
3698

3699
	def LogCollectPing(self,EPC):
hardy's avatar
hardy committed
3700
		SSH = sshconnection.SSHConnection()
3701 3702 3703 3704 3705 3706 3707 3708 3709
		SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
		SSH.command('cd ' + EPC.SourceCodePath, '\$', 5)
		SSH.command('cd scripts', '\$', 5)
		SSH.command('rm -f ping.log.zip', '\$', 5)
		SSH.command('zip ping.log.zip ping*.log', '\$', 60)
		SSH.command('rm ping*.log', '\$', 5)
		SSH.close()

	def LogCollectIperf(self,EPC):
hardy's avatar
hardy committed
3710
		SSH = sshconnection.SSHConnection()
3711 3712 3713 3714 3715 3716 3717 3718 3719
		SSH.open(EPC.IPAddress, EPC.UserName, EPC.Password)
		SSH.command('cd ' + EPC.SourceCodePath, '\$', 5)
		SSH.command('cd scripts', '\$', 5)
		SSH.command('rm -f iperf.log.zip', '\$', 5)
		SSH.command('zip iperf.log.zip iperf*.log', '\$', 60)
		SSH.command('rm iperf*.log', '\$', 5)
		SSH.close()
	
	def LogCollectOAIUE(self):
hardy's avatar
hardy committed
3720
		SSH = sshconnection.SSHConnection()
3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
		SSH.open(self.UEIPAddress, self.UEUserName, self.UEPassword)
		SSH.command('cd ' + self.UESourceCodePath, '\$', 5)
		SSH.command('cd cmake_targets', '\$', 5)
		SSH.command('echo ' + self.UEPassword + ' | sudo -S rm -f ue.log.zip', '\$', 5)
		SSH.command('echo ' + self.UEPassword + ' | sudo -S zip ue.log.zip ue*.log core* ue_*record.raw ue_*.pcap ue_*txt', '\$', 60)
		SSH.command('echo ' + self.UEPassword + ' | sudo -S rm ue*.log core* ue_*record.raw ue_*.pcap ue_*txt', '\$', 5)
		SSH.close()

	def RetrieveSystemVersion(self, machine,HTML,RAN):
		if RAN.eNBIPAddress == 'none' or self.UEIPAddress == 'none':
			HTML.OsVersion[0]='Ubuntu 16.04.5 LTS'
			HTML.KernelVersion[0]='4.15.0-45-generic'
			HTML.UhdVersion[0]='3.13.0.1-0'
			HTML.UsrpBoard[0]='B210'
			HTML.CpuNb[0]='4'
			HTML.CpuModel[0]='Intel(R) Core(TM) i5-6200U'
			HTML.CpuMHz[0]='2399.996 MHz'
			return 0
		if machine == 'eNB':
			if RAN.eNBIPAddress != '' and RAN.eNBUserName != '' and RAN.eNBPassword != '':
				IPAddress = RAN.eNBIPAddress
				UserName = RAN.eNBUserName
				Password = RAN.eNBPassword
				idx = 0
			else:
				return -1
		if machine == 'UE':
			if self.UEIPAddress != '' and self.UEUserName != '' and self.UEPassword != '':
				IPAddress = self.UEIPAddress
				UserName = self.UEUserName
				Password = self.UEPassword
				idx = 1
			else:
				return -1
hardy's avatar
hardy committed
3755 3756

		SSH = sshconnection.SSHConnection()
3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784
		SSH.open(IPAddress, UserName, Password)
		SSH.command('lsb_release -a', '\$', 5)
		result = re.search('Description:\\\\t(?P<os_type>[a-zA-Z0-9\-\_\.\ ]+)', SSH.getBefore())
		if result is not None:
			OsVersion = result.group('os_type')
			logging.debug('OS is: ' + OsVersion)
			HTML.OsVersion[idx]=OsVersion
		else:
			SSH.command('hostnamectl', '\$', 5)
			result = re.search('Operating System: (?P<os_type>[a-zA-Z0-9\-\_\.\ ]+)', SSH.getBefore())
			if result is not None:
				OsVersion = result.group('os_type')
				if OsVersion == 'CentOS Linux 7 ':
					SSH.command('cat /etc/redhat-release', '\$', 5)
					result = re.search('CentOS Linux release (?P<os_version>[0-9\.]+)', SSH.getBefore())
					if result is not None:
						OsVersion = OsVersion.replace('7 ', result.group('os_version'))
				logging.debug('OS is: ' + OsVersion)
				HTML.OsVersion[idx]=OsVersion
		SSH.command('uname -r', '\$', 5)
		result = re.search('uname -r\\\\r\\\\n(?P<kernel_version>[a-zA-Z0-9\-\_\.]+)', SSH.getBefore())
		if result is not None:
			KernelVersion = result.group('kernel_version')
			logging.debug('Kernel Version is: ' + KernelVersion)
			HTML.KernelVersion[idx]=KernelVersion
		SSH.command('dpkg --list | egrep --color=never libuhd003', '\$', 5)
		result = re.search('libuhd003:amd64 *(?P<uhd_version>[0-9\.]+)', SSH.getBefore())
		if result is not None:
3785
			UhdVersion = result.group('uhd_version')
3786 3787 3788 3789 3790 3791
			logging.debug('UHD Version is: ' + UhdVersion)
			HTML.UhdVersion[idx]=UhdVersion
		else:
			SSH.command('uhd_config_info --version', '\$', 5)
			result = re.search('UHD (?P<uhd_version>[a-zA-Z0-9\.\-]+)', SSH.getBefore())
			if result is not None:
3792
				UhdVersion = result.group('uhd_version')
3793 3794
				logging.debug('UHD Version is: ' + UhdVersion)
				HTML.UhdVersion[idx]=UhdVersion
3795
		SSH.command('echo ' + Password + ' | sudo -S uhd_find_devices', '\$', 180)
3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820
		usrp_boards = re.findall('product: ([0-9A-Za-z]+)\\\\r\\\\n', SSH.getBefore())
		count = 0
		for board in usrp_boards:
			if count == 0:
				UsrpBoard = board
			else:
				UsrpBoard += ',' + board
			count += 1
		if count > 0:
			logging.debug('USRP Board(s) : ' + UsrpBoard)
			HTML.UsrpBoard[idx]=UsrpBoard
		SSH.command('lscpu', '\$', 5)
		result = re.search('CPU\(s\): *(?P<nb_cpus>[0-9]+).*Model name: *(?P<model>[a-zA-Z0-9\-\_\.\ \(\)]+).*CPU MHz: *(?P<cpu_mhz>[0-9\.]+)', SSH.getBefore())
		if result is not None:
			CpuNb = result.group('nb_cpus')
			logging.debug('nb_cpus: ' + CpuNb)
			HTML.CpuNb[idx]=CpuNb
			CpuModel = result.group('model')
			logging.debug('model: ' + CpuModel)
			HTML.CpuModel[idx]=CpuModel
			CpuMHz = result.group('cpu_mhz') + ' MHz'
			logging.debug('cpu_mhz: ' + CpuMHz)
			HTML.CpuMHz[idx]=CpuMHz
		SSH.close()

3821 3822 3823 3824 3825 3826
	def ConditionalExit(self):
		if self.testUnstable:
			if self.testStabilityPointReached or self.testMinStableId == '999999':
				sys.exit(0)
		sys.exit(1)

3827 3828 3829 3830
	def ShowTestID(self):
		logging.debug('\u001B[1m----------------------------------------\u001B[0m')
		logging.debug('\u001B[1mTest ID:' + self.testCase_id + '\u001B[0m')
		logging.debug('\u001B[1m' + self.desc + '\u001B[0m')
Remi Hardy's avatar
Remi Hardy committed
3831
		logging.debug('\u001B[1m----------------------------------------\u001B[0m')