def signal_handler(self, signum, *frame): ED2.callFromThread(self.dispatch) if self.previous_handler not in (SIG_IGN, SIG_DFL): try: self.previous_handler(signum, *frame) except: dump_exception('Signal: unhandled exception in signal chain')
def run(self): #print(self.run, 'enter') while True: #print(self.run, 'spin') self.userv.wi_available.acquire() while len(self.userv.wi) == 0: self.userv.wi_available.wait() wi = self.userv.wi.pop(0) if wi == None: # Shutdown request, relay it further self.userv.wi.append(None) self.userv.wi_available.notify() self.userv.wi_available.release() if wi == None: break command, result_callback, callback_parameters = wi try: data, rtpc_delay = self.send_raw(command) if len(data) == 0: data, rtpc_delay = None, None except Exception as e: dump_exception('Rtp_proxy_client_stream: unhandled exception I/O RTPproxy') data, rtpc_delay = None, None if result_callback != None: ED2.callFromThread(self.dispatch, result_callback, data, callback_parameters) if rtpc_delay != None: ED2.callFromThread(self.userv.register_delay, rtpc_delay) self.userv = None
def testTimeoutAbsMono(): def test1(arguments, testnum, mtm): arguments['delay'] = mtm.offsetFromNow() print(testnum, arguments['delay']) arguments['test'] = True ED2.breakLoop() def test2(arguments, testnum, mtm): arguments['delay'] = mtm.offsetFromNow() print(testnum, arguments['delay']) arguments['test'] = 'bar' ED2.breakLoop() mt = MonoTime() arguments = {'test':False, 'delay':None} timeout_1 = TimeoutAbsMono(test1, mt, arguments, 'test1', mt) ED2.loop() assert(arguments['test']) assert(arguments['delay'] < 0.1) mt1 = mt.getOffsetCopy(0.1) mt2 = mt.getOffsetCopy(0.2) arguments = {'test':False, 'delay':None} timeout_1 = TimeoutAbsMono(test1, mt1, arguments, 'test2', mt1) timeout_2 = TimeoutAbsMono(test2, mt2, arguments, 'test3', mt2) timeout_1.cancel() ED2.loop() assert(arguments['test'] == 'bar') assert(arguments['delay'] < 0.1)
def run(self): #print(self.run, 'enter') while True: #print(self.run, 'cycle') self.w_available.acquire() while self.wbuffer != None and len(self.wbuffer) == 0 and not self.close_pendind: self.w_available.wait() if self.wbuffer == None: self.w_available.release() break wbuffer = self.wbuffer if not self.close_pendind: self.wbuffer = bytes() else: self.wbuffer = None self.w_available.release() while True: res = self.clientsock.send(wbuffer) if res == len(wbuffer): break if res > 0: wbuffer = wbuffer[res:] if self.close_pendind: ED2.callFromThread(self.clim.shutdown) self.clim = None
def run(self): local_host = '127.0.0.1' local_host6 = '[::1]' remote_host = local_host remote_host6 = local_host6 self.ping_laddr = (local_host, 12345) self.pong_laddr = (local_host, 54321) self.ping_laddr6 = (local_host6, 12345) self.pong_laddr6 = (local_host6, 54321) self.ping_raddr = (remote_host, 12345) self.pong_raddr = (remote_host, 54321) self.ping_raddr6 = (remote_host6, 12345) self.pong_raddr6 = (remote_host6, 54321) uopts_ping = Udp_server_opts(self.ping_laddr, self.ping_received) uopts_ping6 = Udp_server_opts(self.ping_laddr6, self.ping_received) uopts_pong = Udp_server_opts(self.pong_laddr, self.pong_received) uopts_pong6 = Udp_server_opts(self.pong_laddr6, self.pong_received) udp_server_ping = Udp_server({}, uopts_ping) udp_server_pong = Udp_server({}, uopts_pong) udp_server_pong.send_to(self.ping_data, self.ping_laddr) udp_server_ping6 = Udp_server({}, uopts_ping6) udp_server_pong6 = Udp_server({}, uopts_pong6) udp_server_pong6.send_to(self.ping_data6, self.ping_laddr6) ED2.loop() udp_server_ping.shutdown() udp_server_pong.shutdown() udp_server_ping6.shutdown() udp_server_pong6.shutdown()
def _stop_play(self, rtpps, result_callback = None, index = 0): if not self.session_exists: ED2.callFromThread(rtpps.command_result, None, result_callback) return from_tag, to_tag = self.gettags(rtpps) command = 'S %s %s %s' % ('%s-%d' % (rtpps.call_id, index), from_tag, to_tag) rtpps.rtp_proxy_client.send_command(command, rtpps.command_result, result_callback)
def run(self): maxemptydata = 100 while True: try: data, address = self.userv.skt.recvfrom(8192) if not data and address == None: # Ugly hack to detect socket being closed under us on Linux. # The problem is that even call on non-closed socket can # sometimes return empty data buffer, making AsyncReceiver # to exit prematurely. maxemptydata -= 1 if maxemptydata == 0: break continue else: maxemptydata = 100 rtime = MonoTime() except Exception as why: if isinstance(why, socket.error) and why[0] in (ECONNRESET, ENOTCONN, ESHUTDOWN): break if isinstance(why, socket.error) and why[0] in (EINTR,): continue else: print(datetime.now(), 'Udp_server: unhandled exception when receiving incoming data') print('-' * 70) traceback.print_exc(file = sys.stdout) print('-' * 70) sys.stdout.flush() sleep(1) continue if self.userv.uopts.family == socket.AF_INET6: address = ('[%s]' % address[0], address[1]) ED2.callFromThread(self.userv.handle_read, data, address, rtime) self.userv = None
def _play(self, rtpps, prompt_name, times = 1, result_callback = None, index = 0): if not self.session_exists: ED2.callFromThread(rtpps.command_result, None, result_callback) return otherside = self.getother(rtpps) if not otherside.session_exists: otherside.update(rtpps, '0.0.0.0', 0, self.__play, '', index, 'IP4', prompt_name, times, result_callback, index) return self.__play(None, rtpps, prompt_name, times, result_callback, index)
def results_received(results): global external_command external_command.shutdown() # Give threads time to finish sleep(0.05) if not results == test_data: print(test_data, results) exit(1) ED2.breakLoop()
def testTimeout(): def test1(arguments, testnum): print(testnum) arguments['test'] = True ED2.breakLoop() def test2(arguments, testnum): print(testnum) arguments['test'] = 'bar' ED2.breakLoop() arguments = {'test':False} timeout_1 = Timeout(test1, 0, 1, arguments, 'test1') ED2.loop() assert(arguments['test']) timeout_1 = Timeout(test1, 0.1, 1, arguments, 'test2') timeout_2 = Timeout(test2, 0.2, 1, arguments, 'test3') timeout_1.cancel() ED2.loop() assert(arguments['test'] == 'bar') arguments = {'test':False} timeout_1 = TimeoutAbsMono(test1, MonoTime(), arguments, 'test4') ED2.loop() assert(arguments['test']) timeout_1 = TimeoutAbsMono(test1, MonoTime().getOffsetCopy(0.1), arguments, 'test5') timeout_2 = TimeoutAbsMono(test2, MonoTime().getOffsetCopy(0.2), arguments, 'test6') timeout_1.cancel() ED2.loop() assert(arguments['test'] == 'bar')
def pong_received(self, data, address, udp_server, rtime): if udp_server.uopts.family == socket.AF_INET: print('pong_received') if data != self.pong_data or address != self.ping_raddr: print(data, address, self.pong_data, self.ping_raddr) exit(1) else: print('pong_received6') if data != self.pong_data6 or address != self.ping_raddr6: print(data, address, self.pong_data6, self.ping_raddr6) exit(1) self.npongs -= 1 if self.npongs == 0: ED2.breakLoop()
def run(self): need_close_fds = True if platform == 'win32': need_close_fds = False pipe = Popen(self.command, shell = False, stdin = PIPE, \ stdout = PIPE, stderr = PIPE, close_fds = need_close_fds) while True: self.master.work_available.acquire() while len(self.master.work) == 0: self.master.work_available.wait() wi = self.master.work.pop(0) if wi == None: # Shutdown request, relay it further self.master.work.append(None) self.master.work_available.notify() self.master.work_available.release() if wi == None: break if wi.is_cancelled(): wi.data = None wi.result_callback = None wi.callback_parameters = None continue batch = [x + b'\n' for x in wi.data] batch.append(b'\n') pipe.stdin.writelines(batch) pipe.stdin.flush() result = [] while True: try: line = pipe.stdout.readline().strip() except IOError as e: # Catch EINTR if e.args[0] != EINTR: raise e continue if len(line) == 0: break result.append(line) ED2.callFromThread(self.master.process_result, wi.result_callback, tuple(result), *wi.callback_parameters) wi.data = None wi.result_callback = None wi.callback_parameters = None
def executeStop(self): if not self.safe_stop: return self.global_config['_executeStop_count'] += 1 acalls = [x for x in self.ccmap if x.state in (CCStateConnected, CCStateARComplete)] nactive = len(acalls) print('[%d]: executeStop is invoked, %d calls in map, %d active' % \ (self.global_config['_my_pid'], len(self.ccmap), nactive)) if self.global_config['_executeStop_count'] >= 5 and nactive > 0: print('executeStop: some sessions would not die, forcing exit:') for cc in acalls: print('\t' + str(cc)) nactive = 0 if nactive > 0: return self.er_timer.cancel() del self.er_timer sys.stdout.flush() sys.stderr.flush() ED2.breakLoop() return
def run(self): #print(self.run, 'enter') while True: #print(self.run, 'cycle') pollret = dict(self.pollobj.poll()).get(self.fileno, 0) if pollret & POLLNVAL != 0: break if pollret & POLLIN == 0: continue try: clientsock, addr = self.clicm.serversock.accept() except Exception as why: if isinstance(why, socket.error): if why.errno == ECONNABORTED: continue elif why.errno == EBADF: break else: raise dump_exception('CLIConnectionManager: unhandled exception when accepting incoming connection') break #print(self.run, 'handle_accept') ED2.callFromThread(self.clicm.handle_accept, clientsock, addr) self.clicm = None
def run(self): import os global_config = {} global_config['my_pid'] = os.getpid() rtpc = Rtp_proxy_client_udp(global_config, ('127.0.0.1', 22226), None) rtpc.rtpp_class = Rtp_proxy_client_udp os.system('sockstat | grep -w %d' % global_config['my_pid']) rtpc.send_command('Ib', self.gotreply) ED2.loop() rtpc.reconnect(('localhost', 22226), ('0.0.0.0', 34222)) os.system('sockstat | grep -w %d' % global_config['my_pid']) rtpc.send_command('V', self.gotreply) ED2.loop() rtpc.reconnect(('localhost', 22226), ('127.0.0.1', 57535)) os.system('sockstat | grep -w %d' % global_config['my_pid']) rtpc.send_command('V', self.gotreply) ED2.loop() rtpc.shutdown()
def run(self): rbuffer = '' while True: data = self.clientsock.recv(1024) if len(data) == 0: ED2.callFromThread(self.clim.shutdown) break try: rbuffer += data.decode('ascii') except UnicodeDecodeError: ED2.callFromThread(self.clim.shutdown) break while rbuffer.find('\n') != -1: cmd, rbuffer = rbuffer.split('\n', 1) cmd = cmd.strip() if len(cmd) == 0: continue ED2.callFromThread(self.clim.handle_cmd, cmd) self.clim = None
def main_func(): try: opts, args = getopt.getopt(sys.argv[1:], 'fl:p:n:L:') except getopt.GetoptError: print( 'usage: b2bua.py [-l addr] [-p port] [-n addr] [-f] [-L logfile]') sys.exit(1) laddr = None lport = None logfile = '/var/log/sippy.log' global_config = {'nh_addr': ['127.0.0.1', 5060]} foreground = False for o, a in opts: if o == '-f': foreground = True continue if o == '-l': laddr = a continue if o == '-p': lport = int(a) continue if o == '-L': logfile = a if o == '-n': if a.startswith('['): parts = a.split(']', 1) global_config['nh_addr'] = [parts[0] + ']', 5060] parts = parts[1].split(':', 1) else: parts = a.split(':', 1) global_config['nh_addr'] = [parts[0], 5060] if len(parts) == 2: global_config['nh_addr'][1] = int(parts[1]) continue global_config['nh_addr'] = tuple(global_config['nh_addr']) if not foreground: daemonize(logfile) SipConf.my_uaname = 'vos 2.1.10' SipConf.allow_formats = (0, 8, 18, 100, 101) global_config['_sip_address'] = SipConf.my_address global_config['_sip_port'] = SipConf.my_port if laddr != None: global_config['_sip_address'] = laddr if lport != None: global_config['_sip_port'] = lport global_config['_sip_logger'] = SipLogger('b2bua') # global_config['_invite_session'] = FuturesSession(max_workers=200) global_config['_request_session'] = FuturesSession(max_workers=200) global_config['_sip_logger'].write(global_config['_sip_address'], ":", global_config['_sip_port']) cmap = CallMap(global_config) global_config['_sip_tm'] = SipTransactionManager(global_config, cmap.recvRequest) ED2.loop()
else: self.delete() if __name__ == '__main__': from sippy.Time.Timeout import Timeout from sippy.Rtp_proxy_client import Rtp_proxy_client def display(*args): print('got:', args) ED2.breakLoop() def waitonline(rpc): if rpc.online: ED2.breakLoop() gc = {'_sip_address':'1.2.3.4'} r = Rtp_proxy_client(gc) t = Timeout(waitonline, 0.1, 10, r) ED2.loop(2.0) assert(r.online) t.cancel() gc['rtp_proxy_client'] = r rs = Rtp_proxy_session(gc, 'call_id1', 'from_tag1', 'to_tag1') rs.version(display) ED2.loop() rs.start_recording('bogus', result_callback = display) print(1) ED2.loop() print(2) rs.play_callee('bogus', result_callback = display) ED2.loop() print(3)
if fname == '-': file_out = sys.stdout else: file_out = open(fname, 'w') elif o == '-b': no_rtpp_version_check = True elif o == '-n': nwrks = int(a) elif o == '-t': timeout = float(a.strip()) if len(args) > 0: commands = args if sippy_path != None: sys.path.insert(0, sippy_path) from sippy.Rtp_proxy_client import Rtp_proxy_client from sippy.Time.Timeout import Timeout from sippy.Core.EventDispatcher import ED2 rc = Rtp_proxy_client(global_config, spath = spath, nworkers = nwrks, \ no_version_check = no_rtpp_version_check) #commands = ('VF 123456', 'G nsess_created', 'G ncmds_rcvd') crun = command_runner(rc, commands, file_in, file_out) if timeout != None: Timeout(crun.timeout, timeout) ED2.loop(freq = 100.0) rc.shutdown() sys.exit(crun.rval)
self.work_available.notify() self.work_available.release() def process_result(self, result_callback, result, *callback_parameters): try: result_callback(result, *callback_parameters) except Exception as ex: if isinstance(ex, SystemExit): raise dump_exception('External_command: unhandled exception in external command results callback') if __name__ == '__main__': from sys import exit from time import sleep test_data = (b'foo', b'bar') def results_received(results): global external_command external_command.shutdown() # Give threads time to finish sleep(0.05) if not results == test_data: print(test_data, results) exit(1) ED2.breakLoop() external_command = External_command('/bin/cat') external_command.process_command(test_data, results_received) ED2.loop()
if fname == '-': file_out = sys.stdout else: file_out = open(fname, 'w') elif o == '-b': no_rtpp_version_check = True elif o == '-n': nwrks = int(a) elif o == '-t': timeout = float(a.strip()) if len(args) > 0: commands = args if sippy_path != None: sys.path.insert(0, sippy_path) from sippy.Rtp_proxy_client import Rtp_proxy_client from sippy.Time.Timeout import Timeout from sippy.Core.EventDispatcher import ED2 rc = Rtp_proxy_client(global_config, spath = spath, nworkers = nwrks, \ no_version_check = no_rtpp_version_check) #commands = ('VF 123456', 'G nsess_created', 'G ncmds_rcvd') crun = command_runner(rc, commands, file_in, file_out) if timeout != None: Timeout(crun.timeout, timeout) ED2.loop() rc.shutdown() sys.exit(crun.rval)
def test(arguments): arguments['test'] = not arguments['test'] ED2.breakLoop()
def main_func(): global_config = MyConfigParser() global_config['digest_auth'] = True global_config['start_acct_enable'] = False global_config['keepalive_ans'] = 0 global_config['keepalive_orig'] = 0 global_config['auth_enable'] = True global_config['acct_enable'] = True global_config['_pass_headers'] = [] global_config['_orig_argv'] = sys.argv[:] global_config['_orig_cwd'] = os.getcwd() try: opts, args = getopt.getopt(sys.argv[1:], 'fDl:p:d:P:L:s:a:t:T:k:m:A:ur:F:R:h:c:M:HC:W:', global_config.get_longopts()) except getopt.GetoptError: usage(global_config) global_config['foreground'] = False global_config['pidfile'] = '/var/run/b2bua.pid' global_config['logfile'] = '/var/log/b2bua.log' global_config['b2bua_socket'] = '/var/run/b2bua.sock' global_config['_sip_address'] = SipConf.my_address global_config['_sip_port'] = SipConf.my_port global_config['_my_pid'] = os.getpid() rtp_proxy_clients = [] writeconf = None for o, a in opts: if o == '-f': global_config['foreground'] = True continue if o == '-l': global_config.check_and_set('sip_address', a) continue if o == '-p': global_config.check_and_set('sip_port', a) continue if o == '-P': global_config.check_and_set('pidfile', a) continue if o == '-L': global_config.check_and_set('logfile', a) continue if o == '-s': global_config.check_and_set('static_route', a) continue if o == '-a': global_config.check_and_set('accept_ips', a) continue if o == '-D': global_config['digest_auth'] = False continue if o == '-A': acct_level = int(a.strip()) if acct_level == 0: global_config['acct_enable'] = False global_config['start_acct_enable'] = False elif acct_level == 1: global_config['acct_enable'] = True global_config['start_acct_enable'] = False elif acct_level == 2: global_config['acct_enable'] = True global_config['start_acct_enable'] = True else: sys.__stderr__.write('ERROR: -A argument not in the range 0-2\n') usage(global_config, True) continue if o == '-t': global_config.check_and_set('static_tr_in', a) continue if o == '-T': global_config.check_and_set('static_tr_out', a) continue if o == '-k': ka_level = int(a.strip()) if ka_level == 0: pass elif ka_level == 1: global_config['keepalive_ans'] = 32 elif ka_level == 2: global_config['keepalive_orig'] = 32 elif ka_level == 3: global_config['keepalive_ans'] = 32 global_config['keepalive_orig'] = 32 else: sys.__stderr__.write('ERROR: -k argument not in the range 0-3\n') usage(global_config, True) if o == '-m': global_config.check_and_set('max_credit_time', a) continue if o == '-u': global_config['auth_enable'] = False continue if o == '-r': global_config.check_and_set('rtp_proxy_client', a) continue if o == '-F': global_config.check_and_set('allowed_pts', a) continue if o == '-R': global_config.check_and_set('radiusclient.conf', a) continue if o == '-h': for a in a.split(','): global_config.check_and_set('pass_header', a) continue if o == '-c': global_config.check_and_set('b2bua_socket', a) continue if o == '-M': global_config.check_and_set('max_radiusclients', a) continue if o == '-H': global_config['hide_call_id'] = True continue if o in ('-C', '--config'): global_config.read(a.strip()) continue if o.startswith('--'): global_config.check_and_set(o[2:], a) continue if o == '-W': writeconf = a.strip() continue if '_rtp_proxy_clients' in global_config: for a in global_config['_rtp_proxy_clients']: rtp_proxy_clients.append(a) if 'static_route' in global_config: global_config['_static_route'] = B2BRoute(global_config['static_route']) elif not global_config['auth_enable']: sys.__stderr__.write('ERROR: static route should be specified when Radius auth is disabled\n') usage(global_config, True) if writeconf != None: global_config.write(open(writeconf, 'w')) if not global_config['foreground']: daemonize(logfile = global_config['logfile']) global_config['_sip_logger'] = SipLogger('b2bua') if len(rtp_proxy_clients) > 0: global_config['_rtp_proxy_clients'] = [] for address in rtp_proxy_clients: global_config['_rtp_proxy_clients'].append(Rtp_proxy_client(global_config, spath = address)) if global_config['auth_enable'] or global_config['acct_enable']: global_config['_radius_client'] = RadiusAuthorisation(global_config) global_config['_uaname'] = 'Sippy B2BUA (RADIUS)' global_config['_cmap'] = CallMap(global_config) if 'sip_proxy' in global_config: host_port = global_config['sip_proxy'].split(':', 1) if len(host_port) == 1: global_config['_sip_proxy'] = (host_port[0], 5060) else: global_config['_sip_proxy'] = (host_port[0], int(host_port[1])) global_config['_cmap'].proxy = StatefulProxy(global_config, global_config['_sip_proxy']) if global_config.getdefault('xmpp_b2bua_id', None) != None: global_config['_xmpp_mode'] = True global_config['_sip_tm'] = SipTransactionManager(global_config, global_config['_cmap'].recvRequest) global_config['_sip_tm'].nat_traversal = global_config.getdefault('nat_traversal', False) cmdfile = global_config['b2bua_socket'] if cmdfile.startswith('unix:'): cmdfile = cmdfile[5:] cli_server = CLIConnectionManager(global_config['_cmap'].recvCommand, cmdfile) if not global_config['foreground']: open(global_config['pidfile'], 'w').write(str(os.getpid()) + '\n') Signal(SIGUSR1, reopen, SIGUSR1, global_config['logfile']) ED2.loop()
def callback(clm, cmd): print('in:', cmd) clm.send('hello, there!\n') clm.close() ED2.breakLoop()
def display(res, ro, arg): print(res, arg) ro.rval = (res, arg) ED2.breakLoop()
def test2(arguments, testnum, mtm): arguments['delay'] = mtm.offsetFromNow() print(testnum, arguments['delay']) arguments['test'] = 'bar' ED2.breakLoop()
def display(*args): print('got:', args) ED2.breakLoop()
self.ptransmitted = ptransmitted def shutdown(self): if self.shut_down: # do not crash when shutdown() called twice return self.shut_down = True self.rtpp_class.shutdown(self) self.rtpp_class = None def get_rtpc_delay(self): return self.rtpp_class.get_rtpc_delay(self) if __name__ == '__main__': from sippy.Core.EventDispatcher import ED2 from sippy.Time.Timeout import Timeout def display(*args): print(args) ED2.breakLoop() def waitonline(rpc): if rpc.online: ED2.breakLoop() r = Rtp_proxy_client({'_sip_address':'1.2.3.4'}) t = Timeout(waitonline, 0.1, 10, r) ED2.loop(2.0) assert(r.online) t.cancel() r.send_command('VF 123456', display, 'abcd') ED2.loop() r.shutdown() print('passed')
def gotreply(self, *args): print(args) ED2.breakLoop()
def run(self): rfile = None session_timeout = self.default_timeout ctime = None count = 0 port = Serial(self.sdev, baudrate = self.brate, timeout=0.1) while True: try: data = port.read(256) except Exception as e: self.lfile.write('Session exception: %s\n' % str(e)) self.lfile.flush() if rfile != None: #rfile.flush() rfile.close() rfile = None sleep(1) port = Serial(self.sdev, baudrate = self.brate, timeout=0.1) continue atime = time() if rfile != None and atime - ctime > session_timeout: self.lfile.write('Session timeout: %f\n' % (atime - ctime)) self.lfile.flush() #rfile.flush() rfile.close() rfile = None if self.send_cb != None: ED2.callFromThread(self.send_cb) self.enqueue_cb_lock.acquire() self.enqueue_cb = None self.enqueue_cb_lock.release() self.prequeue = [] if len(data) == 0: continue previous_ctime = ctime ctime = atime if rfile == None: fname = '/tmp/%s.csv' % int(ctime) rfile = open(fname, 'w') session_timeout = self.default_timeout previous_ctime = None count = 0 self.lfile.write('Starting recording %s\n' % fname) self.lfile.flush() if self.sstart_cb != None: ED2.callFromThread(self._sstart_cb) if previous_ctime != None and session_timeout > (ctime - previous_ctime) * 2 and count > 2: session_timeout = (ctime - previous_ctime) * 2 self.lfile.write(' Updating session timeout to %f sec\n' % session_timeout) self.lfile.flush() parts = [x.strip() for x in data.decode('ascii').split(' ', 3)] try: volts = float(parts[1][:-1]) amps = float(parts[2][:-1]) except: count += 1 continue pload = '%d,%f,%f' % (count, volts, amps) rfile.write('%s\n' % pload) pload = pload.encode() self.enqueue_cb_lock.acquire() if self.enqueue_cb != None: self.enqueue_cb(pload) else: self.prequeue.append(pload) self.enqueue_cb_lock.release() #rfile.flush() count += 1
def main_func(): global_config = MyConfigParser() global_config['digest_auth'] = True global_config['start_acct_enable'] = False global_config['keepalive_ans'] = 0 global_config['keepalive_orig'] = 0 global_config['auth_enable'] = True global_config['acct_enable'] = True global_config['_pass_headers'] = [] global_config['_orig_argv'] = sys.argv[:] global_config['_orig_cwd'] = os.getcwd() try: opts, args = getopt.getopt( sys.argv[1:], 'fDl:p:d:P:L:s:a:t:T:k:m:A:ur:F:R:h:c:M:HC:W:', global_config.get_longopts()) except getopt.GetoptError: usage(global_config) global_config['foreground'] = False global_config['pidfile'] = '/var/run/b2bua.pid' global_config['logfile'] = '/var/log/b2bua.log' global_config['b2bua_socket'] = '/var/run/b2bua.sock' global_config['_sip_address'] = SipConf.my_address global_config['_sip_port'] = SipConf.my_port global_config['_my_pid'] = os.getpid() rtp_proxy_clients = [] writeconf = None for o, a in opts: if o == '-f': global_config['foreground'] = True continue if o == '-l': global_config.check_and_set('sip_address', a) continue if o == '-p': global_config.check_and_set('sip_port', a) continue if o == '-P': global_config.check_and_set('pidfile', a) continue if o == '-L': global_config.check_and_set('logfile', a) continue if o == '-s': global_config.check_and_set('static_route', a) continue if o == '-a': global_config.check_and_set('accept_ips', a) continue if o == '-D': global_config['digest_auth'] = False continue if o == '-A': acct_level = int(a.strip()) if acct_level == 0: global_config['acct_enable'] = False global_config['start_acct_enable'] = False elif acct_level == 1: global_config['acct_enable'] = True global_config['start_acct_enable'] = False elif acct_level == 2: global_config['acct_enable'] = True global_config['start_acct_enable'] = True else: sys.__stderr__.write( 'ERROR: -A argument not in the range 0-2\n') usage(global_config, True) continue if o == '-t': global_config.check_and_set('static_tr_in', a) continue if o == '-T': global_config.check_and_set('static_tr_out', a) continue if o == '-k': ka_level = int(a.strip()) if ka_level == 0: pass elif ka_level == 1: global_config['keepalive_ans'] = 32 elif ka_level == 2: global_config['keepalive_orig'] = 32 elif ka_level == 3: global_config['keepalive_ans'] = 32 global_config['keepalive_orig'] = 32 else: sys.__stderr__.write( 'ERROR: -k argument not in the range 0-3\n') usage(global_config, True) if o == '-m': global_config.check_and_set('max_credit_time', a) continue if o == '-u': global_config['auth_enable'] = False continue if o == '-r': global_config.check_and_set('rtp_proxy_client', a) continue if o == '-F': global_config.check_and_set('allowed_pts', a) continue if o == '-R': global_config.check_and_set('radiusclient.conf', a) continue if o == '-h': for a in a.split(','): global_config.check_and_set('pass_header', a) continue if o == '-c': global_config.check_and_set('b2bua_socket', a) continue if o == '-M': global_config.check_and_set('max_radiusclients', a) continue if o == '-H': global_config['hide_call_id'] = True continue if o in ('-C', '--config'): global_config.read(a.strip()) continue if o.startswith('--'): global_config.check_and_set(o[2:], a) continue if o == '-W': writeconf = a.strip() continue if '_rtp_proxy_clients' in global_config: for a in global_config['_rtp_proxy_clients']: rtp_proxy_clients.append(a) if 'static_route' in global_config: global_config['_static_route'] = B2BRoute( global_config['static_route']) elif not global_config['auth_enable']: sys.__stderr__.write( 'ERROR: static route should be specified when Radius auth is disabled\n' ) usage(global_config, True) if writeconf != None: global_config.write(open(writeconf, 'w')) if not global_config['foreground']: daemonize(logfile=global_config['logfile']) global_config['_sip_logger'] = SipLogger('b2bua') if len(rtp_proxy_clients) > 0: global_config['_rtp_proxy_clients'] = [] for address in rtp_proxy_clients: global_config['_rtp_proxy_clients'].append( Rtp_proxy_client(global_config, spath=address)) if global_config['auth_enable'] or global_config['acct_enable']: global_config['_radius_client'] = RadiusAuthorisation(global_config) global_config['_uaname'] = 'Sippy B2BUA (RADIUS)' global_config['_cmap'] = CallMap(global_config) if 'sip_proxy' in global_config: host_port = global_config['sip_proxy'].split(':', 1) if len(host_port) == 1: global_config['_sip_proxy'] = (host_port[0], 5060) else: global_config['_sip_proxy'] = (host_port[0], int(host_port[1])) global_config['_cmap'].proxy = StatefulProxy( global_config, global_config['_sip_proxy']) if global_config.getdefault('xmpp_b2bua_id', None) != None: global_config['_xmpp_mode'] = True global_config['_sip_tm'] = SipTransactionManager( global_config, global_config['_cmap'].recvRequest) global_config['_sip_tm'].nat_traversal = global_config.getdefault( 'nat_traversal', False) cmdfile = global_config['b2bua_socket'] if cmdfile.startswith('unix:'): cmdfile = cmdfile[5:] cli_server = CLIConnectionManager(global_config['_cmap'].recvCommand, cmdfile) if not global_config['foreground']: open(global_config['pidfile'], 'w').write(str(os.getpid()) + '\n') Signal(SIGUSR1, reopen, SIGUSR1, global_config['logfile']) ED2.loop()
def display(*args): print(args) ED2.breakLoop()
def waitonline(rpc): if rpc.online: ED2.breakLoop()
def __del__(self): if self.my_ident != get_ident(): #print 'Rtp_proxy_session.__del__() from wrong thread, re-routing' ED2.callFromThread(self.delete) else: self.delete()