mod_sipp.py 9.5 KB

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