def __init__(self, usr='******', pwd='123456a@', host='localhost', port=5672, vhost='vh1'): self.vhost = vhost creds = pika.PlainCredentials(username=usr, password=pwd) params = pika.ConnectionParameters(host=host, port=port, virtual_host=vhost, credentials=creds) self.is_waiting = False self.c = Caller() try: self.conn = pika.BlockingConnection(parameters=params) self.ch = self.conn.channel() except pika.exceptions.ProbableAccessDeniedError: logging.info("[AppServer] Connection error. Check configuration.") return None except: return None # declare a queue to reply res = self.ch.queue_declare(exclusive=True, queue='reply') self.reply_queue = res.method.queue # get the queue name self.ch.basic_consume(queue=self.reply_queue, consumer_callback=self.on_feedback, no_ack=True) logging.info("[AppServer] Done init ...")
def __init__(self, usr='******', pwd='123456a@', host='localhost', port=5672, vhost='vh1'): logging.info("BEGIN INIT THE [AppServer] ----------------------------->") self.vhost = vhost creds = pika.PlainCredentials(username=usr, password=pwd) params = pika.ConnectionParameters(host=host, port=port, virtual_host=vhost, credentials=creds) # is in waiting state self.is_waiting = False # is initiate successfully self.is_init = False self.c = Caller() try: self.conn = pika.BlockingConnection(parameters=params) self.ch = self.conn.channel() except pika.exceptions.ProbableAccessDeniedError: logging.critical("[AppServer] Connection error. Check configuration.") return None except: return None # declare a queue to reply try: res = self.ch.queue_declare(exclusive=True, queue='reply') self.reply_queue = res.method.queue # get the queue name self.ch.basic_consume(queue=self.reply_queue, consumer_callback=self.on_feedback, no_ack=True) except pika.exceptions.ChannelClosed as e: logging.critical("[AppServer] The pika channel is closed. Error message: {0}".format(e)) return None except Exception as e: logging.critical("[AppServer] Unknown error while init app: {0}".format(e)) return None self.is_init = True logging.info("[AppServer] Done init ...")
def pm(debug, host): """Connect to password manager""" logger = Logger(debug) logger.debug('debug mode on') caller = None p_key_derived = None try: if not Caller.check_up(host): logger.error('error creating session: host down') else: logger.debug('host up') key, p_key_derived = Input.get_public_key() logger.debug('creating a new session...') caller = Caller(host, key) logger.info(f'session created') except ConnectionError as ce: logger.error(f'error creating session: connection error - {str(ce)}') except TypeError as te: logger.error(f'error creating session: wrong input - {str(te)}') if caller is not None: InteractiveInput(caller, logger, p_key_derived).cmdloop()
def call(namespace): caller = Caller(verbose=True) phone = namespace.phone if namespace.phone is not None else 9023618802 trunk = namespace.trunk if namespace.trunk is not None else '2' phone2 = namespace.phone2 if namespace.phone2 is not None else None trunk = decipher(trunk) if not trunk: print('указан несуществующий транк - ошибка') return muid = str(uuid.uuid4()) with TeleDB() as db: db << 'INSERT INTO `tele_material` (`intphone`, `region_id`, `extra`, `start_dial`,`trunk_dial`) \ VALUES (%s,33,2,NOW(),%s)' < (int(phone), muid) db << 'SELECT last_insert_id() as id' ids = [db.one()['id']] if phone2: db << 'INSERT INTO `tele_material` (`intphone`, `region_id`, `extra`, `start_dial`,`trunk_dial`) \ VALUES (%s,33,2,NOW(),%s)' < (int(phone2), muid) db << 'SELECT last_insert_id() as id' ids.append(db.one()['id']) #import pdb; pdb.set_trace() if not caller.produce(db, trunk, ids): db << 'UPDATE `tele_material` SET `trunk_dial`=NULL,`start_dial`=NULL WHERE `id` = %s' < muid
def webapp_login(): global caller # logging in if request.method == 'POST': host_param = request.form['host'] try: if not Caller.check_up(host_param): return render_template("login.html", msg='host is down', host=host_param) private_key_df = request.form['private_key'] private_key_df_derived = Parser.derive(private_key_df) public_key_df = gen_public_key(private_key_df_derived) caller = Caller(host_param, public_key_df) return redirect(url_for('webapp.webapp_main', path='', dirname='')) except TypeError as te: return render_template("login.html", msg=str(te), host=host_param) elif request.method == 'GET': if caller is not None: if caller.get_session().status_code == 200: return redirect(url_for('webapp.webapp_main', path='', dirname='')) return render_template("login.html")
def __init__(self, vhost_data): Greenlet.__init__(self) self.vhost_data = vhost_data self.app1 = AppServer(usr=self.vhost_data['user'], pwd=self.vhost_data['password'], host=self.vhost_data['host'], port=self.vhost_data['port'], vhost=self.vhost_data['name']) self.c = Caller()
def trunk(namespace): #import pdb; pdb.set_trace() trunk = decipher(namespace.trunk) if not trunk: print('указан несуществующий транк - ошибка') return with TeleDB() as db: router = MaterialRouter(db) feedstock = router.feedstock(trunk) if feedstock and namespace.verbose: print('Запас ' + str(len(feedstock))) caller = Caller(verbose=namespace.verbose) if not caller.produce(db, trunk, feedstock): db << 'UPDATE `tele_material` SET `trunk_dial`=NULL,`start_dial`=NULL WHERE `trunk_dial` = %s' < router.uid
def times(array): return [ Caller.bubble_sort(array=array), Caller.bubble_sort_with_flag(array=array), Caller.insertion_sort(array=array), Caller.selection_sort(array=array), Caller.shell_sort(array=array), Caller.merge_sort(array=array), Caller.quick_sort(array=array), Caller.counting_sort(array=array), Caller.radix_sort(array=array) ]
class AppCore(Greenlet): def __init__(self, vhost_data): Greenlet.__init__(self) self.vhost_data = vhost_data self.app1 = AppServer(usr=self.vhost_data['user'], pwd=self.vhost_data['password'], host=self.vhost_data['host'], port=self.vhost_data['port'], vhost=self.vhost_data['name']) self.c = Caller() def _run(self): current_thread().name = self.vhost_data['name'] while 1: # reload config importlib.reload(coreconfig) # begin get vhosts & ips self.ips = self.c.getIPS(coreconfig.CoreConfig.URL_GET_LIST_IP, self.vhost_data['name']) # self.ips = ['192.168.1.1', '192.168.1.2', '192.168.1.3'] if self.app1 is not None: self.app1.push(self.ips) time.sleep(coreconfig.CoreConfig.PING_INTERVAL_SECONDS)
def run(self): caller = Caller.Instance() notchFreq = [50] highCutOff = 80 caller.raw.filter(l_freq=None, h_freq=highCutOff, n_jobs=2) caller.raw.notch_filter(freqs=notchFreq) self.emit_filterFinished()
def callFilter(self): finished = QtCore.pyqtSignal() caller = Caller.Instance() caller.raw.filter(l_freq=None, h_freq=self.highCutOff, n_jobs=2) caller.raw.notch_filter(freqs=self.notchFreq) finished.emit()
class Intercom(object): def __init__(self, led_red_channel, led_green_channel, doors_channel, btn_call_channel, snd_dev_capture="default", snd_dev_playback="default"): self.selected_sipid = "sip:localhost" self.led_red = OnOffDevice(led_red_channel) self.led_green = OnOffDevice(led_green_channel) self.doors = OnOffDevice(doors_channel) self.caller = Caller(snd_dev_capture, snd_dev_playback, simple_callback_factory=self._callback_factory) self.buttonCall = Button(btn_call_channel, self.call) def _callback_factory(self): intercom = self class _IntercomCallCallback(SimpleCallCallback): def on_connecting(self): intercom.led_green.start_blinking(0.5) def on_connected(self): intercom.led_green.set(True) def on_disconnected(self): intercom.led_green.set(False) return _IntercomCallCallback() def call(self): self.caller.call(self.selected_sipid) def cancel_call(self): self.caller.cancel_call() def open_door(self, duration=5): self.doors.set(True) time.sleep(duration) self.doors.set(False)
def __init__(self, verbose=0): """ Class constructor """ self.verbose = verbose # Object to do dashboard call self.dashcall = DashboardCaller(verbose=1) # Object shared to do server calls self.servercall = Caller(verbose=1) self.config_file = None self.config = []
def get_server_status(self): """ Read all server status """ status = [] for server in self.config: stat = {} self.servercall = Caller() self.servercall.set_cfg(server) stat["status"] = self.servercall.call(route="status", verb="GET", data=None) stat["name"] = server.name["name"] status.append(stat) return status
def __init__(self, led_red_channel, led_green_channel, doors_channel, btn_call_channel, snd_dev_capture="default", snd_dev_playback="default"): self.selected_sipid = "sip:localhost" self.led_red = OnOffDevice(led_red_channel) self.led_green = OnOffDevice(led_green_channel) self.doors = OnOffDevice(doors_channel) self.caller = Caller(snd_dev_capture, snd_dev_playback, simple_callback_factory=self._callback_factory) self.buttonCall = Button(btn_call_channel, self.call)
def do_refresh(self, arg): """ Get a fresh new session from server """ key = Input.get_public_key() current_host = self.caller.host try: self.caller = Caller(current_host, key) self.logger.info('session refreshed') except ConnectionError as ce: self.logger.error( f'error creating session: connection error - {str(ce)}') except TypeError as te: self.logger.error( f'error creating session: wrong input - {str(te)}')
class AppCore(Greenlet): def __init__(self, vhost_data): Greenlet.__init__(self) self.vhost_data = vhost_data self.app1 = AppServer(usr=self.vhost_data['user'], pwd=self.vhost_data['password'], host=self.vhost_data['host'], port=self.vhost_data['port'], vhost=self.vhost_data['name']) self.c = Caller() def _run(self): current_thread().name = self.vhost_data['name'] while 1: # reload config importlib.reload(coreconfig) # check if app is None logging.info("[AppCore] Current app is: {0}".format(self.app1)) if not self.app1.is_init: # re-initate logging.info("[AppCore] App isn't init properly. Re-initiate now ...") self.app1 = AppServer(usr=self.vhost_data['user'], pwd=self.vhost_data['password'], host=self.vhost_data['host'], port=self.vhost_data['port'], vhost=self.vhost_data['name']) logging.info("[AppCore] Now sleeping {0}s...".format(coreconfig.CoreConfig.PING_INTERVAL_SECONDS)) time.sleep(coreconfig.CoreConfig.PING_INTERVAL_SECONDS) # yes, ignore to continue continue # begin get vhosts & ips logging.info("[AppCore] Begin getting IPs ...") self.ips = self.c.getIPS(coreconfig.CoreConfig.URL_GET_LIST_IP, self.vhost_data['name']) # self.ips = ['192.168.1.1', '192.168.1.2', '192.168.1.3'] if self.app1.is_init and self.ips: self.app1.push(self.ips) else: logging.info("[AppCore] Nothing to push (app is None or get IPs failed)") logging.info("[AppCore] Now sleeping {0}s...".format(coreconfig.CoreConfig.PING_INTERVAL_SECONDS)) time.sleep(coreconfig.CoreConfig.PING_INTERVAL_SECONDS)
class TestCaller(unittest.TestCase): @patch.object(Caller, '_read_file', mock_read_file) def setUp(self): self.c = Caller('from', 'sid', 'authkey') def test_init(self): self.assertEqual(self.c._from_number, 'from') self.assertEqual(self.c._account_sid, 'sid') self.assertEqual(self.c._auth_key, 'authkey') def test_read_file(self): self.assertIsNotNone(self.c._data) self.assertIsInstance(self.c._data, dict) def test_loop(self): self.assertIsNotNone(self.c._loop) self.assertIsInstance(self.c._loop, AbstractEventLoop) def test_session(self): self.assertIsNotNone(self.c._session) self.assertIsInstance(self.c._session, aiohttp.ClientSession) def test_logger(self): self.assertIsNotNone(self.c._logger) self.assertIsInstance(self.c._logger, logging.Logger) def test_parse_data(self): self.assertIsInstance(self.c._accounts, set) self.assertNotIn('account_two', self.c._accounts) for a in self.c._accounts: self.assertIsInstance(a, Account) def test_make_url(self): self.assertEqual( self.c._make_url('testpath'), 'https://api.twilio.com/2010-04-01/Accounts/sid/testpath.json')
def start(self, seq): ## self.db = adbapi.ConnectionPool('MySQLdb', host='localhost', ## user='******', passwd='HerrMeister', ## db='actor') # listen on all devices for t in seq.trunks: for i in range(t.lines): c = Caller(seq, self, t.name) self.devices.append(c) c.send(c, 'LSTN %s %s' % (t.name, 'any')) self.a_hackcenter = A_Hackcenter() self.a_haecksen = A_Haecksen(seq) self.b_se = B_SE() self.b_nw = B_NW() self.b_ne = B_NE() self.b_sw = B_SW() self.b_lounge = B_Lounge(seq) self.b_saal2 = B_Saal2(seq) self.b_saal3 = B_Saal3(seq) self.c_se = C_SE() self.c_nw = C_NW() self.c_ne = C_NE() self.c_sw = C_SW() self.c_office = C_Office() self.c_saal1 = C_Saal1(seq) self.entry = self.b_se # Floor A connect(self.a_hackcenter, self.a_haecksen, Door(), 'south') # Floor B connect(self.b_se, self.b_sw, Door(), 'west') connect(self.b_se, self.b_ne, Door(), 'north') connect(self.b_sw, self.b_nw, Door(), 'north') connect(self.b_ne, self.b_nw, Door(), 'west') connect(self.b_se, self.b_lounge, Door(), 'northwest') connect(self.b_sw, self.b_lounge, Door(), 'northeast') connect(self.b_nw, self.b_lounge, Door(), 'southeast') connect(self.b_ne, self.b_lounge, Door(), 'southwest') connect(self.b_sw, self.b_saal3, Door(), 'west') connect(self.b_nw, self.b_saal2, Door(), 'west') # Floor C connect(self.c_se, self.c_sw, Door(), 'west') connect(self.c_se, self.c_ne, Door(), 'north') connect(self.c_sw, self.c_nw, Door(), 'north') connect(self.c_ne, self.c_nw, Door(), 'west') connect(self.c_se, self.c_saal1, Door(), 'northwest') connect(self.c_sw, self.c_saal1, Door(), 'northeast') connect(self.c_nw, self.c_saal1, Door(), 'southeast') connect(self.c_ne, self.c_saal1, Door(), 'southwest') connect(self.c_sw, self.c_office, Door(), 'west') # Stairs connect(self.b_ne, self.a_hackcenter, Stairs(), 'northeast', 'northeast') connect(self.b_se, self.c_se, Stairs(), 'southeast', 'southeast') connect(self.b_sw, self.c_sw, Stairs(), 'southwest', 'southwest') connect(self.b_nw, self.c_nw, Stairs(), 'northwest', 'northwest') self.update_shortcuts()
class AppServer(object): def __init__(self, usr='******', pwd='123456a@', host='localhost', port=5672, vhost='vh1'): self.vhost = vhost creds = pika.PlainCredentials(username=usr, password=pwd) params = pika.ConnectionParameters(host=host, port=port, virtual_host=vhost, credentials=creds) self.is_waiting = False self.c = Caller() try: self.conn = pika.BlockingConnection(parameters=params) self.ch = self.conn.channel() except pika.exceptions.ProbableAccessDeniedError: logging.info("[AppServer] Connection error. Check configuration.") return None except: return None # declare a queue to reply res = self.ch.queue_declare(exclusive=True, queue='reply') self.reply_queue = res.method.queue # get the queue name self.ch.basic_consume(queue=self.reply_queue, consumer_callback=self.on_feedback, no_ack=True) logging.info("[AppServer] Done init ...") def on_feedback(self, ch, method, props, body): self.is_waiting = False logging.info("[AppServer] Received Corr_id: {0}".format(props.correlation_id)) # logging.info(body) if props.correlation_id == self.corr_id: # call a function to insert result to db # format data #self.vhost = self.vhost.decode('utf-8') body = body.decode('utf-8') body = json.loads(body) # begin inser toinsert = {'vhost': self.vhost, 'data': body} #c = Caller() self.c.insertIPS(coreconfig.CoreConfig.URL_POST_TRANSACTION, toinsert) #logging.info("The post data: {0}".format(toinsert)) self.res = body return False #return false to signal to consume that you're done. other wise it continues to block def push(self, msg): """ :param msg: list IP to ping msg = ['1.1.1.1', '2.2.2.2', '3.3.3.3', ] dumps -> encoder loads -> decoder :return: """ try: self.corr_id = str(uuid.uuid4()) self.res = None self._msg = json.dumps(msg) logging.info("[AppServer] Sent corr_id: {0}".format(self.corr_id)) #logging.info("[x] Processing: {0}".format(self._msg)) if not self.is_waiting: self.ch.basic_publish( exchange='', routing_key='default', properties=pika.BasicProperties( correlation_id=self.corr_id, content_type='text/plain', delivery_mode=2, reply_to=self.reply_queue, ), body=self._msg, ) logging.info("[AppServer] Done pushing ...") else: logging.info("[AppServer] Is waiting for the queue: {0}".format(self.is_waiting)) pass # waiting while (self.res is None): self.is_waiting = True self.conn.process_data_events(time_limit=0) return self.res except Exception as e: logging.info("[AppServer] Exception while pushing message.") raise e return False
sys.path.append("./src") from caller import Caller if __name__ == '__main__': PARSER = argparse.ArgumentParser(description='Options to access micro service') PARSER.add_argument('--service', dest='service', help='service to access') PARSER.add_argument('--job', dest='job', help='job to report') PARSER.add_argument('--status', dest='status', help='job status to report') args = PARSER.parse_args() APP = Caller(verbose=1, serverip="localhost", port="8080") APP.set_verbose(1) APP.set_ip(serverip="localhost") APP.set_port(port="8080") if "create" in args.service: ROUTE = "create/" + str(args.job) APP.call(route=ROUTE, verb="POST", data=None) elif "delete" in args.service: ROUTE = "delete/" + str(args.job) APP.call(route=ROUTE, verb="DELETE", data=None) elif "search" in args.service: ROUTE = "search/" + str(args.job) APP.call(route=ROUTE, verb="GET", data=None)
async def _init_caller(self): self.caller = Caller(settings.TWILIO_FROM_NUMBER, settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_KEY)
#!/usr/bin/env python # encoding: utf-8 import sys from caller import Caller if __name__ == "__main__": caller = Caller() while True: sys.stdout.write("Provide sip id: or q to exit") line = sys.stdin.readline().strip() if line == "q": break caller.call(line) sys.stdout.write("enter to end the call") sys.stdin.readline() caller.cancel_call() sys.exit(0)
def setUp(self): self.c = Caller('from', 'sid', 'authkey')
class AppServer(object): def __init__(self, usr='******', pwd='123456a@', host='localhost', port=5672, vhost='vh1'): self.vhost = vhost creds = pika.PlainCredentials(username=usr, password=pwd) params = pika.ConnectionParameters(host=host, port=port, virtual_host=vhost, credentials=creds) self.is_waiting = False self.c = Caller() try: self.conn = pika.BlockingConnection(parameters=params) self.ch = self.conn.channel() except pika.exceptions.ProbableAccessDeniedError: logging.info("[AppServer] Connection error. Check configuration.") return None except: return None # declare a queue to reply res = self.ch.queue_declare(exclusive=True, queue='reply') self.reply_queue = res.method.queue # get the queue name self.ch.basic_consume(queue=self.reply_queue, consumer_callback=self.on_feedback, no_ack=True) logging.info("[AppServer] Done init ...") def on_feedback(self, ch, method, props, body): self.is_waiting = False logging.info("[AppServer] Received Corr_id: {0}".format( props.correlation_id)) # logging.info(body) if props.correlation_id == self.corr_id: # call a function to insert result to db # format data #self.vhost = self.vhost.decode('utf-8') body = body.decode('utf-8') body = json.loads(body) # begin inser toinsert = {'vhost': self.vhost, 'data': body} #c = Caller() self.c.insertIPS(coreconfig.CoreConfig.URL_POST_TRANSACTION, toinsert) #logging.info("The post data: {0}".format(toinsert)) self.res = body return False #return false to signal to consume that you're done. other wise it continues to block def push(self, msg): """ :param msg: list IP to ping msg = ['1.1.1.1', '2.2.2.2', '3.3.3.3', ] dumps -> encoder loads -> decoder :return: """ try: self.corr_id = str(uuid.uuid4()) self.res = None self._msg = json.dumps(msg) logging.info("[AppServer] Sent corr_id: {0}".format(self.corr_id)) #logging.info("[x] Processing: {0}".format(self._msg)) if not self.is_waiting: self.ch.basic_publish( exchange='', routing_key='default', properties=pika.BasicProperties( correlation_id=self.corr_id, content_type='text/plain', delivery_mode=2, reply_to=self.reply_queue, ), body=self._msg, ) logging.info("[AppServer] Done pushing ...") else: logging.info( "[AppServer] Is waiting for the queue: {0}".format( self.is_waiting)) pass # waiting while (self.res is None): self.is_waiting = True self.conn.process_data_events(time_limit=0) return self.res except Exception as e: logging.info("[AppServer] Exception while pushing message.") raise e return False
class Broker(object): """ Broker object to control regression system along Gitlab push/issue/merge requests """ def __init__(self, verbose=0): """ Class constructor """ self.verbose = verbose # Object to do dashboard call self.dashcall = DashboardCaller(verbose=1) # Object shared to do server calls self.servercall = Caller(verbose=1) self.config_file = None self.config = [] def set_config_file(self, config): """ Configuration file setter """ self.config_file = config def setup(self): """ Function to setup the server from configuration file """ self.config = [] tree = etree.parse(self.config_file) root = tree.getroot() # Read from xml configuration file all # the available resources for server in root.find("servers"): srv = {} srv["namespace"] = server.attrib['namespace'] srv["version"] = server.attrib['version'] srv["name"] = server.attrib['name'] srv["ip"] = server.attrib['ip'] srv["port"] = server.attrib['port'] srv["type"] = server.attrib['type'] srv["place"] = server.attrib['place'] srv["vendor"] = server.attrib['vendor'] srv["board"] = server.attrib['board'] self.config.append(srv) # Configure the dashboard caller for server in self.config: if server["namespace"] == "dashboard": self.dashcall.setup(server) if self.verbose: print "info - broker.py - Configuration loaded:" for server in self.config: print server def filter_hooks(self): """ Function to filter hooks and launch them after a mean time to avoid multiple useless runs """ pass def get_dashboard(self): """ Read all server status """ return self.dashcall.read_dashboard() def get_dashboard_help(self): """ Read all server status """ return self.dashcall.read_help() def get_server_status(self): """ Read all server status """ status = [] for server in self.config: stat = {} self.servercall = Caller() self.servercall.set_cfg(server) stat["status"] = self.servercall.call(route="status", verb="GET", data=None) stat["name"] = server.name["name"] status.append(stat) return status