def on_channel_bridge(self, event): """B Leg from Dial element answered """ # if plivo_app != 'true', check b leg Dial callback # request Dial callbackUrl if needed aleg_uuid = event['Bridge-A-Unique-ID'] if not aleg_uuid: return bleg_uuid = event['Bridge-B-Unique-ID'] if not bleg_uuid: return disposition = event['variable_endpoint_disposition'] if disposition != 'ANSWER': return app_vars = event['variable_current_application_data'] if not 'plivo_dial_callback_url' in app_vars: return ck_url = app_vars.split('plivo_dial_callback_url=')[1].split(',')[0] if not 'plivo_dial_callback_method' in app_vars: return ck_method = app_vars.split('plivo_dial_callback_method=')[1].split(',')[0] params = {'DialBLegUUID': bleg_uuid, 'DialALegUUID': aleg_uuid, 'DialBLegStatus': 'answer', 'CallUUID': aleg_uuid } spawn_raw(self.send_to_url, ck_url, params, ck_method) return
def on_channel_progress(self, event): request_uuid = event['variable_plivo_request_uuid'] direction = event['Call-Direction'] # Detect ringing state if request_uuid and direction == 'outbound': try: call_req = self.call_requests[request_uuid] except (KeyError, AttributeError): return # only send if not already ringing/early state if not call_req.state_flag: # set state flag to true call_req.state_flag = 'Ringing' # clear gateways to avoid retry call_req.gateways = [] called_num = event['Caller-Destination-Number'] caller_num = event['Caller-Caller-ID-Number'] self.log.info("Call from %s to %s Ringing for RequestUUID %s" \ % (caller_num, called_num, request_uuid)) # send ring if ring_url found ring_url = call_req.ring_url if ring_url: params = { 'To': called_num, 'RequestUUID': request_uuid, 'Direction': direction, 'CallStatus': 'ringing', 'From': caller_num } spawn_raw(self.send_to_url, ring_url, params)
def on_call_update(self, event): """A Leg from API outbound call answered """ # if plivo_app != 'true', check b leg Dial callback plivo_app_flag = event['variable_plivo_app'] == 'true' if not plivo_app_flag: # request Dial callbackUrl if needed aleg_uuid = event['Bridged-To'] if not aleg_uuid: return bleg_uuid = event['Unique-ID'] if not bleg_uuid: return disposition = event['variable_endpoint_disposition'] if disposition != 'ANSWER': return ck_url = event['variable_plivo_dial_callback_url'] if not ck_url: return ck_method = event['variable_plivo_dial_callback_method'] if not ck_method: return params = {'DialBLegUUID': bleg_uuid, 'DialALegUUID': aleg_uuid, 'DialBLegStatus': 'answer', 'CallUUID': aleg_uuid } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) spawn_raw(self.send_to_url, ck_url, params, ck_method) return
def on_call_update(self, event): # if plivo_app != 'true', check b leg Dial callback plivo_app_flag = event["variable_plivo_app"] == "true" if not plivo_app_flag: # request Dial callbackUrl if needed aleg_uuid = event["Bridged-To"] if not aleg_uuid: return bleg_uuid = event["Unique-ID"] if not bleg_uuid: return disposition = event["variable_endpoint_disposition"] if disposition != "ANSWER": return ck_url = event["variable_plivo_dial_callback_url"] if not ck_url: return ck_method = event["variable_plivo_dial_callback_method"] if not ck_method: return params = { "DialBLegUUID": bleg_uuid, "DialALegUUID": aleg_uuid, "DialBLegStatus": "answer", "CallUUID": aleg_uuid, } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) spawn_raw(self.send_to_url, ck_url, params, ck_method) return
def on_session_heartbeat(self, event): """Capture every heartbeat event in a session and post info """ params = {} answer_seconds_since_epoch = float(event['Caller-Channel-Answered-Time'])/1000000 # using UTC here .. make sure FS is using UTC also params['AnsweredTime'] = str(answer_seconds_since_epoch) heartbeat_seconds_since_epoch = float(event['Event-Date-Timestamp'])/1000000 # using UTC here .. make sure FS is using UTC also params['HeartbeatTime'] = str(heartbeat_seconds_since_epoch) params['ElapsedTime'] = str(heartbeat_seconds_since_epoch - answer_seconds_since_epoch) params['To'] = event['Caller-Destination-Number'].lstrip('+') params['From'] = event['Caller-Caller-ID-Number'].lstrip('+') params['CallUUID'] = event['Unique-ID'] params['Direction'] = event['Call-Direction'] forwarded_from = get_substring(':', '@', event['variable_sip_h_Diversion']) if forwarded_from: params['ForwardedFrom'] = forwarded_from.lstrip('+') if event['Channel-State'] == 'CS_EXECUTE': params['CallStatus'] = 'in-progress' # RequestUUID through which this call was initiated if outbound request_uuid = event['variable_plivo_request_uuid'] if request_uuid: params['RequestUUID'] = request_uuid self.log.debug("Got Session Heartbeat from Freeswitch: %s" % params) if self.call_heartbeat_url: self.log.debug("Sending heartbeat to callback: %s" % self.call_heartbeat_url) spawn_raw(self.send_to_url, self.call_heartbeat_url, params)
def on_call_update(self, event): # if plivo_app != 'true', check b leg Dial callback plivo_app_flag = event['variable_plivo_app'] == 'true' if not plivo_app_flag: # request Dial callbackUrl if needed aleg_uuid = event['Bridged-To'] if not aleg_uuid: return bleg_uuid = event['Unique-ID'] if not bleg_uuid: return disposition = event['variable_endpoint_disposition'] if disposition != 'ANSWER': return ck_url = event['variable_plivo_dial_callback_url'] if not ck_url: return ck_method = event['variable_plivo_dial_callback_method'] if not ck_method: return params = {'DialBLegUUID': bleg_uuid, 'DialALegUUID': aleg_uuid, 'DialBLegStatus': 'answer', 'CallUUID': aleg_uuid } spawn_raw(self.send_to_url, ck_url, params, ck_method) return
def _spawn(self, func, *args, **kwargs): ''' Spawns with or without pool. ''' if self.pool: self.pool.spawn(func, *args, **kwargs) else: gevent.spawn_raw(func, *args, **kwargs)
def spawn_originate(self, request_uuid): try: call_req = self.call_requests[request_uuid] except KeyError: self.log.warn("Call Request not found for RequestUUID %s" % request_uuid) return False spawn_raw(self._spawn_originate, call_req) self.log.warn("Call Request Spawned for RequestUUID %s" % request_uuid) return True
def on_custom(self, event): # case conference event if self.current_element == 'Conference': # special case to get Member-ID for Conference if event['Event-Subclass'] == 'conference::maintenance' \ and event['Action'] == 'add-member' \ and event['Unique-ID'] == self.get_channel_unique_id(): self.log.debug("Entered Conference") self._action_queue.put(event) # special case for hangupOnStar in Conference elif event['Event-Subclass'] == 'conference::maintenance' \ and event['Action'] == 'kick' \ and event['Unique-ID'] == self.get_channel_unique_id(): room = event['Conference-Name'] member_id = event['Member-ID'] if room and member_id: self.bgapi("conference %s kick %s" % (room, member_id)) self.log.warn("Conference Room %s, member %s pressed '*', kicked now !" \ % (room, member_id)) # special case to send callback for Conference elif event['Event-Subclass'] == 'conference::maintenance' \ and event['Action'] == 'digits-match' \ and event['Unique-ID'] == self.get_channel_unique_id(): self.log.debug("Digits match on Conference") digits_action = event['Callback-Url'] digits_method = event['Callback-Method'] if digits_action and digits_method: params = {} params['ConferenceMemberID'] = event['Member-ID'] or '' params['ConferenceUUID'] = event['Conference-Unique-ID'] or '' params['ConferenceName'] = event['Conference-Name'] or '' params['ConferenceDigitsMatch'] = event['Digits-Match'] or '' params['ConferenceAction'] = 'digits' spawn_raw(self.send_to_url, digits_action, params, digits_method) # special case to send callback when Member take the floor in Conference # but only if member can speak (not muted) elif event['Event-Subclass'] == 'conference::maintenance' \ and event['Action'] == 'floor-change' \ and event['Unique-ID'] == self.get_channel_unique_id() \ and event['Speak'] == 'true': self._action_queue.put(event) # case dial event elif self.current_element == 'Dial': if event['Event-Subclass'] == 'plivo::dial' \ and event['Action'] == 'digits-match' \ and event['Unique-ID'] == self.get_channel_unique_id(): self.log.debug("Digits match on Dial") digits_action = event['Callback-Url'] digits_method = event['Callback-Method'] if digits_action and digits_method: params = {} params['DialDigitsMatch'] = event['Digits-Match'] or '' params['DialAction'] = 'digits' params['DialALegUUID'] = event['Unique-ID'] params['DialBLegUUID'] = event['variable_bridge_uuid'] spawn_raw(self.send_to_url, digits_action, params, digits_method)
def on_channel_progress(self, event): request_uuid = event['variable_plivo_request_uuid'] direction = event['Call-Direction'] # Detect ringing state if request_uuid and direction == 'outbound': accountsid = event['variable_plivo_accountsid'] # case GroupCall if event['variable_plivo_group_call'] == 'true': # get ring_url ring_url = event['variable_plivo_ring_url'] # case BulkCall and Call else: try: call_req = self.call_requests[request_uuid] except (KeyError, AttributeError): return # notify call and self.log.debug( "Notify Call success (Ringing) for RequestUUID %s" % request_uuid) call_req.notify_call_end() # only send if not already ringing/early state if not call_req.state_flag: # set state flag to 'Ringing' call_req.state_flag = 'Ringing' # clear gateways to avoid retry call_req.gateways = [] # get ring_url ring_url = call_req.ring_url else: return # send ring if ring_url found if ring_url: called_num = event['variable_plivo_destination_number'] if not called_num or called_num == '_undef_': called_num = event['Caller-Destination-Number'] or '' called_num = called_num.lstrip('+') caller_num = event['Caller-Caller-ID-Number'] or '' call_uuid = event['Unique-ID'] or '' self.log.info("Call from %s to %s Ringing for RequestUUID %s" \ % (caller_num, called_num, request_uuid)) params = { 'To': called_num, 'RequestUUID': request_uuid, 'Direction': direction, 'CallStatus': 'ringing', 'From': caller_num, 'CallUUID': call_uuid } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) if accountsid: params['AccountSID'] = accountsid spawn_raw(self.send_to_url, ring_url, params)
def on_channel_progress(self, event): request_uuid = event['variable_plivo_request_uuid'] direction = event['Call-Direction'] # Detect ringing state if request_uuid and direction == 'outbound': accountsid = event['variable_plivo_accountsid'] # case GroupCall if event['variable_plivo_group_call'] == 'true': # get ring_url ring_url = event['variable_plivo_ring_url'] # case BulkCall and Call else: try: call_req = self.call_requests[request_uuid] except (KeyError, AttributeError): return # notify call and self.log.debug("Notify Call success (Ringing) for RequestUUID %s" % request_uuid) call_req.notify_call_end() # only send if not already ringing/early state if not call_req.state_flag: # set state flag to 'Ringing' call_req.state_flag = 'Ringing' # clear gateways to avoid retry call_req.gateways = [] # get ring_url ring_url = call_req.ring_url else: return # send ring if ring_url found if ring_url: called_num = event['variable_plivo_destination_number'] if not called_num or called_num == '_undef_': called_num = event['Caller-Destination-Number'] or '' called_num = called_num.lstrip('+') caller_num = event['Caller-Caller-ID-Number'] or '' call_uuid = event['Unique-ID'] or '' self.log.info("Call from %s to %s Ringing for RequestUUID %s" \ % (caller_num, called_num, request_uuid)) params = {'To': called_num, 'RequestUUID': request_uuid, 'Direction': direction, 'CallStatus': 'ringing', 'From': caller_num, 'CallUUID': call_uuid } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) if accountsid: params['AccountSID'] = accountsid spawn_raw(self.send_to_url, ring_url, params)
def on_channel_progress(self, event): request_uuid = event["variable_plivo_request_uuid"] direction = event["Call-Direction"] # Detect ringing state if request_uuid and direction == "outbound": accountsid = event["variable_plivo_accountsid"] # case GroupCall if event["variable_plivo_group_call"] == "true": # get ring_url ring_url = event["variable_plivo_ring_url"] # case BulkCall and Call else: try: call_req = self.call_requests[request_uuid] except (KeyError, AttributeError): return # notify call and self.log.debug("Notify Call success (Ringing) for RequestUUID %s" % request_uuid) call_req.notify_call_end() # only send if not already ringing/early state if not call_req.state_flag: # set state flag to 'Ringing' call_req.state_flag = "Ringing" # clear gateways to avoid retry call_req.gateways = [] # get ring_url ring_url = call_req.ring_url else: return # send ring if ring_url found if ring_url: called_num = event["variable_plivo_destination_number"] if not called_num or called_num == "_undef_": called_num = event["Caller-Destination-Number"] or "" called_num = called_num.lstrip("+") caller_num = event["Caller-Caller-ID-Number"] or "" call_uuid = event["Unique-ID"] or "" self.log.info("Call from %s to %s Ringing for RequestUUID %s" % (caller_num, called_num, request_uuid)) params = { "To": called_num, "RequestUUID": request_uuid, "Direction": direction, "CallStatus": "ringing", "From": caller_num, "CallUUID": call_uuid, } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) if accountsid: params["AccountSID"] = accountsid spawn_raw(self.send_to_url, ring_url, params)
def run(self): self.beating = True gevent.spawn(self.log_beating_hearts) if self.check_xrep: gevent.spawn_later(1, self.check_xrep_state) else: gevent.spawn_raw(self.recv_hearts_no_xrep_state_check) gevent.spawn_later(2, self.beat) while self.beating: gevent.sleep(5)
def recv_hearts_no_xrep_state_check(self): buffer = [] while True: message = self.xrep.recv() if message: buffer.append(message) if not self.xrep.rcvmore(): # Message is now complete # break to process it! gevent.spawn_raw(self.handle_pong, buffer[:]) buffer = []
def send_message(self, channel, message): if channel not in self._channel_id_cache: return args = { 'username': self._jeev.name, 'text': message, 'link_names': self._link_names, 'channel': self._channel_id_cache[channel] } spawn_raw(self._requests.post, self._send_url, json.dumps(args))
def decorated_function(*args, **kwargs): kwargs_keys = kwargs.keys() kwargs_keys.sort() path = "%s/%s/%s" % (f.func_name, '/'.join(args), '/'.join(['%s=%s' % (k, kwargs[k]) for k in kwargs_keys])) cached_response = self.redis_handler.get_cached_object(path) if cached_response: return json.loads(cached_response) response = f(*args, **kwargs) expire_duration = app.config.get('EXPIRE_DURATION') gevent.spawn_raw(self.redis_handler.set_object_cache, path, json.dumps(response), expire_duration) return response
def on_channel_hangup_complete(self, event): """Capture Channel Hangup Complete """ # if plivo_app != 'true', check b leg Dial callback plivo_app_flag = event['variable_plivo_app'] == 'true' print 'ddddddddddddddddddddddddddd', event if not plivo_app_flag: # request Dial callbackUrl if needed ck_url = event['variable_plivo_dial_callback_url'] if not ck_url: return ck_method = event['variable_plivo_dial_callback_method'] if not ck_method: return aleg_uuid = event['variable_plivo_dial_callback_aleg'] if not aleg_uuid: return hangup_cause = event['Hangup-Cause'] or '' # don't send http request for B legs losing bridge race if hangup_cause == 'LOSE_RACE': return bleg_uuid = event['Unique-ID'] params = { 'DialBLegUUID': bleg_uuid, 'DialALegUUID': aleg_uuid, 'DialBLegStatus': 'hangup', 'DialBLegHangupCause': hangup_cause, 'CallUUID': aleg_uuid } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) spawn_raw(self.send_to_url, ck_url, params, ck_method) return # Get call direction direction = event['Call-Direction'] # Handle incoming call hangup if direction == 'inbound': print 'inbound--------------', event call_uuid = event['Unique-ID'] reason = event['Hangup-Cause'] # send hangup try: self.set_hangup_complete(None, call_uuid, reason, event, None) except Exception, e: self.log.error(str(e))
def beat(self): toc = time.time() self.lifetime += toc - self.tic self.tic = toc # self.message = str(self.lifetime) goodhearts = self.hearts.intersection(self.responses) heartfailures = self.hearts.difference(goodhearts) newhearts = self.responses.difference(goodhearts) # print newhearts, goodhearts, heartfailures map(self.handle_new_heart, newhearts) map(self.handle_heart_failure, heartfailures) self.responses = set() gevent.spawn_later(self.period, self.beat) gevent.spawn_raw(self.pub.send, str(self.lifetime))
def on_channel_hangup_complete(self, event): """Capture Channel Hangup Complete """ # if plivo_app != 'true', check b leg Dial callback plivo_app_flag = event["variable_plivo_app"] == "true" if not plivo_app_flag: # request Dial callbackUrl if needed ck_url = event["variable_plivo_dial_callback_url"] if not ck_url: return ck_method = event["variable_plivo_dial_callback_method"] if not ck_method: return aleg_uuid = event["variable_plivo_dial_callback_aleg"] if not aleg_uuid: return hangup_cause = event["Hangup-Cause"] or "" # don't send http request for B legs losing bridge race if hangup_cause == "LOSE_RACE": return bleg_uuid = event["Unique-ID"] params = { "DialBLegUUID": bleg_uuid, "DialALegUUID": aleg_uuid, "DialBLegStatus": "hangup", "DialBLegHangupCause": hangup_cause, "CallUUID": aleg_uuid, } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) spawn_raw(self.send_to_url, ck_url, params, ck_method) return # Get call direction direction = event["Call-Direction"] # Handle incoming call hangup if direction == "inbound": call_uuid = event["Unique-ID"] reason = event["Hangup-Cause"] # send hangup try: self.set_hangup_complete(None, call_uuid, reason, event, None) except Exception, e: self.log.error(str(e))
def _serve_forever(self): """Main-loop handling incoming connections.""" while not self._stop: try: new_socket, address = self.socket.accept() starttime = self._get_tick() gevent.spawn_raw(self._handle_connection, new_socket) gevent.spawn_raw(self._print_connection, address, starttime) except (socket.timeout, socket.error): pass finally: gevent.sleep(0) self.socket.close() print "goodbye, cruel world"
def on_channel_hangup_complete(self, event): """Capture Channel Hangup Complete """ # if plivo_app != 'true', check b leg Dial callback plivo_app_flag = event['variable_plivo_app'] == 'true' if not plivo_app_flag: # request Dial callbackUrl if needed ck_url = event['variable_plivo_dial_callback_url'] if not ck_url: return ck_method = event['variable_plivo_dial_callback_method'] if not ck_method: return aleg_uuid = event['variable_plivo_dial_callback_aleg'] if not aleg_uuid: return hangup_cause = event['Hangup-Cause'] or '' # don't send http request for B legs losing bridge race if hangup_cause == 'LOSE_RACE': return bleg_uuid = event['Unique-ID'] params = {'DialBLegUUID': bleg_uuid, 'DialALegUUID': aleg_uuid, 'DialBLegStatus': 'hangup', 'DialBLegHangupCause': hangup_cause, 'CallUUID': aleg_uuid } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) spawn_raw(self.send_to_url, ck_url, params, ck_method) return # Get call direction direction = event['Call-Direction'] # Handle incoming call hangup if direction == 'inbound': call_uuid = event['Unique-ID'] reason = event['Hangup-Cause'] # send hangup try: self.set_hangup_complete(None, call_uuid, reason, event, None) except Exception, e: self.log.error(str(e))
def test_greenthread_singleton(metaclass: Type, repetitions: int): """Test Greenthread Singleton with Gevent.""" assert singletons.detect_greenthread_environment() == "gevent" class MySingleton(metaclass=metaclass): def __init__(self): self.uuid = uuid.uuid4() def inner_func(q: gevent.queue.Queue): a = MySingleton() b = MySingleton() q.put((a.uuid, b.uuid)) test_q = gevent.queue.Queue() greenthreads = [] for _ in range(repetitions): p = gevent.spawn_raw(inner_func, test_q) greenthreads.append(p) gevent.sleep() # force execution context to switch seen_uuids = set() while len(seen_uuids) < repetitions: a, b = test_q.get(timeout=JOIN_TIMEOUT) assert a == b assert a not in seen_uuids seen_uuids.add(a)
def test_tree_locals(self): g = g2 = None def func(): child = greenlet.Greenlet() self.assertIs(child.spawn_tree_locals, getcurrent().spawn_tree_locals) self.assertIs(child.spawning_greenlet(), getcurrent()) g = greenlet.Greenlet(func) g2 = greenlet.Greenlet(func) # Creating those greenlets did not give the main greenlet # a locals dict. self.assertFalse(hasattr(getcurrent(), 'spawn_tree_locals'), getcurrent()) self.assertIsNot(g.spawn_tree_locals, g2.spawn_tree_locals) g.start() g.join() raw = gevent.spawn_raw(func) self.assertIsNotNone(raw.spawn_tree_locals) self.assertIsNot(raw.spawn_tree_locals, g.spawn_tree_locals) self.assertIs(raw.spawning_greenlet(), getcurrent()) while not raw.dead: gevent.sleep(0.01)
def sync_details(): """ Sync AWS details into redis and reply status """ lock_time, expire_timeout = redis_handler.get_lock() if lock_time in ['0', 0]: expire_timeout = expire_timeout if expire_timeout else 0 return "Synced recently. It can be started again after %s secs" \ % expire_timeout elif lock_time: return "Sync in progress. Started %s secs ago" \ % (int(time.time()) - int(lock_time)) else: if config.SYNC_LOCK: timeout = config.SYNC_TIMEOUT + config.MIN_SYNC_GAP redis_handler.save_lock(timeout=timeout) gevent.spawn_raw(sync_everything) return 'OK - Sync initiated'
def test_wrap_greenlet(self): def func(): gevent.sleep(0.010) return "ok" gt = gevent.spawn_raw(func) fut = aiogevent.wrap_greenlet(gt) result = self.loop.run_until_complete(fut) self.assertEqual(result, "ok")
def test_wrap_greenlet_exc(self): self.loop.set_debug(True) def func(): raise ValueError(7) gt = gevent.spawn_raw(func) fut = aiogevent.wrap_greenlet(gt) self.assertRaises(ValueError, self.loop.run_until_complete, fut)
def test_gevent_executor(self): from gevent import sleep, spawn_raw from gevent.event import Event count = 1 finish_event = Event() def task(): executor = geventFutureExecutor ret = executor.apply_future(self.foo, count) assert ret == count + 1 finish_event.set() spawn_raw(task) while not finish_event.is_set(): sleep(0.02)
def test_wrap_greenlet_dead(self): event = gevent.event.Event() def func(): event.set() gt = gevent.spawn_raw(func) event.wait() msg = "wrap_greenlet: the greenlet already finished" self.assertRaisesRegex(RuntimeError, msg, aiogevent.wrap_greenlet, gt)
def on_session_heartbeat(self, event): """Capture every heartbeat event in a session and post info """ params = {} answer_seconds_since_epoch = float( event['Caller-Channel-Answered-Time']) / 1000000 # using UTC here .. make sure FS is using UTC also params['AnsweredTime'] = str(answer_seconds_since_epoch) heartbeat_seconds_since_epoch = float( event['Event-Date-Timestamp']) / 1000000 # using UTC here .. make sure FS is using UTC also params['HeartbeatTime'] = str(heartbeat_seconds_since_epoch) params['ElapsedTime'] = str(heartbeat_seconds_since_epoch - answer_seconds_since_epoch) called_num = event['variable_plivo_destination_number'] if not called_num or called_num == '_undef_': called_num = event['Caller-Destination-Number'] or '' called_num = called_num.lstrip('+') params['To'] = called_num params['From'] = event['Caller-Caller-ID-Number'].lstrip('+') params['CallUUID'] = event['Unique-ID'] params['Direction'] = event['Call-Direction'] forwarded_from = get_substring(':', '@', event['variable_sip_h_Diversion']) if forwarded_from: params['ForwardedFrom'] = forwarded_from.lstrip('+') if event['Channel-State'] == 'CS_EXECUTE': params['CallStatus'] = 'in-progress' # RequestUUID through which this call was initiated if outbound request_uuid = event['variable_plivo_request_uuid'] if request_uuid: params['RequestUUID'] = request_uuid accountsid = event['variable_plivo_accountsid'] if accountsid: params['AccountSID'] = accountsid self.log.debug("Got Session Heartbeat from Freeswitch: %s" % params) if self.get_server().call_heartbeat_url: self.log.debug("Sending heartbeat to callback: %s" % self.get_server().call_heartbeat_url) spawn_raw(self.send_to_url, self.get_server().call_heartbeat_url, params)
def test_wrap_greenlet_running(self): event = gevent.event.Event() result = [] def func(): try: gt = gevent.getcurrent() fut = aiogevent.wrap_greenlet(gt) except Exception as exc: result.append((True, exc)) else: result.append((False, fut)) event.set() gevent.spawn_raw(func) event.wait() error, value = result[0] self.assertTrue(error) self.assertIsInstance(value, RuntimeError) self.assertEqual(str(value), "wrap_greenlet: the greenlet is running")
def send_attachment(self, channel, *attachments): if channel in self._channel_id_cache: channel = self._channel_id_cache[channel] elif not channel.startswith('#'): channel = '#' + channel args = { 'username': self._jeev.name, 'link_names': self._link_names, 'channel': channel, 'attachments': [a.serialize() for a in attachments] } for a in attachments: if not a.has_message_overrides: continue for k, v in a.message_overrides.items(): args[k] = v spawn_raw(self._requests.post, self._send_url, json.dumps(args))
def test_gevent_executor_http(self, httpserver): from gevent import sleep, spawn_raw from gevent.event import Event content = b'Hello world!' httpserver.serve_content(content=content) finish_event = Event() def task(): executor = geventFutureExecutor ret = executor.apply_future(self.foo_http, httpserver.url) assert ret == content executor.apply_future(self.stop_httpserver, httpserver) finish_event.set() spawn_raw(task) while not finish_event.is_set(): sleep(0.02)
def test_spawn_raw_kwargs(self): value = [] def f(*args, **kwargs): value.append(args) value.append(kwargs) g = gevent.spawn_raw(f, 1, name='value') gevent.sleep(0.01) assert not g self.assertEqual(value[0], (1,)) self.assertEqual(value[1], {'name': 'value'})
def on_channel_progress_media(self, event): request_uuid = event['variable_plivo_request_uuid'] direction = event['Call-Direction'] # Detect early media state # See http://wiki.freeswitch.org/wiki/Early_media#Early_Media_And_Dialing_Out if request_uuid and direction == 'outbound': try: call_req = self.call_requests[request_uuid] except (KeyError, AttributeError): return # only send if not already ringing/early state if not call_req.state_flag: # set state flag to 'EarlyMedia' call_req.state_flag = 'EarlyMedia' # clear gateways to avoid retry call_req.gateways = [] called_num = event['variable_plivo_destination_number'] if not called_num or called_num == '_undef_': called_num = event['Caller-Destination-Number'] or '' called_num = called_num.lstrip('+') caller_num = event['Caller-Caller-ID-Number'] call_uuid = event['Unique-ID'] or '' self.log.info("Call from %s to %s in EarlyMedia for RequestUUID %s" \ % (caller_num, called_num, request_uuid)) # send ring if ring_url found ring_url = call_req.ring_url if ring_url: params = { 'To': called_num, 'RequestUUID': request_uuid, 'Direction': direction, 'CallStatus': 'ringing', 'From': caller_num, 'CallUUID': call_uuid } # add extra params extra_params = self.get_extra_fs_vars(event) if extra_params: params.update(extra_params) spawn_raw(self.send_to_url, ring_url, params)
def __init__(self, host=None, port=None, password=None, idle_timeout=None): global connection_pool if host is None: host = '127.0.0.1' if port is None: port = 6379 if not connection_pool: connection_pool = redis.ConnectionPool(host=host, port=port, password=password) self.connection = redis.StrictRedis(connection_pool=connection_pool) self.idle_timeout = idle_timeout self.instance_hash_prefix = 'aws:ec2:instance' ## Suffix: region, instance id self.ebs_vol_hash_prefix = 'aws:ec2:ebs:vol' ## Suffix: region, volume id self.ebs_snapshot_hash_prefix = 'aws:ec2:ebs:snap' ## Suffix: region, snapshot id self.elb_hash_prefix = 'aws:ec2:elb' ## Suffix: region, elb name self.elastic_ip_hash_prefix = 'aws:ec2:elastic_ip' ## Suffix: ip_address self.index_prefix = 'aws:index' ## Suffix: index_item self.all_tags_hash = 'sethji:indexed_tags' ## No Suffix self.sync_lock_hash = 'sethji:sync_lock' ## No Suffix self.last_sync_time_hash = 'sethji:last_sync_time' ## No Suffix self.object_cache_hash = 'sethji:object_cache' ## object path gevent.spawn_raw(self._close_idle_connections)
def on_session_heartbeat(self, event): """Capture every heartbeat event in a session and post info """ params = {} answer_seconds_since_epoch = float(event["Caller-Channel-Answered-Time"]) / 1000000 # using UTC here .. make sure FS is using UTC also params["AnsweredTime"] = str(answer_seconds_since_epoch) heartbeat_seconds_since_epoch = float(event["Event-Date-Timestamp"]) / 1000000 # using UTC here .. make sure FS is using UTC also params["HeartbeatTime"] = str(heartbeat_seconds_since_epoch) params["ElapsedTime"] = str(heartbeat_seconds_since_epoch - answer_seconds_since_epoch) called_num = event["variable_plivo_destination_number"] if not called_num or called_num == "_undef_": called_num = event["Caller-Destination-Number"] or "" called_num = called_num.lstrip("+") params["To"] = called_num params["From"] = event["Caller-Caller-ID-Number"].lstrip("+") params["CallUUID"] = event["Unique-ID"] params["Direction"] = event["Call-Direction"] forwarded_from = get_substring(":", "@", event["variable_sip_h_Diversion"]) if forwarded_from: params["ForwardedFrom"] = forwarded_from.lstrip("+") if event["Channel-State"] == "CS_EXECUTE": params["CallStatus"] = "in-progress" # RequestUUID through which this call was initiated if outbound request_uuid = event["variable_plivo_request_uuid"] if request_uuid: params["RequestUUID"] = request_uuid accountsid = event["variable_plivo_accountsid"] if accountsid: params["AccountSID"] = accountsid self.log.debug("Got Session Heartbeat from Freeswitch: %s" % params) if self.get_server().call_heartbeat_url: self.log.debug("Sending heartbeat to callback: %s" % self.get_server().call_heartbeat_url) spawn_raw(self.send_to_url, self.get_server().call_heartbeat_url, params)
def run_blocking_call(A): print "starting blocking loop" tic = time.time() numpy.dot(A, A.transpose()) print "blocked for %.3f s" % (time.time() - tic) if __name__ == '__main__': dev = ThreadDevice(zmq.FORWARDER, zmq.SUB, zmq.XREQ) dev.setsockopt_in(zmq.SUBSCRIBE, "") dev.setsockopt_out(zmq.IDENTITY, str(os.getpid())) dev.connect_in('tcp://127.0.0.1:5555') dev.connect_out('tcp://127.0.0.1:5556') # dev.start() gevent.spawn_raw(dev.start) gevent.spawn_later(0, im_alive, 5) gevent.sleep(0) A = numpy.random.random((2**11, 2**11)) while True: try: run_blocking_call(A) print 'Sleeping' gevent.sleep(1) except KeyboardInterrupt: print 'Exiting' break
def spawn_n(method, *args, **kwargs): global alive g = gevent.spawn_raw(method, *args, **kr) alive += 1 g.link(removeOne)
def on_custom(self, event): # case conference event if self.current_element == 'Conference': # special case to get Member-ID for Conference if event['Event-Subclass'] == 'conference::maintenance' \ and event['Action'] == 'add-member' \ and event['Unique-ID'] == self.get_channel_unique_id(): self.log.debug("Entered Conference") self._action_queue.put(event) # special case for hangupOnStar in Conference elif event['Event-Subclass'] == 'conference::maintenance' \ and event['Action'] == 'kick' \ and event['Unique-ID'] == self.get_channel_unique_id(): room = event['Conference-Name'] member_id = event['Member-ID'] if room and member_id: self.bgapi("conference %s kick %s" % (room, member_id)) self.log.warn("Conference Room %s, member %s pressed '*', kicked now !" \ % (room, member_id)) # special case to send callback for Conference elif event['Event-Subclass'] == 'conference::maintenance' \ and event['Action'] == 'digits-match' \ and event['Unique-ID'] == self.get_channel_unique_id(): self.log.debug("Digits match on Conference") digits_action = event['Callback-Url'] digits_method = event['Callback-Method'] if digits_action and digits_method: params = {} params['ConferenceMemberID'] = event['Member-ID'] or '' params[ 'ConferenceUUID'] = event['Conference-Unique-ID'] or '' params['ConferenceName'] = event['Conference-Name'] or '' params[ 'ConferenceDigitsMatch'] = event['Digits-Match'] or '' params['ConferenceAction'] = 'digits' spawn_raw(self.send_to_url, digits_action, params, digits_method) # special case to send callback when Member take the floor in Conference # but only if member can speak (not muted) elif event['Event-Subclass'] == 'conference::maintenance' \ and event['Action'] == 'floor-change' \ and event['Unique-ID'] == self.get_channel_unique_id() \ and event['Speak'] == 'true': self._action_queue.put(event) # case dial event elif self.current_element == 'Dial': if event['Event-Subclass'] == 'plivo::dial' \ and event['Action'] == 'digits-match' \ and event['Unique-ID'] == self.get_channel_unique_id(): self.log.debug("Digits match on Dial") digits_action = event['Callback-Url'] digits_method = event['Callback-Method'] if digits_action and digits_method: params = {} params['DialDigitsMatch'] = event['Digits-Match'] or '' params['DialAction'] = 'digits' params['DialALegUUID'] = event['Unique-ID'] params['DialBLegUUID'] = event['variable_bridge_uuid'] spawn_raw(self.send_to_url, digits_action, params, digits_method)
def spawn_n(function, *args, **kwargs): global alive g = gevent.spawn_raw(method, *args, **kr) alive += 1 g.link(removeOne)
def background_sync(self): gevent.spawn_raw(self.sync)
def set_hangup_complete(self, request_uuid, call_uuid, reason, event, hangup_url): params = {} # add extra params params = self.get_extra_fs_vars(event) # case incoming call if not request_uuid: self.log.info("Hangup for Incoming CallUUID %s Completed, HangupCause %s" \ % (call_uuid, reason)) # get hangup url hangup_url = event['variable_plivo_hangup_url'] if hangup_url: self.log.debug("Using HangupUrl for CallUUID %s" \ % call_uuid) else: if self.get_server().default_hangup_url: hangup_url = self.get_server().default_hangup_url self.log.debug("Using HangupUrl from DefaultHangupUrl for CallUUID %s" \ % call_uuid) elif event['variable_plivo_answer_url']: hangup_url = event['variable_plivo_answer_url'] self.log.debug("Using HangupUrl from AnswerUrl for CallUUID %s" \ % call_uuid) elif self.get_server().default_answer_url: hangup_url = self.get_server().default_answer_url self.log.debug("Using HangupUrl from DefaultAnswerUrl for CallUUID %s" \ % call_uuid) if not hangup_url: self.log.debug("No HangupUrl for Incoming CallUUID %s" % call_uuid) return called_num = event['variable_plivo_destination_number'] if not called_num or called_num == '_undef_': called_num = event['Caller-Destination-Number'] or '' called_num = called_num.lstrip('+') caller_num = event['Caller-Caller-ID-Number'] direction = event['Call-Direction'] # case outgoing call, add params else: self.log.info("Hangup for Outgoing CallUUID %s Completed, HangupCause %s, RequestUUID %s" % (call_uuid, reason, request_uuid)) try: call_req = self.call_requests[request_uuid] called_num = call_req.to.lstrip('+') caller_num = call_req._from if call_req._accountsid: params['AccountSID'] = call_req._accountsid direction = "outbound" self.call_requests[request_uuid] = None del self.call_requests[request_uuid] except (KeyError, AttributeError): called_num = '' caller_num = '' direction = "outbound" self.log.debug("Call Cleaned up for RequestUUID %s" % request_uuid) if not hangup_url: self.log.debug("No HangupUrl for Outgoing Call %s, RequestUUID %s" % (call_uuid, request_uuid)) return forwarded_from = get_substring(':', '@', event['variable_sip_h_Diversion']) aleg_uuid = event['Caller-Unique-ID'] aleg_request_uuid = event['variable_plivo_request_uuid'] sched_hangup_id = event['variable_plivo_sched_hangup_id'] params['RequestUUID'] = request_uuid if forwarded_from: params['ForwardedFrom'] = forwarded_from.lstrip('+') if aleg_uuid: params['ALegUUID'] = aleg_uuid if aleg_request_uuid: params['ALegRequestUUID'] = aleg_request_uuid if sched_hangup_id: params['ScheduledHangupId'] = sched_hangup_id # if hangup url, handle http request if hangup_url: sip_uri = event['variable_plivo_sip_transfer_uri'] or '' if sip_uri: params['SIPTransfer'] = 'true' params['SIPTransferURI'] = sip_uri params['CallUUID'] = call_uuid or '' params['HangupCause'] = reason params['To'] = called_num or '' params['From'] = caller_num or '' params['Direction'] = direction or '' params['CallStatus'] = 'completed' spawn_raw(self.send_to_url, hangup_url, params)
def _handle_message(self, message, client): if message.author == client.me: return # Schedule the handling of the message to occur during the next iteration of the event loop. gevent.spawn_raw(self.__handle_message, message)
def handle_request(self, request, session): gevent.spawn_raw(_gevent_echo, request, session)
def _run(self): while True: spawn_raw(self.f, *self.args, **self.kwargs) sleep(self.interval)
def get_page(url): gevent.spawn_raw(requests,url)
def start(self): """Start an asynchronous getaddrinfo invocation.""" if self._greenlet is None: self._greenlet = gevent.spawn_raw(self._resolve) else: LOGGER.warning("_GeventAddressResolver already started")
def test_killall_raw(self): g = gevent.spawn_raw(lambda: 1) gevent.killall([g])
def set_database_uri(self, uri): """Set the database uri""" if uri != self.database_uri: log.debug("Setting database URI to %s", uri) self.database_uri = uri gevent.spawn_raw(self.create_engine)