def initialize(self): """! Initializes redis cache with lauch variables which will persist through out the application. And performs certain housekeeping tasks. @return: void """ try: with open(os.path.dirname(os.path.realpath(os.path.dirname(__file__))) + '/scripts/launch_config.json') as file: config = json.load(file) self.redis_cache.set ('instance',None) self.redis_cache.set('default_instance', config['pyliner']['default_instance']) self.redis_cache.set('address', config['pyliner']['address']) self.redis_cache.set('port', config['pyliner']['port']) self.redis_cache.set('video_port', config['pyliner']['video_port']) self.redis_cache.set('adsb_port', config['pyliner']['adsb_port']) self.redis_cache.set('number_of_workers', config['number_of_workers']) self.redis_cache.set('mode', config['mode']) self.redis_cache.set('app_path', config['app_path']) self.redis_cache.set('t_btn_cnt',0) ## clean test database, table if int(self.redis_cache.get('mode')) == 0: conn = sqlite3.connect(self.redis_cache.get('app_path') + '/test_database', timeout=5) c = conn.cursor() ex = 'delete from TESTCASES' c.execute(ex) conn.commit() conn.close() tk.log('Preconfiguration', 'Successful', 'INFO') except Exception as e: ## TODO: safely log error, unit test required tk.log('Preconfiguration', 'Faliure - '+str(e), 'ERROR') #tk.log('Preconfiguration', 'Faliure - '+str(e), 'ERROR') pass
def cmd2_disconnect( message): """! Accepts disconnection message and disconnects with client. @param message: disconnection request from client, this message will disconnection headers. @return: void """ Feedback = json.dumps("ENDOK") message.reply_channel.send({'close': True, 'text': Feedback}) tk.log('defaultInstance', 'Commanding (dis)connected from client', 'INFO')
def cmd2_connect( message): """! Accepts request and establishes a connection with client. @param message: connection request from client, this message will connection headers. @return: void """ Feedback = json.dumps("OK") message.reply_channel.send({'accept': True, 'text': Feedback}) tk.log(defaultInstance,'Commanding connected to client','INFO')
def tlm_disconnect( message): """! Accepts disconnection message and disconnects with client. @param message: disconnection request from client, this message will disconnection headers. @return: void """ Feedback = json.dumps("ENDOK") message.reply_channel.send({'close': True, 'text':Feedback}) Group('tlm_bc').discard(message.reply_channel) tk.log('Instance', '(Dis)connected.', 'INFO')
def tlm_connect( message): """! Accepts request and establishes a connection with client. @param message: connection request from client, this message will connection headers. @return: void """ Group('tlm_bc').add(message.reply_channel) Feedback = json.dumps("OK") message.reply_channel.send({'accept': True, 'text':Feedback}) tk.log('Instance', 'Connected.', 'INFO')
def directoryListing(message): """! Takes the file or directory name in the message object, scrapes file system and sends out a json to client which has sub-directories listed. @param message: message object with directory or file name is sent from the client. @return: void """ name = message.content['text'] response = tk.get_directory(name) data = json.dumps(response) ## Train test_db_wrapper(name, data,'DIR','obtain directory listing') message.reply_channel.send({'text': data}) tk.log('Directory',' Packet ' + name + ' sent.','INFO')
def test_db_wrapper(input,output,code,desc): """! This is a hook to record inputs and subsequent outputs that are generated by Command. @param input: a string object before a certain process is applied on it. @param output: a string object after the process is applied on it. @param code: a user defined string, categorizes various database entries. @param desc: description of the process that is applied on the input. @return: void """ if mode == 0: try: conn = sqlite3.connect(test_db_path + '/test_database', timeout=5) tk.collectTestCases(conn, code, input, output, desc) conn.commit() conn.close() tk.log('Train', 'Item inserted in database.', 'DEBUG') except: ## TODO: safely log error, unit test required tk.log('Train', 'NA', 'ERROR') pass
def push(websocket_obj,message_obj): """! A non-busy forever loop pushes events to client. @param websocket_obj: websocket object @param message_obj: message object @return: void """ while True: result = websocket_obj.recv() ## If result is not a ACK signal, in YAMCS case ACK for events looks like `[1,4,x]` if result.find('[1,4,')!=-1 : #result = tk.preProcess(result) message_obj.reply_channel.send({'text': result}) message_obj.reply_channel.send({'text': result}) message_obj.reply_channel.send({'text': result}) tk.log('Event', 'BOUND', 'INFO') print message_obj.reply_channel.__dict__ print result ## avoids busy-while-loop time.sleep(0.01)
def getEvents(message): """! Upon receipt of invoke signal this function generates a process which pushes live event feeds to client. Upon receipt of kill signal the fucntion will kill the running process. @param message: event message object is sent from the client. @return: void """ message_text = message.content['text'] client_id = message.content['reply_channel'] ## when invoke signal is received if message_text == 'INVOKE': data = '[1, 1, 1, {"events": "subscribe"}]' ws = None if defaultInstance == 'None': ws = create_connection('ws://' + address + ':' + str(port) + '/'+redis_cache.get('default_instance')+'/_websocket') else: ws = create_connection('ws://' + address + ':' + str(port) + '/'+defaultInstance+'/_websocket') ws.send(data) t = Process(target=push, args=(ws, message)) t.start() proc_map_e[client_id] = t.pid sock_map_e[client_id] = ws # when kill signal is received elif message_text =='KILLSWITCH': try: us_sock = sock_map_e[client_id] data = '[1, 1, 1, {"events": "unsubscribe"}]' us_sock.send(data) tk.log('Event', '[UNSIBSCRIBED] - ' + client_id+' events', 'DEBUG') except: ## TODO: safely log error, unit test required tk.log('Event','Unable to unsubscribe.','ERROR') pass try: to_kill_pid = proc_map_e[client_id] print '****', to_kill_pid, proc_map_e to_kill = psutil.Process(to_kill_pid) to_kill.kill() tk.log('Event', '[KILLED] - ' + to_kill_pid, 'DEBUG') except: ## TODO: safely log error, unit test required tk.log('Event', 'Unable to kill.', 'ERROR') pass
def index(r, a=None): """! Serves various files like pug and js. @param r: param 1 @param a: param 2 @return: Rendered Response """ if a == None: log('index.pug', '[REQUEST] Index page requested.', 'INFO') return render(r, 'index.pug') elif a.find('.js') != -1: log('/' + a, '[REQUEST] Javascript document requested.', 'INFO') return render(r, str(a)) elif a.find('groundcontrol_video_socket') != -1: log('/' + a, '[REQUEST] Websocket requested.', 'INFO') return HttpResponse('Connected to websockets.') else: log('/' + a + '.pug', '[REQUEST] Document requested.', 'INFO') return render(r, str(a + '.pug'))
def pug_router(r, a, b, c=None, d=None): """ Serves various files like pug and js. @param r: param 1 @param a: param 2 @param b: param 3 @param c: param 4 @param d: param 5 @return: Rendered Response """ if c == None and d == None: log(str(a + '/' + b), '[REQUEST] Document requested.', 'INFO') return render(r, str(a + '/' + b)) elif d == None: log(str(a + '/' + b + '/' + c), '[REQUEST] Document requested.', 'INFO') return render(r, str(a + '/' + b + '/' + c)) else: log(str(a + '/' + b + '/' + c + '/' + d), '[REQUEST] Document requested.', 'INFO') return render(r, str(a + '/' + b + '/' + c + '/' + d))
def router(r, a, b, c=None, d=None): """! Serves various files like pug and js. @param r: param 1 @param a: param 2 @param b: param 3 @param c: param 4 @param d: param 5 @return: Rendered Response """ if c == None and d == None: log(str(a + '/' + b + '.pug'), '[REQUEST] Document requested.', 'INFO') try: json = readJsonFromCloseCirlce(str(a)) except: json = 'NULL' return render(r, str(a + '/' + b + '.pug'), {'obj': json}) elif d == None: log(str(a + '/' + b + '/' + c + '.pug'), '[REQUEST] Document requested.', 'INFO') try: json = readJsonFromCloseCirlce(str(a + '/' + b + '/')) except: json = 'NULL' return render(r, str(a + '/' + b + '/' + c + '.pug'), {'obj': json}) else: log(str(a + '/' + b + '/' + c + '/' + d + '.pug'), '[REQUEST] Document requested.', 'INFO') try: json = readJsonFromCloseCirlce(str(a + '/' + b + '/' + c + '/')) except: json = 'NULL' return render(r, str(a + '/' + b + '/' + c + '/' + d + '.pug'), {'obj': json})
def getTelemetry( message): """! Takes the telemetry message object and either sends a subscribe or unsubscribe signal to pyliner/yamcs. Creates or destroys `push` processes based on signal received. @param message: telemetry message object is sent from the client. @return: void """ message_client_id = message.content['reply_channel'] ## clean text message_text = tk.byteify(message.content['text']) ## unsubscribe signal if message_text.find('kill_tlm') != -1: try: msg = message_text.replace('kill_tlm', '') msg_text_obj = json.loads(msg) temp = ' {"parameter":"unsubscribe", "data":{"list":' + str(tk.byteify(msg_text_obj['tlm'])) + '}}' temp = temp.replace("\'", "\"") to_send = '[1,1,0,' + str(temp) + ']' ## Train test_db_wrapper(message_text,'null','KILTLM','unsubscribe telemetry') ## sending unsubscribe signal to pyliner/yamcs sock_map[message_client_id].send(to_send) tk.log('Instance', '[UNSUBSCRIBED] - '+message_client_id+' - '+msg, 'DEBUG') except: ## TODO: safely log error, unit test required tk.log('Instance', '[ERR - UNSUBSCRIBED] - ' + message_client_id + ' - ' + message_text, 'ERROR') pass ## kill all processes elif message_text.find('USALL')!=-1: try: to_kill_pid = proc_map[message_client_id] to_kill = psutil.Process(to_kill_pid) to_kill.kill() del proc_map[message_client_id] del sock_map[message_client_id] tk.log('Instance', '[KILLED] - ' + str(to_kill_pid), 'DEBUG') except: ## TODO: safely log error, unit test required tk.log('Instance', '[ERR - KILLED] - NA', 'ERROR') pass ## Subscribe signal ## Send message, start a system process, store current data in a local dict. elif message_text.find('tlm')!=-1: msg_text_obj = json.loads(message_text) temp = ' {"parameter":"subscribe", "data":{"list":' + str(tk.byteify(msg_text_obj['tlm'])) + '}}' temp = temp.replace("\'", "\"") to_send = '[1,1,0,' + str(temp) + ']' ## Train test_db_wrapper(message_text, 'null', 'SUBTLM', 'subscribe telemetry') ## One time per application cycle. if message_client_id not in sock_map.keys(): try: client_id = message.content['reply_channel'] #print client_id #ws = create_connection('ws://' + str(address) + ':' + str(port) + '/' + redis_cache.get('instance') + '/_websocket') ws = create_connection('ws://127.0.0.1:8090/softsim/_websocket') #print ws sock_map[client_id] = ws #msg_map[message_client_id] = message sock_map[message_client_id].send(to_send) #print client_id #print sock_map #Feedback = json.dumps("OK") #message.reply_channel.send({'text': Feedback}) process = Process(target=push1,args=(sock_map[message_client_id],)) process.start() proc_map[client_id] = process.pid tk.log('Instance', '[PROCESS] - ' + str(process.pid) , 'DEBUG') except Exception as e: ## TODO: safely log error, unit test required tk.log('Instance', '[ERR - PROCESS] - '+str(e)+' - ' + message_client_id + ' - ' + message_text, 'ERROR') pass ## If already a socket is created then continue and use that socket else: try: sock_map[message_client_id].send(to_send) tk.log('Instance', '[SUBSCRIBED] - ' + message_client_id + ' - ' + message_text, 'DEBUG') except: ## TODO: safely log error, unit test required tk.log('Instance', '[ERR - SUBSCRIBED] - ' + message_client_id + ' - ' + message_text, 'DEBUG') pass