Debian Codegraph @

Xpjproject/tests/pjsua/mod_sipp.py

raw symbols SCIP
1
2 ## Automatic test module for SIPp.
3 ##
4 ## This module will need a test driver for each SIPp scenario:
5 ## - For simple scenario, i.e: make/receive call (including auth), this
6 ## test module can auto-generate a default test driver, i.e: make call
7 ## or apply auto answer. Just name the SIPp scenario using "uas" or
8 ## "uac" prefix accordingly.
9 ## - Custom test driver can be defined in a python script file containing
10 ## a list of the PJSUA instances and another list for PJSUA expects/
11 ## commands. The custom test driver file must use the same filename as
12 ## the SIPp XML scenario. See samples of SIPp scenario + its driver
13 ## in tests/pjsua/scripts-sipp/ folder for detail.
14 ##
15 ## Here are defined macros that can be used in the custom driver:
16 ## - $SIPP_PORT : SIPp binding port
17 ## - $SIPP_URI : SIPp SIP URI
18 ## - $PJSUA_PORT[N] : binding port of PJSUA instance #N
19 ## - $PJSUA_URI[N] : SIP URI of PJSUA instance #N
20 import ctypes
21 import time
22 import sys
23 import os
24 import re
25 import subprocess
26 from inc_cfg import *
27 import inc_const
28 import inc_util as util
29
30 # flags that test is running in Unix
31 G_INUNIX = False
32 if sys.platform.lower().find("win32")!=-1 or sys.platform.lower().find("microsoft")!=-1:
33 G_INUNIX = False
34 else:
35 G_INUNIX = True
36
37 # /dev/null handle, for redirecting output when SIPP is not in background mode
38 FDEVNULL = None
39
40 # SIPp executable path and param
41 #SIPP_PATH = '"C:\\devs\\bin\\Sipp_3.2\\sipp.exe"'
42 SIPP_PATH = 'sipp'
43 SIPP_PORT = 50070
44 SIPP_PARAM = "-m 1 -i 127.0.0.1 -p " + str(SIPP_PORT)
45 SIPP_TIMEOUT = 60
46 # On BG mode, SIPp doesn't require special terminal
47 # On non-BG mode, on win, it needs env var: "TERMINFO=c:\cygwin\usr\share\terminfo"
48 # TODO: on unix with BG mode, waitpid() always fails, need to be fixed
49 SIPP_BG_MODE = False
50 #SIPP_BG_MODE = not G_INUNIX
51
52 # Will be updated based on the test driver file (a .py file whose the same name as SIPp XML file)
53 PJSUA_INST_PARAM = []
54 PJSUA_EXPECTS = []
55
56 # Default PJSUA param if test driver is not available:
57 # - no-tcp as SIPp is on UDP only
58 # - id, username, and realm: to allow PJSUA sending re-INVITE with auth after receiving 401/407 response
59 PJSUA_DEF_PARAM = "--null-audio --max-calls=1 --no-tcp --id=sip:a@localhost --username=a --realm=*"
60
61 # Get SIPp scenario (XML file)
62 SIPP_SCEN_XML = ""
63 if ARGS[1].endswith('.xml'):
64 SIPP_SCEN_XML = ARGS[1]
65 else:
66 exit(-99)
67
68
69 # Functions for resolving macros in the test driver
70 def resolve_pjsua_port(mo):
71 return str(PJSUA_INST_PARAM[int(mo.group(1))].sip_port)
72
73 def resolve_pjsua_uri(mo):
74 return PJSUA_INST_PARAM[int(mo.group(1))].uri[1:-1]
75
76 def resolve_driver_macros(st):
77 st = re.sub("\$SIPP_PORT", str(SIPP_PORT), st)
78 st = re.sub("\$SIPP_URI", "sip:[email protected]:"+str(SIPP_PORT), st)
79 st = re.sub("\$PJSUA_PORT\[(\d+)\]", resolve_pjsua_port, st)
80 st = re.sub("\$PJSUA_URI\[(\d+)\]", resolve_pjsua_uri, st)
81 return st
82
83
84 # Init test driver
85 if os.access(SIPP_SCEN_XML[:-4]+".py", os.R_OK):
86 # Load test driver file (the corresponding .py file), if any
87 cfg_file = util.load_module_from_file("cfg_file", SIPP_SCEN_XML[:-4]+".py")
88 for ua_idx, ua_param in enumerate(cfg_file.PJSUA):
89 ua_param = resolve_driver_macros(ua_param)
90 PJSUA_INST_PARAM.append(InstanceParam("pjsua"+str(ua_idx), ua_param))
91 if DEFAULT_TELNET and hasattr(cfg_file, 'PJSUA_CLI_EXPECTS'):
92 PJSUA_EXPECTS = cfg_file.PJSUA_CLI_EXPECTS
93 else:
94 PJSUA_EXPECTS = cfg_file.PJSUA_EXPECTS
95 else:
96 # Generate default test driver
97 if os.path.basename(SIPP_SCEN_XML)[0:3] == "uas":
98 # auto make call when SIPp is as UAS
99 ua_param = PJSUA_DEF_PARAM + " sip:127.0.0.1:" + str(SIPP_PORT)
100 else:
101 # auto answer when SIPp is as UAC
102 ua_param = PJSUA_DEF_PARAM + " --auto-answer=200"
103 PJSUA_INST_PARAM.append(InstanceParam("pjsua", ua_param))
104
105
106 # Start SIPp process, returning PID
107 def start_sipp():
108 global SIPP_BG_MODE
109 sipp_proc = None
110
111 sipp_param = SIPP_PARAM + " -sf " + SIPP_SCEN_XML
112 if SIPP_BG_MODE:
113 sipp_param = sipp_param + " -bg"
114 if SIPP_TIMEOUT:
115 sipp_param = sipp_param + " -timeout "+str(SIPP_TIMEOUT)+"s -timeout_error" + " -deadcall_wait "+str(SIPP_TIMEOUT)+"s"
116
117 # add target param
118 sipp_param = sipp_param + " 127.0.0.1:" + str(PJSUA_INST_PARAM[0].sip_port)
119
120 # run SIPp
121 fullcmd = os.path.normpath(SIPP_PATH) + " " + sipp_param
122 print("Running SIPP: " + fullcmd)
123 if SIPP_BG_MODE:
124 sipp_proc = subprocess.Popen(fullcmd, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=G_INUNIX, universal_newlines=False)
125 else:
126 # redirect output to NULL
127 global FDEVNULL
128 #FDEVNULL = open(os.devnull, 'w')
129 FDEVNULL = open("logs/sipp_output.tmp", 'w')
130 sipp_proc = subprocess.Popen(fullcmd, shell=G_INUNIX, stdout=FDEVNULL, stderr=FDEVNULL)
131
132 if not SIPP_BG_MODE:
133 if sipp_proc == None or sipp_proc.poll():
134 return None
135 return sipp_proc
136
137 else:
138 # get SIPp child process PID
139 pid = 0
140 r = re.compile("PID=\[(\d+)\]", re.I)
141
142 while True:
143 line = sipp_proc.stdout.readline()
144 pid_r = r.search(line)
145 if pid_r:
146 pid = int(pid_r.group(1))
147 break
148 if not sipp_proc.poll():
149 break
150
151 if pid != 0:
152 # Win specific: get process handle from PID, as on win32, os.waitpid() takes process handle instead of pid
153 if (sys.platform == "win32"):
154 SYNCHRONIZE = 0x00100000
155 PROCESS_QUERY_INFORMATION = 0x0400
156 hnd = ctypes.windll.kernel32.OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, False, pid)
157 pid = hnd
158
159 return pid
160
161
162 # Wait SIPp process to exit, returning SIPp exit code
163 def wait_sipp(sipp):
164 if not SIPP_BG_MODE:
165 global FDEVNULL
166 sipp.wait()
167 FDEVNULL.close()
168 return sipp.returncode
169
170 else:
171 print("Waiting SIPp (PID=" + str(sipp) + ") to exit..")
172 wait_cnt = 0
173 while True:
174 try:
175 wait_cnt = wait_cnt + 1
176 [pid_, ret_code] = os.waitpid(sipp, 0)
177 if sipp == pid_:
178 #print "SIPP returned ", ret_code
179 ret_code = ret_code >> 8
180
181 # Win specific: Close process handle
182 if (sys.platform == "win32"):
183 ctypes.windll.kernel32.CloseHandle(sipp)
184
185 return ret_code
186 except os.error:
187 if wait_cnt <= 5:
188 print("Retry ("+str(wait_cnt)+") waiting SIPp..")
189 else:
190 return -99
191
192
193 # Execute PJSUA flow
194 def exec_pjsua_expects(t, sipp):
195 # Get all PJSUA instances
196 ua = []
197 for ua_idx in range(len(PJSUA_INST_PARAM)):
198 ua.append(t.process[ua_idx])
199
200 ua_err_st = ""
201 while len(PJSUA_EXPECTS):
202 expect = PJSUA_EXPECTS.pop(0)
203 ua_idx = expect[0]
204 expect_st = expect[1]
205 send_cmd = resolve_driver_macros(expect[2])
206 timeout = expect[3] if len(expect)>=4 else 0
207 # Handle exception in pjsua flow, to avoid zombie SIPp process
208 try:
209 if expect_st != "":
210 if timeout > 0:
211 ua[ua_idx].expect(expect_st, raise_on_error = True, timeout = timeout)
212 else:
213 ua[ua_idx].expect(expect_st, raise_on_error = True)
214 if send_cmd != "":
215 ua[ua_idx].send(send_cmd)
216 except TestError as e:
217 ua_err_st = e.desc
218 break;
219 except:
220 ua_err_st = "Unknown error"
221 break;
222
223 # Need to poll here for handling these cases:
224 # - If there is no PJSUA EXPECT scenario, we must keep polling the stdout,
225 # otherwise PJSUA process may stuck (due to stdout pipe buffer full?).
226 # - last PJSUA_EXPECT contains a pjsua command that needs time to
227 # finish, for example "v" (re-INVITE), the SIPp XML scenario may expect
228 # that re-INVITE transaction to be completed and without stdout poll
229 # PJSUA process may stuck.
230 # Ideally the poll should be done contiunously until SIPp process is
231 # terminated.
232 # Update: now pjsua stdout is polled continuously by a dedicated thread,
233 # so the poll is no longer needed
234 #for ua_idx in range(len(ua)):
235 # ua[ua_idx].expect(inc_const.STDOUT_REFRESH, raise_on_error = False)
236
237 return ua_err_st
238
239
240 def sipp_err_to_str(err_code):
241 if err_code == 0:
242 return "All calls were successful"
243 elif err_code == 1:
244 return "At least one call failed"
245 elif err_code == 97:
246 return "exit on internal command. Calls may have been processed"
247 elif err_code == 99:
248 return "Normal exit without calls processed"
249 elif err_code == -1:
250 return "Fatal error (timeout)"
251 elif err_code == -2:
252 return "Fatal error binding a socket"
253 else:
254 return "Unknown error"
255
256
257 # Test body function
258 def TEST_FUNC(t):
259
260 sipp_ret_code = 0
261 ua_err_st = ""
262
263 sipp = start_sipp()
264 if not sipp:
265 raise TestError("Failed starting SIPp")
266
267 ua_err_st = exec_pjsua_expects(t, sipp)
268
269 sipp_ret_code = wait_sipp(sipp)
270
271 if ua_err_st != "":
272 raise TestError(ua_err_st)
273
274 if sipp_ret_code:
275 rc = ctypes.c_byte(sipp_ret_code).value
276 raise TestError("SIPp returned error " + str(rc) + ": " + sipp_err_to_str(rc))
277
278
279 # Here where it all comes together
280 test = TestParam(SIPP_SCEN_XML[:-4],
281 PJSUA_INST_PARAM,
282 TEST_FUNC)