def requestTransfer(self, tid, numChunks, msg): start = tid logger.info('Started thread {} for Request {}'.format( tid, msg[REQUEST_ID])) # while the reqId is to be downloaded try: while start < numChunks: with self.chunkLeftLock: ok = (start in self.chunkLeft[msg[REQUEST_ID]][1]) msg[CHUNK_NO] = start while ok: logger.info( 'Asking Chunk {} for Request {} from {} ({})'.format( start, msg[REQUEST_ID], msg[DEST_IP], msg[DEST_GUID])) network.send(msg[DEST_IP], **msg) time.sleep(TRANS_WAIT) with self.chunkLeftLock: ok = (start in self.chunkLeft[msg[REQUEST_ID]][1]) start += NUM_THREADS except KeyError: pass logger.info('Finishing thread {} for Request {}'.format( tid, msg[REQUEST_ID]))
def _sendCreate(self): network.send(CREATE) if not self._getAck(CREATE): print "PLM, NU MERGE CREAT" return False return True
def broadcast_action_data(self): frame_data_str = self.frame_data.SerializeToString() for player_uid, player_conn in self.conn_list.items(): send(player_conn, const.FUNC_NAME_TO_OPCODE["action_data"], frame_data_str) frame = self.frame_data.frame self.frame_data = tps_message_pb2.SC_Fight_Message() self.frame_data.frame = frame + 1
def handle_heartbeat(strs): print "Received heartbeat.." instance.last_heartbeat_rcvd = time.time() if instance.is_master and instance.name != strs[instance.SENDER]: master.clear_master() instance.curr_master = strs[instance.SENDER] instance.nodes = [] nodecount = int(strs[instance.NODECOUNT]) for i in range(4, 4 + nodecount): s = strs[i] val = s.split('#') d = dict() d['name'] = val[0] d['password'] = val[1] d['ip'] = val[2] d['port'] = val[3] instance.nodes.append(config.Node(**d)) if val[3] == '0': network.remove_peer(val[0]) reply = "master:heartbeatreply" network.send(instance.curr_master, reply) video_name = strs[4 + nodecount] video_ip = strs[5 + nodecount] video_port = int(strs[6 + nodecount]) for i in range(8 + nodecount, len(strs)): instance.chat_msgs += ":" + strs[i] api.update_video_source(video_name, video_ip, video_port)
def run(): picture = camera.tomat() storage.picture = picture cv2.imshow("Original", picture) cv2.setMouseCallback("Original", click_get_hsv) coordinates = worker.process2(picture) if (coordinates.found()): network.send(coordinates)
def _sendStart(self): network.send(START) if not self._getAck(START): print "PLM, NU MERGE START" else: state.in_game = True state.in_game_lobby = False
def _sendJoin(self, game_id): network.send(JOIN + str(game_id)) print "JOIN ", game_id if not self._getAck(JOIN): print "PLM, NU MERGE JOIN" return False return True
def send_text_msg(text): msg = "node:textmsg:" + text instance.gmutex.acquire() for peer in network.get_connection_list(): if peer == instance.name: continue; network.send(peer, msg) instance.gmutex.release()
def _update_clients(self, message, exclude=None): log_event_send(message['event'], message['args'], label='Server') for name, sock in self.current_players.items(): if name != exclude: network.send(sock, message) if self.local_player != exclude: self.local_interface.handle(message)
def send_video_req(): instance.gmutex.acquire() if instance.is_master: msg = instance.name + ":master:videoreq:" + instance.local_ip + ":" + str(instance.video_port) master.handle_message(msg, None) else: msg = "master:videoreq:" + instance.local_ip + ":" + str(instance.video_port) network.send(instance.curr_master, msg) instance.gmutex.release()
def send_video_stop_req(): instance.gmutex.acquire() if instance.is_master: msg = instance.name + ":master:videostop" master.handle_message(msg, None) else: msg = "master:videostop" network.send(instance.curr_master, msg) instance.gmutex.release()
def send_text_msg(text): msg = "node:textmsg:" + text instance.gmutex.acquire() log_text_msg(instance.name, text) gui.append_chat_msg(time.strftime("%H-%M-%S"), instance.name, text) for peer in network.get_connection_list(): if peer == instance.name: continue; network.send(peer, msg) instance.gmutex.release()
def game_list(session): while(1): network.send( session, packet.gamelist_request()) time.sleep(1) a = network.receive( session ) if a==None: continue if a["__type"] == "GameListReply:#Messages.ReplyMessages": return session, a["GameInfo"] else: log.warning("Unexpected packet received: " + str(a) ) return session, None
def sendPing(self, destGUID, destIP): pingMsg = { TYPE: PING, SEND_IP: MY_IP, SEND_GUID: self.myGUID, DEST_IP: destIP, DEST_GUID: destGUID } network.send(pingMsg[DEST_IP], **pingMsg) self.mutexPP.acquire() self.sentPing.append(destGUID) self.mutexPP.release()
def findContent(self, searchQ): # Check for minimum query size if len(searchQ) < QUERY_MIN_SIZE: print("Query too small!") return with self.queryResLock: if self.queryResQueue.qsize() >= QUERY_QUEUE: print("Throwing away older queries!") while self.queryResQueue.qsize() >= QUERY_QUEUE: which = self.queryResQueue.get() del self.queryRes[which] logger.warning('Throwing away query {}'.format(which)) qId = network.generate_uuid_from_guid(self.GUID, self.queryCnt) self.queryRes[qId] = [] self.queryResQueue.put(qId) self.save_queryResQueue(qId) # Save State self.save_queryRes() # Save State logger.info('Generated Query {}'.format(qId)) queryMsg = { TYPE: QUERY, SEND_IP: MY_IP, SEND_GUID: self.GUID, SOURCE_IP: MY_IP, SOURCE_GUID: self.GUID, SEARCH: searchQ, QUERY_ID: qId } self.queryCnt += 1 # Caching for ignoring repeated with self.repQuerLock: while self.repQuerQueue.qsize() >= REP_QUERY_CACHE: self.repQuer.discard(self.repQuerQueue.get()) self.repQuer.add(queryMsg[QUERY_ID]) self.repQuerQueue.put(queryMsg[QUERY_ID]) self.save_repQuerQueue(queryMsg[QUERY_ID]) # Save State logger.info('Adding query {} to cache'.format(queryMsg[QUERY_ID])) # Sending Query to neighbours for flooding for neighbours in self.routTab.neighbours(): queryMsg[DEST_IP] = neighbours[0] queryMsg[DEST_GUID] = neighbours[1] network.send(queryMsg[DEST_IP], **queryMsg) logger.info('Sending query to neighbour {} ({})'.format( queryMsg[DEST_IP], queryMsg[DEST_GUID])) print("Query Id: {}".format(qId))
def send_heartbeats(): data = gen_heartbeat_str() print "Sending heartbeats..", data for peer in network.get_connection_list(): if peer not in instance.heartbeat_time: instance.heartbeat_time[peer] = time.time() if (time.time() - instance.heartbeat_time[peer]) >= instance.HEARTBEAT_TIMEOUT: print "Timeout: ", peer, "Current time: ", time.time(), "Last replied: ", instance.heartbeat_time[peer] #TODO: handle timeout else: network.send(peer, data) #print "Heartbeat reply times:", instance.heartbeat_time api.update_video_source(instance.curr_video_name, instance.curr_video_ip, instance.curr_video_port)
def __init__(self, room_id, conn_list): self.frame_data = tps_message_pb2.SC_Fight_Message() self.frame_data.frame = 1 self.order_list = [] self.conn_list = conn_list ready_list = {} self.ready_list = ready_list self.room_id = room_id msg = create_rpc_data({"func_name": "RoomCreateSuccess"}) for player_uid, player_conn in conn_list.items(): ready_list[player_uid] = False room_index[player_uid] = room_id send(player_conn, const.FUNC_NAME_TO_OPCODE["rpc_command"], msg)
def _handleLogin(self, **params): user = params.get("USER") password = params.get("PASS") message = LOGIN + " " + user + " " + password # Send the credentials network.send(message) ans = network.recv() if ans == "ok": return True return False
def game_start(asd, gamers): # schnelles durchprobieren, ob genug spieler da sind amount_players = 0 for i in range(0, 4): # enough players or bots if gamers[i] in [1, 2, 4]: # human, bot or networkplayer amount_players += 1 if amount_players in [0, 1]: return del amount_players for i in range(4): # players with no names if start_window.names[i].get_text() == "" and start_window.sel_but.get_active_text() != "Closed": start_window.bgohg = gtk.MessageDialog(message_format="Ein Spieler hat keinen Namen") start_window.bgohg.show_all() return # game can begin if network.hosting: network.send("g") for i in range(4): if start_window.sel_but[i].get_active_text() != "Network": network.gamedetails.op.append(i) # set players print(network.gamedetails.op) for i in range(0, 4): if start_window.loaded: break if gamers[i]: game.players[i] = plun.player(i, "balubel") game.players[i].name = start_window.names[i].get_text() else: game.players[i] = 0 # Make sure that the grave of the other players is grey surface.restrict_to_player(game.memo.act_pl.nr) start_window.optwindow.hide() start_window.joinwindow.hide() start_window.hide() surface.set_visi(True) # todo: network stuff # send msg to clients that the game has started # send playernames to the server and otherway round # send rules of the game surface.pre_render(game.players) game.newgame() surface.set_msg(game.memo.get_plstr() + "\nstarts the game")
def __init__(self, myAddr, otherAddrs): self.running = True self.myAddr = myAddr self.otherAddrs = otherAddrs self.num_elems = 3 # there are 3 entries in our multi-paxos log. # For each log element that we need to reach consensus on, # make a PaxosNode, arrange to have its outgoing msgs # tagged with its element index, and give it a function # it can use to communicate with the other nodes' PaxosNodes # that correspond to that particular array element. # # Note the incredibly shitty "i=i" expr in the lambda. # Without it, the value i resolves to the max value of all i's in the range. # (This is bad.) self.paxosNodes = [] for i in range(self.num_elems): p = PaxosNode( nodeid=(self.myAddr, i), otherAddrs=[(o, i) for o in otherAddrs], sendfn=lambda d, i=i: network.send(d['to'][0], { 'paxos': True, 'elem': i, 'msg': d }) # [0]: to get the IP addr from the (addr,elementindex) nodeid ) self.paxosNodes.append(p)
def login(fname, lname, anumber, alias, endpoint, label=None): if label==None: label=alias id = packet.ID() id.fname = fname id.lname = lname id.alias = alias id.anumber = anumber session = Session() #only ipv4 for now. Splits port from IP (address, port) = endpoint.split(":") port = eval(port) session.registry = (address,port) session.id = id while session.socket == None: session.socket = network.create_socket() log.info("Logging in") #While we're still waiting on a login reply, keep listening status = 0 while(session.login == False): network.send( session, packet.login_request(session.id, label) ) time.sleep(1) data = network.receive(session) if data==None: continue if(data["__type"] == "LoginReply:#Messages.ReplyMessages"): if(data["Success"]): log.info("Login succeeded") session.procinfo = data["ProcessInfo"] session.login = True else: log.error("Login failed") log.error("Error message was: "+ data["Note"]) return session else: log.warning("Unexpected packet received: " + str(data) ) return session
def get_ready(self, player_uid): self.ready_list[player_uid] = True is_all_ready = True for _, is_ready in self.ready_list.items(): if not is_ready: is_all_ready = False break if is_all_ready: msg = create_rpc_data({"func_name": "AllPlayerGameReady"}) for player_uid, player_conn in self.conn_list.items(): send(player_conn, const.FUNC_NAME_TO_OPCODE["rpc_command"], msg) def timer_callback(): self.broadcast_action_data() print time.time() self.room_timer = timer.create_timer(timer_callback, 1, -1)
def parse(data,addr,session): log.debug("Parsing: "+data) try: packet = json.loads(data) #Bad packet - Log error and return None (Try to keep working) except json.decoder.JSONDecodeError: log.error("Bad JSON Packet: " + data) return None #reply request - handle and return None if( packet["__type"] == "AliveRequest:#Messages.RequestMessages" ): log.debug("Sending KeepAlive Reply") network.send(session,alive_reply()) return None return packet
def __init__(self,myAddr,otherAddrs): self.running = True self.myAddr = myAddr self.otherAddrs = otherAddrs self.num_elems = 3 # there are 3 entries in our multi-paxos log. self.paxosNodes = [] for i in range(self.num_elems): p = PaxosNode( nodeid=(self.myAddr,i), otherAddrs=[(o,i) for o in otherAddrs], sendfn=lambda d,i=i: network.send(d['to'][0],{'paxos':True,'elem':i,'msg':d}) # [0]: to get the IP addr from the (addr,elementindex) nodeid ) self.paxosNodes.append(p)
def update(network, force=False): deets = None while True: # send local teams' deets if players == 3: network.send(teams[2].deets, force) deets = network.send(teams[0].deets, force) if deets is not None or not force: break # update remote teams' deets (if they were retrieved before a timeout) if deets is not None: if players == 2: teams[1].update(deets[1 - teams[0].teamID]) elif players == 3: teams[1].update(deets[1 - teams[0].teamID]) teams[3].update(deets[3 - teams[0].teamID]) elif players == 4: for t in range(3): try: teams[t + 1].update(deets[teams[t + 1].teamID]) except: pass else: if players == 2: teams[1].ships[0].move() elif players == 3: teams[1].ships[0].move() teams[3].ships[0].move() elif players == 4: for t in range(3): try: teams[t + 1].ships[0].move() except: pass return deets
def joinNetwork(self, bootstrapIP): # Create a Join Message and send it to the bootstrap peer joinMsg = { TYPE: JOIN, SEND_IP: MY_IP, DEST_IP: bootstrapIP, } # Wait for the JOIN_ACK message while not self.isJoined: # If error sending JOIN message while not network.send(bootstrapIP, **joinMsg): time.sleep(ERROR_RETRY) logger.warning( 'Failed to send JOIN message to {}'.format(bootstrapIP)) logger.info('Sent JOIN message to {}'.format(bootstrapIP)) clientsock, address = self.sock.accept() if address[0] == bootstrapIP: data = network.receive(clientsock) if data and data[TYPE] == JOIN_ACK: self.GUID = data[DEST_GUID] self.isJoined = True # Initialise RT self.routTab.initialise(rt=data[ROUTING], myGUID=self.GUID, Central_GUID=data[SEND_GUID], Central_IP=bootstrapIP) # State Details print("Joined Network! Your GUID: {}".format(self.GUID)) logger.info('Joined Network! GUID: {}'.format(self.GUID))
def networkPoll(self): data = network.getInput() for e in data: a = e[0] # adress e = e[1] # message # print e if e[0] == "g": # gamestart game_start("lan", self.pl) elif e[0] == "d": if network.hosting: network.send(e, a, True) game.throw_the_dice("butter", inp=int(e[1])) elif e[0] == "z": if network.hosting: print("MUHAHAHA") # this is called repeatedly network.send(e, a, True) game.actio(int(e[2]), None, int(e[1]), fr=True) # actio(doing,player,unit) elif e[0] == "o": # optionsaenderung #TODO might not work, hasnt been tested if e[1] == "c": # change chessmod self.optwindow.chessmod.set_active(int(e[1])) # self.optwindow.chessmod.toggled() elif e[1] == "j": # change jumps self.optwindow.check_jumps.set_active(int(e[1])) # TODO geht nicht, und nur host darf das aendern else: continue elif e[0] == "s": # spieleraenderung try: num = int(e[1]) # which player except: continue if e[2] == "n": # name self.names[num].set_text(e[3:]) elif e[2] == "c": # controlled how t = {"h": 0, "n": 3, "b": 2, "c": 1}[e[3]] self.sel_but[num].set_active(t) else: continue elif e[0] == "e": # end of turn if network.hosting: # send it to everyone else network.send("e", adress=a, n=True) game.next_pl("nw") else: # nix continue return 1
def send_to_all(self, message): for player in self.players: if player.is_connected(): send(message, player.connection)
def process_respondable(self, key, word, connection_to_player): print("Processing: ", key, str(word).replace('\n', ' '), str(connection_to_player)[-19:-1]) if key == 'name': for player in self.players: if not player.connected and hasattr( player, 'name') and player.name == word: player.connect(word, connection_to_player) print(word + " reconnected.") return_table = [] for card in self.table: return_table.append([card.suit, card.number]) send( { 'connection': True, 'reply': word + ' reconnected to ' + self.name, 'chat': self.chat, 'hand': player.hand_to_list(), 'players': self.players_name_list(), 'table': return_table, 'turn': self.turn }, player.connection) self.send_to_all() return if not player.connected and not hasattr(player, 'name'): player.connect(word, connection_to_player) print(word + " connected.") return_table = [] for card in self.table: return_table.append([card.suit, card.number]) send( { 'connection': True, 'reply': word + ' connected to ' + self.name, 'chat': self.chat, 'hand': player.hand_to_list(), 'table': return_table, 'turn': self.turn }, player.connection) self.send_to_all( to_dict('players', self.players_name_list())) return print(self.players_name_list()) send({ 'connection': False, 'reply': self.name + ' is full' }, connection_to_player) elif key == 'picture': for player in self.players: if player.is_connected(connection_to_player): player.picture = word break for player in self.players: if player.is_connected(): self.send_to_all( to_dict('picture', [player.turn_number, player.picture])) elif key == 'chat': for player in self.players: if player.is_connected(connection_to_player): self.chat += player.name + ": " + word + '\n' self.send_to_all(to_dict("chat", player.name + ": " + word)) elif key == 'disconnected': for player in self.players: if player.is_connected(connection_to_player): player.disconnect() self.send_to_all( to_dict('reply', player.name + " disconnected.")) elif key == 'report': for player in self.players: if player.is_connected(connection_to_player): self.send_to_all( to_dict("reply", player.name + " reported himself")) elif key == 'pass': for player in self.players: if player.is_connected( connection_to_player) and player.my_turn(): if self.passs(): self.table = [] self.send_to_all(to_dict("table", self.table)) self.next_turn() self.send_to_all(to_dict('turn', self.turn)) elif key == 'play': for player in self.players: if player.is_connected( connection_to_player) and player.my_turn(): play_list = [] for card_list in word: play_list.append(Card(card_list[0], card_list[1])) play = Play(play_list) if play.value() and play > Play(self.table): self.table = play_list.copy() self.next_turn() for player in self.players: if player.is_connected(connection_to_player): player.hand = [ card for card in player.hand if not card in play_list or play_list.remove(card) ] send({'hand': player.hand_to_list()}, connection_to_player) return_table = [] for card in self.table: return_table.append( [card.suit, card.number]) self.send_to_all({ "table": return_table, 'players': self.players_name_list() }) else: for player in self.players: if player.is_connected(connection_to_player): send(to_dict("reply", "Bad play"), player.connection) else: if player.is_connected(connection_to_player): send(to_dict("reply", "Not your turn"), player.connection) else: print("Unknown key ", key, " : ", word)
def LCMPRequestHandler(connection, lcmpPacket, connectionTable, sessionID): """ Beschreibung: wird von connectionHandler() aufgerufen und bearbeitet LCMP-Pakete mit "Request"-Typ. Der OpType des Pakets wird mit geprüft und je nach Wert, werden andere Aktionen ausgeführt. Diese Aktionen generieren mind. einen Fehler- code und oft auch Daten. Beides wird am Ende an den Client zurückgesendet (als "Answer"-Typ und mit dem gleichen OpType, wie der, der Request-Anforderung) Parameter: (socket)connection: Enthält die Verbindungsinformationen des Client. (tuple)lcmpPacket: Enthält die Daten eines LCMP-Paketes (list)connectionTable: Enthält alle noch aktiven Verbindungen (int)sessionID: Die aktuelle ID der Session Rückgabewert: Keiner Exceptions: LCMPError """ errorcode = 0 data = "" opType = lcmp.OPTYPES_REVERSE[lcmpPacket[lcmp.LCMP_INDICES["OpType"]]] sessionName = "" connectionTable_sessionIDs = getSessionIDs(connectionTable) # Hat die Session schon einen zugehörigen Computernamen? Dann zeige ihn an. if connectionTable[connectionTable_sessionIDs.index(sessionID)][2] == "": sessionName = "Session %s" % sessionID else: sessionName = connectionTable[connectionTable_sessionIDs.index(sessionID)][2] log.writeLogLV(config_backend.getLogfile(), "%s: %s: Client requests: %s with data: %s\n" % (threading.currentThread().name, sessionName, lcmp.OPTYPES_REVERSE[lcmpPacket[lcmp.LCMP_INDICES["OpType"]]], lcmpPacket[lcmp.LCMP_INDICES["Data"]]), log.LOGLEVEL["info"]) # Dieser Try-Block soll alle Fehler abfangen, die innerhalb des Data-Backends auftreten # natürlich können damit auch andere Fehler abgefangen werden, die dann gesondert behandelt # werden müssen try: if (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["quitConnection"]): errorcode = 0 data = "Goodbye" connectionTable_sessionIDs = getSessionIDs(connectionTable) # Entferne sessionID aus connectionTable, wenn der Client die Verbindung beendet. connectionTable.remove(connectionTable[connectionTable_sessionIDs.index(sessionID)]) # Client Operationen elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["addClient"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) # Setze interne Optionen und überschreibe benutzerdefinierte Optionen, wenn jemand versucht # die internen Optionen so zu überschreiben options["last-seen"] = "never" options["created-on"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if "scriptmember" in options: del options["scriptmember"] if errorcode == 0: errorcode = data_backend.addClient(name, options) else: # parseNameAndOptions() hat nicht funktioniert pass # der errorcode von parseNameAndOptions wird im LCMP-Errorfeld # zurückgesendet und muss nicht mehr gesetzt werden data = "" # Es müssen keine Nutzdaten zurückgesendet werden, also kann das Feld leer bleiben else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["removeClient"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) if errorcode == 0: errorcode = data_backend.removeClient(name) else: # parseNameAndOptions() hat nicht funktioniert pass # der errorcode von parseNameAndOptions wird im LCMP-Errorfeld # zurückgesendet und muss nicht mehr gesetzt werden data = "" # Es müssen keine Nutzdaten zurückgesendet werden, also kann das Feld leer bleiben else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["modifyClient"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) if errorcode == 0: errorcode = data_backend.modifyClient(name, options) else: # parseNameAndOptions() hat nicht funktioniert pass # der errorcode von parseNameAndOptions wird im LCMP-Errorfeld # zurückgesendet und muss nicht mehr gesetzt werden data = "" # Es müssen keine Nutzdaten zurückgesendet werden, also kann das Feld leer bleiben else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["getClients"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.getClients() else: errorcode = error.ERRORS["NotAllowed"] data = "" # Gruppen Operationen elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["addGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) # Wenn keine Parent-Gruppe angegeben ist, nehme die 'root'-Gruppe if not 'parent' in options: options["parent"] = "root" else: # Prüfen, ob die parentGruppe existiert if not options["parent"] in data_backend.getGroupNames()[1]: errorcode = error.ERRORS["ParentGroupDoesNotExist"] # Lösche interne Optionen, wenn jemand versucht, die internen Optionen so zu überschreiben if "member" in options: del options["member"] if "scriptmember" in options: del options["scriptmember"] if errorcode == 0: errorcode = data_backend.addGroup(name, options) data = "" else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["removeGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) if errorcode == 0: errorcode = data_backend.removeGroup(name) else: # parseNameAndOptions() hat nicht funktioniert pass # der errorcode von parseNameAndOptions wird im LCMP-Errorfeld # zurückgesendet und muss nicht mehr gesetzt werden data = "" # Es müssen keine Nutzdaten zurückgesendet werden, also kann das Feld leer bleiben else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["modifyGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) if errorcode == 0: errorcode = data_backend.modifyGroup(name, options) else: # parseNameAndOptions() hat nicht funktioniert pass # der errorcode von parseNameAndOptions wird im LCMP-Errorfeld # zurückgesendet und muss nicht mehr gesetzt werden data = "" # Es müssen keine Nutzdaten zurückgesendet werden, also kann das Feld leer bleiben else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["getGroups"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.getGroups() else: errorcode = error.ERRORS["NotAllowed"] data = "" # Script Operationen elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["addScript"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) if errorcode == 0: if 'path' in options: if not core.doesFileExist(options['path']): errorcode = error.ERRORS['ScriptDoesNotExistInFilesystem'] else: options["md5"] = core.getMD5(options['path']) if not 'active' in options: options['active'] = "true" elif options['active'] == "true" or\ options['active'] == "yes" or\ options['active'] == "1": options['active'] = "true" elif options['active'] == "false" or\ options['active'] == "no" or\ options['active'] == "0": options['active'] = "false" else: options['active'] = "true" errorcode = data_backend.addScript(name, options) else: errorcode = error.ERRORS['IllegalNumberOfParameters'] # TODO: Neuen Errorcode else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["removeScript"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) if errorcode == 0: errorcode = data_backend.removeScript(name) else: # parseNameAndOptions() hat nicht funktioniert pass # der errorcode von parseNameAndOptions wird im LCMP-Errorfeld # zurückgesendet und muss nicht mehr gesetzt werden data = "" # Es müssen keine Nutzdaten zurückgesendet werden, also kann das Feld leer bleiben else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["modifyScript"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, name, options = parseNameAndOptions(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) if errorcode == 0: errorcode = data_backend.modifyScript(name, options) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["getScripts"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.getScripts() else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["getScripts"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.getScriptsFull() else: errorcode = error.ERRORS["NotAllowed"] data = "" # Client & Gruppen Operationen elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["addClientToGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode = data_backend.addClientToGroup(lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[0], lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[1]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["removeClientFromGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode = data_backend.removeClientFromGroup(lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[0], lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[1]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["showClientsOfGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.showClientsOfGroup(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["showGroupsOfClient"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.showGroupsOfClient(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) else: errorcode = error.ERRORS["NotAllowed"] data = "" # Client & Skript Operationen elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["addScriptToClient"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode = data_backend.addScriptToClient(lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[0], lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[1]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["removeScriptFromClient"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode = data_backend.removeScriptFromClient(lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[0], lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[1]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["showScriptsOfClient"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.showScriptsOfClient(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["showClientsOfScript"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.showClientsOfScript(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) else: errorcode = error.ERRORS["NotAllowed"] data = "" # Gruppen & Skript Operationen elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["addScriptToGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode = data_backend.addScriptToGroup(lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[0], lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[1]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["removeScriptFromGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode = data_backend.removeScriptFromGroup(lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[0], lcmpPacket[lcmp.LCMP_INDICES["Data"]].split(' ')[1]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["showScriptsOfGroup"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.showScriptsOfGroup(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["showGroupsOfScript"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): errorcode, data = data_backend.showGroupsOfScript(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) else: errorcode = error.ERRORS["NotAllowed"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["sendScript"]): # prüfe zuerst ob der Hostname in der Verbindungstabelle verfügbar ist connectionTable_sessionIDs = list() for i in connectionTable: connectionTable_sessionIDs.append(i[0]) hostname = connectionTable[connectionTable_sessionIDs.index(sessionID)][2] if hostname != "": # Es ist ein Hostname vorhanden, fahre fort scripts = data_backend.getScriptsForClient(hostname)[1] if lcmpPacket[lcmp.LCMP_INDICES["Data"]] in scripts: errorcode, scriptpath = data_backend.getScriptpath(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) if errorcode == 0: if data_backend.getScriptActive(lcmpPacket[lcmp.LCMP_INDICES["Data"]]): if core.doesFileExist(scriptpath): scriptFd = open(scriptpath) scriptcontent = "" for line in scriptFd: scriptcontent += line log.writeLogLV(config_backend.getLogfile(), "%s: %s: Sende Skript '%s' (%s) an Client\n" % (threading.currentThread().name, sessionName, lcmpPacket[lcmp.LCMP_INDICES["Data"]], scriptpath), log.LOGLEVEL["info"]) errorcode = 0 data = scriptcontent else: log.writeLogLV(config_backend.getLogfile(), "%s: %s: Das Skript wurde im Dateisystem nicht gefunden\n" % (threading.currentThread().name, sessionName), log.LOGLEVEL["warning"]) errorcode = error.ERRORS["ScriptDoesNotExistInFilesystem"] data = "" else: log.writeLogLV(config_backend.getLogfile(), "%s: %s: Das Skript wurde von einem Administrator deaktiviert\n" % (threading.currentThread().name, sessionName), log.LOGLEVEL["warning"]) errorcode = error.ERRORS["ScriptIsDeactivated"] data = "" else: log.writeLogLV(config_backend.getLogfile(), "%s: %s: Das Skript ist in der Datenbank des Servers nicht vorhanden\n" % (threading.currentThread().name, sessionName), log.LOGLEVEL["warning"]) errorcode = error.ERRORS["ScriptNotRegistered"] data = "" else: log.writeLogLV(config_backend.getLogfile(), "%s: %s: Das Skript ist diesem Client nicht zugewiesen\n" % (threading.currentThread().name, sessionName), log.LOGLEVEL["warning"]) errorcode = error.ERRORS["ScriptDoesntBelongToClient"] data = "" else: core.writeLogLV(config_backend.getLogfile(), "%s: %s: Dem Server ist der Hostname dieses Clients noch nicht bekannt" % (threading.currentThread().name, sessionName), log.LOGLEVEL["warning"]) errorcode = error.ERRORS["NoHostnameGiven"] data = "" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["getScriptsForClient"]): # Berechne Skripte für Client (Achtung: scriptsForClient ist eine Liste!! errorcode, scriptsForClient = data_backend.getScriptsForClient(lcmpPacket[lcmp.LCMP_INDICES["Data"]]) # Ist der Client überhaupt registriert? Data_Backend gibt Fehler wenn Client nicht vorhanden ist if errorcode == error.ERRORS["ClientNotRegistered"]: log.writeLogLV(config_backend.getLogfile(), "%s: %s: Client ist nicht im Data-Backend vorhanden\n" % (threading.currentThread().name, sessionName), log.LOGLEVEL["warning"]) errorcode = error.ERRORS["ClientNotRegistered"] # TODO: überflüssig? data = "[]" # sind überhaupt scripte für den client vorhanden? elif scriptsForClient == list(): # leere Liste log.writeLogLV(config_backend.getLogfile(), "%s: %s: Dem Client sind keine Skripte zugewiesen:\n" % (threading.currentThread().name, sessionName), log.LOGLEVEL["warning"]) errorcode = error.ERRORS["NoScriptsForClient"] data = "[]" # aktualisiere das Feld 'last-seen' beim Client data_backend.modifyClient(lcmpPacket[lcmp.LCMP_INDICES["Data"]], {'last-seen':datetime.now().strftime("%Y-%m-%d %H:%M:%S")}) else: log.writeLogLV(config_backend.getLogfile(), "%s: %s: Dem Client sind diese Skripte zugewiesen: %s\n" % (threading.currentThread().name, sessionName, scriptsForClient), log.LOGLEVEL["info"]) # Hostnamen in ConnectionTable eintragen connectionTable_sessionIDs = list() for i in connectionTable: connectionTable_sessionIDs.append(i[0]) connectionTable[connectionTable_sessionIDs.index(sessionID)][2] = lcmpPacket[lcmp.LCMP_INDICES["Data"]] # aktualisiere das Feld 'last-seen' beim Client data_backend.modifyClient(lcmpPacket[lcmp.LCMP_INDICES["Data"]], {'last-seen':datetime.now().strftime("%Y-%m-%d %H:%M:%S")}) data = str(scriptsForClient) elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["sendReturnCode"]): connectionTable_sessionIDs = list() for i in connectionTable: connectionTable_sessionIDs.append(i[0]) scriptname = lcmpPacket[lcmp.LCMP_INDICES["Data"]] rc = lcmpPacket[lcmp.LCMP_INDICES["Errorcode"]] clientname = connectionTable[connectionTable_sessionIDs.index(sessionID)][2] log.writeLogLV(config_backend.getLogfile(), "%s: %s: Client %s hat das Skript %s mit Code %s ausgeführt\n" % (threading.currentThread().name, sessionName, clientname, scriptname, rc), log.LOGLEVEL["info"]) errorcode = 0 data = "thx" elif (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["printSessions"]): # prüfe, ob die Session dazu berechtigt ist diesen OpType auszuführen if getSession(connectionTable, sessionID)[1] in config_backend.getAdminIPs(): print connectionTable errorcode = 0 data = "" else: errorcode = error.ERRORS["NotAllowed"] data = "" # Wenn OpType nicht bekannt ist else: errorcode = error.ERRORS["NotImplemented"] data = lcmp.OPTYPES_REVERSE[lcmpPacket[lcmp.LCMP_INDICES["OpType"]]] except error.DataBackendReturnTypeError as e: errorcode = error.ERRORS["DataBackendReturnTypeError"] log.writeLogLV(config_backend.getLogfile(), "%s: %s: "\ "%s hat einen falschen Rückgabetypen zurückgegeben "\ "(%s; erwartet wurde %s), "\ "eventuell liegt im Data-Backend-Modul eine fehlerhafte Implementierung von %s "\ "vor. Die aktuelle Operation wird abgebrochen!\n" % (threading.currentThread().name, sessionName, opType, e.getWrongType(), e.getRightType(), opType), log.LOGLEVEL["error"]) if config_backend.getDebug(): print traceback.print_exc() except error.DataBackendReturnValueError as e: errorcode = error.ERRORS["DataBackendReturnValueError"] log.writeLogLV(config_backend.getLogfile(), "%s: %s: "\ "'%s' hat einen falschen Rückgabewert zurückgegeben(%s). "\ "Eventuell liegt im Data-Backend-Modul eine fehlerhafte Implementierung von '%s' "\ "vor. Die aktuelle Operation wird abgebrochen!\n" % (threading.currentThread().name, sessionName, opType, e.getValue(), opType), log.LOGLEVEL["error"]) if config_backend.getDebug(): print traceback.print_exc() except error.DataBackendInternalError as e: errorcode = error.ERRORS["DataBackendInternalError"] log.writeLogLV(config_backend.getLogfile(), "%s: %s: "\ "%s wurde nicht ordnungsgemäß ausgeführt, "\ "die Fehlermeldung lautet: '%s'. " "Eventuell liegt im Data-Backend-Modul eine fehlerhafte Implementierung von %s "\ "vor. Die aktuelle Operation wird abgebrochen!\n" % (threading.currentThread().name, sessionName, opType, e.getValue(), opType), log.LOGLEVEL["error"]) if config_backend.getDebug(): print traceback.print_exc() except Exception as e: errorcode = error.ERRORS["InternalServerError"] log.writeLogLV(config_backend.getLogfile(), "%s: %s: "\ "Bei der Bearbeitung von '%s' ist ein Fehler aufgetreten (%s). "\ "Die aktuelle Operation wird abgebrochen!\n" % (threading.currentThread().name, sessionName, lcmp.OPTYPES_REVERSE[lcmpPacket[lcmp.LCMP_INDICES["OpType"]]], e.args), log.LOGLEVEL["error"]) if config_backend.getDebug(): print traceback.print_exc() # Statusmeldung ausgeben log.writeLogLV(config_backend.getLogfile(), "%s: %s: %s executed with Code %s [%s]\n" % (threading.currentThread().name, sessionName, lcmp.OPTYPES_REVERSE[lcmpPacket[lcmp.LCMP_INDICES["OpType"]]], errorcode, error.ERRORS_REVERSE[errorcode]), log.LOGLEVEL["debug"]) # sende Paket (immer von Type: Answer, OpType ist derselbe wie beim eigentlichen Request, errorcode und data ist variabel answer = lcmp.genLCMPPacket(int(sessionID), "Answer", lcmp.OPTYPES_REVERSE[lcmpPacket[lcmp.LCMP_INDICES["OpType"]]], errorcode, data) log.writeLogLV(config_backend.getLogfile(), "%s: %s: sending this lcmpPacket: %s\n" % (threading.currentThread().name, sessionName, answer), log.LOGLEVEL["debug"]) network.send(connection, answer) # Ende: RequestHandler()
def connectionHandler(socket, connectionTable): """ Beschreibung: wird direkt aufgerufen, nachdem eine Verbindung aus der Warteschlange geholt worden ist. connectionHandler() wertet das eingehende Paket in Bezug auf die Gültigkeit aus und reicht das Paket an LCMPRequestHandler() weiter. Parameter: (socket)connection: Enthält die Verbindungsinformationen zum Client. Rückgabewert: Keiner Exceptions: Wirft selbst keine """ try: # hole LCMP Paket data = network.recv(socket) # wandle Paket in Tuple um lcmpPacket = ast.literal_eval(data) log.writeLogLV(config_backend.getLogfile(), "%s: LCMP-Paket: %s\n" % (threading.currentThread().name, lcmpPacket), log.LOGLEVEL["debug"]) # Prüfe Paket auf Gültigkeit, wirft Exceptions bei Fehlern lcmp.isLCMPPacket(lcmpPacket) # Prüfen, ob der Client bereits eine offene Verbindung hat sessionID = "%s" % (lcmpPacket[lcmp.LCMP_INDICES["ID"]]) connectionTable_sessionIDs = list() for i in connectionTable: connectionTable_sessionIDs.append(i[0]) if sessionID in connectionTable_sessionIDs: log.writeLogLV(config_backend.getLogfile(), "%s: Session-ID OK (%s)\n" % (threading.currentThread().name, sessionID), log.LOGLEVEL["debug"]) # Aktualisiere SessionZeitstempel der Session connectionTable[connectionTable_sessionIDs.index(sessionID)][3] = datetime.now().strftime("%s") # Server bearbeit nur Requests, alles andere wird ignoriert if not lcmpPacket[lcmp.LCMP_INDICES["Type"]] == lcmp.TYPES["Request"]: log.writeLogLV(config_backend.getLogfile(), "%s: Server bearbeitet nur Requests. Anforderung war: %s...\n" % (threading.currentThread().name, lcmpPacket[1]), log.LOGLEVEL["warning"]) # Paket zum Auswerten an LCMPTypeHandler geben LCMPRequestHandler(socket, lcmpPacket, connectionTable, sessionID ) else: # Client ist noch nicht in Verbindungstabelle # wenn Client nocht nicht in der Verbindungstabelle ist, kann er # nur durch einen "openConnection"-Request hinzugefügt werden if (lcmpPacket[lcmp.LCMP_INDICES["OpType"]] == lcmp.OPTYPES["openConnection"]) and (lcmpPacket[lcmp.LCMP_INDICES["Type"]] == lcmp.TYPES["Request"]): # TODO: prüfe Version connectionTable.append([sessionID,socket.getpeername()[0],'', datetime.now().strftime("%s")]) log.writeLogLV(config_backend.getLogfile(), "%s: Session-ID (%s) wurde zur Session-Tabelle hinzugefügt\n" % (threading.currentThread().name, sessionID), log.LOGLEVEL["info"]) # Antworte Client, dass die Verbindung erfolgreich hergestellt ist und die Session ID eingetragen ist network.send(socket, lcmp.genLCMPPacket(sessionID, "Answer", "openConnection", 0, "")) else: network.send(socket, lcmp.genLCMPPacket(sessionID, "Answer", "openConnection", error.ERRORS["NoValidConnection"], "")) raise error.LCMPError("Client hat kein \"openConnection\" gesendet") log.writeLogLV(config_backend.getLogfile(), "%s: Verbindungstabelle: %s\n" % (threading.currentThread().name, connectionTable), log.LOGLEVEL["debug"]) except error.LCMPError as e: log.writeLogLV(config_backend.getLogfile(), "%s: Kein gültiges LCMP-Paket (%s)\n" % (threading.currentThread().name, e.value), log.LOGLEVEL["error"]) if config_backend.getDebug(): print traceback.print_exc() except Exception as e: log.writeLogLV(config_backend.getLogfile(), "Fehler in Abarbeitung des LCMP-Paketes:", e.args, log.LOGLEVEL["error"]) if config_backend.getDebug(): traceback.print_exc()
def msgHandler(self, clientsock, address): msg = network.receive(clientsock) if not msg: logger.warning('Did not receive message properly from {}'.format( address[0])) return if (DEST_GUID in msg and msg[DEST_GUID] != self.GUID): logger.warning( 'Not the intended recipient for message. From {}. Destination GUID: {}' .format(msg[SEND_IP], msg[DEST_GUID])) return # If received Join message (for bootstrap node) if msg[TYPE] == JOIN: if self.isBootstrap: logger.info('Received JOIN message from {}'.format( msg[SEND_IP])) joinAck = { TYPE: JOIN_ACK, SEND_IP: MY_IP, SEND_GUID: self.GUID, DEST_IP: msg[SEND_IP], DEST_GUID: network.generate_guid(), ROUTING: self.routTab.getTable() } network.send(joinAck[DEST_IP], **joinAck) self.routTab.addPeer(GUID=joinAck[DEST_GUID], IPAddr=joinAck[DEST_IP]) logger.info('Assigned GUID {} to {}'.format( joinAck[DEST_GUID], joinAck[DEST_IP])) else: logger.warning('Join message received! But not bootstrap node') # Reciving PING message if msg[TYPE] == PING: logger.info('Received PING message from {} ({})'.format( msg[SEND_IP], msg[SEND_GUID])) pongMsg = { TYPE: PONG, SEND_IP: MY_IP, SEND_GUID: self.GUID, DEST_IP: msg[SEND_IP], DEST_GUID: msg[SEND_GUID] } network.send(msg[SEND_IP], **pongMsg) self.routTab.handlePing(msg) # Receiving PONG message elif msg[TYPE] == PONG: logger.info('Received PONG message from {} ({})'.format( msg[SEND_IP], msg[SEND_GUID])) self.routTab.handlePong(msg) # Receiving QUERY message elif msg[TYPE] == QUERY: logger.info( 'Received QUERY message with ID {} from {} ({}). Source:- {} ({})' .format(msg[QUERY_ID], msg[SEND_IP], msg[SEND_GUID], msg[SOURCE_IP], msg[SOURCE_GUID])) # Check whether the query is repeated with self.repQuerLock: ok = msg[QUERY_ID] in self.repQuer # If not repeated search database and forward query if not ok: # Throw away older cached query and add the query to the cache with self.repQuerLock: while self.repQuerQueue.qsize() >= REP_QUERY_CACHE: self.repQuer.discard(self.repQuerQueue.get()) self.repQuer.add(msg[QUERY_ID]) self.repQuerQueue.put(msg[QUERY_ID]) self.save_repQuerQueue(msg[QUERY_ID]) logger.info('Adding Query {} to cache'.format(msg[QUERY_ID])) sender = msg[SEND_GUID] msg[SEND_IP] = MY_IP msg[SEND_GUID] = self.GUID # Search for results in database and send back if any results = self.fileSys.search(msg[SEARCH]) if bool(results): reponseMsg = { TYPE: QUERY_RESP, SEND_IP: MY_IP, SEND_GUID: self.GUID, DEST_IP: msg[SOURCE_IP], DEST_GUID: msg[SOURCE_GUID], QUERY_ID: msg[QUERY_ID], RESULTS: results } network.send(msg[SOURCE_IP], **reponseMsg) logger.info( 'Sending {} response(s) to Query {} to {} ({})'.format( len(results), msg[QUERY_ID], msg[SOURCE_IP], msg[SOURCE_GUID])) # Send queries to neighbours in Table for neighbours in self.routTab.neighbours(): msg[DEST_IP] = neighbours[0] msg[DEST_GUID] = neighbours[1] if msg[DEST_GUID] != sender: network.send(msg[DEST_IP], **msg) logger.info( 'Forwarding query to neighbour {} ({})'.format( msg[DEST_IP], msg[DEST_GUID])) else: logger.info('Repeated query {}'.format(msg[QUERY_ID])) # If received QUERY_RESP message elif msg[TYPE] == QUERY_RESP: logger.info( 'Received QUERY_RESP with {} result(s) for query {} from {} ({})' .format( len(msg[RESULTS]), msg[QUERY_ID], msg[SEND_IP], msg[SEND_GUID], )) with self.queryResLock: if msg[QUERY_ID] in self.queryRes: self.queryRes[msg[QUERY_ID]].append(msg) self.save_queryRes() # Save State return logger.warning('Query {} previously discarded'.format( msg[QUERY_ID])) # If received TRANSFER_REQ elif msg[TYPE] == TRANSFER_REQ: logger.info( 'Received TRANSFER_REQ from {} ({}) for File ID {} and Chunk {}' .format(msg[SEND_IP], msg[SEND_GUID], msg[FILE_ID], msg[CHUNK_NO])) fileTranMsg = { TYPE: TRANSFER_FILE, SEND_IP: MY_IP, SEND_GUID: self.GUID, DEST_IP: msg[SEND_IP], DEST_GUID: msg[SEND_GUID], REQUEST_ID: msg[REQUEST_ID], CHUNK_NO: msg[CHUNK_NO], CONTENT: self.fileSys.getContent(msg[FILE_ID], msg[CHUNK_NO]) } if fileTranMsg[CONTENT] is None: logger.warning('Content Unavailable for File ID {}'.format( msg[FILE_ID])) else: network.send(msg[SEND_IP], **fileTranMsg) # If received TRANSFER_FILE message elif msg[TYPE] == TRANSFER_FILE: logger.info( 'Received TRANSFER_FILE from {} ({}) for Request ID {} and Chunk {}' .format(msg[SEND_IP], msg[SEND_GUID], msg[REQUEST_ID], msg[CHUNK_NO])) with self.chunkLeftLock: # If the request is not yet done and the write to the file system is successful if msg[CHUNK_NO] in self.chunkLeft.get(msg[REQUEST_ID], (0, set()))[1] \ and self.fileSys.writeChunk(msg): # Remove the chunk no from the required chunk list self.chunkLeft[msg[REQUEST_ID]][1].remove(msg[CHUNK_NO]) # If all the chunks are done, inform filesys of the completion if not bool(self.chunkLeft[msg[REQUEST_ID]][1]): self.fileSys.done(msg[REQUEST_ID]) del self.chunkLeft[msg[REQUEST_ID]] del self.chunkLeftTransferReq[msg[REQUEST_ID]] self.save_pending() # Force Save State else: self.save_pending(False) # Save State
#A basic testing program for the leader library import sys, time import network import leader node = int(sys.argv[1]) network = leader.LeaderNetwork(network.Network('config/local.cfg', node)) def recv(msg, src): print(src, msg) pass network.registerReceive(recv) print('This is node ' + str(node)) while True: text = raw_input() if not text: break elif text == 'l': print('leader: ' + str(network.leader)) else: network.send(text, [1-network.node, -1])
def _sendDrop(self): network.send(DROP)
u.pos = (u.pos[0] + v[0], u.pos[1] + v[1]) d = pygame.display.set_mode((400, 400)) units = [] me = int(sys.argv[3]) for x in range(6): u = Unit() u.pos = (x * 20., x * 20.) u.dest = u.pos u.owner = x % 2 units.append(u) raw_input() while True: orders = get_my_orders(units) network.send(int(sys.argv[2]), repr(orders)) i = eval(network.get()) all_orders = [] all_orders.extend(orders) all_orders.extend(i) # magic logic(units, all_orders) d.fill((0, 0, 0)) for u in units: f = 1 if u in selection: f = 0 pygame.draw.circle(d, (255 * (u.owner != me), 255 * (u.owner == me), 0), u.pos, 16 if u.type == 1 else 4, f) pygame.display.update()
def update(): if helper.player.lives<=0: print "Out of lives!" sendLoseMsg() if tkMessageBox.askyesno("You lost!", "Play again?"): restartfn(False) network.doRestart=False # Schedule this function again root.after(10,update) else: exit() return if scoreboard.otherScoreLabelVar.get()!=network.newOtherScore: scoreboard.otherScoreLabelVar.set(network.newOtherScore) #if threading udp server got restart packet, restart if network.doRestart: restartfn(False) network.doRestart=False # Schedule this function again root.after(10,update) return if network.iWon: print 'you killed the opponent!' if tkMessageBox.askyesno("You won!", "Play again?"): restartfn(False) network.iWon=False # Schedule this function again root.after(10,update) else: exit() return if network.OppStatusBoxVar.get()!=network.newStatusString: network.OppStatusBoxVar.set(network.newStatusString) network.OppStatusBox.config(fg=network.newStatusColor) if network.isConnected and (time.time()-network.TimeSinceLastPacket)*1000>network.CONNECTIONTIMEOUT: print 'not connected any more' network.isConnected=False network.newStatusColor="red" network.newStatusString="Not Connected" network.OppStatusBoxVar.set("Not Connected") network.OppStatusBox.config(fg='red') #update speed deltaSpeed=[0,0] for key in helper.pressedKeys: if helper.pressedKeys[key]: newSpeed={"w":[0,-helper.CONTROLSENSITIVITY],"a":[-helper.CONTROLSENSITIVITY,0],"s":[0,helper.CONTROLSENSITIVITY],"d":[helper.CONTROLSENSITIVITY,0]}[key] deltaSpeed[0]+=newSpeed [0] deltaSpeed[1]+=newSpeed [1] helper.player.deltaX[0]+=deltaSpeed[0] helper.player.deltaX[1]+=deltaSpeed[1] for obj in objects: obj.update() bulletCoords=[] #make array of coords from bullets for count,bullet in enumerate(helper.bullets): # use the hex address of the bullet as uuid (id returns hex address) bulletCoords.append([id(helper.bullets[count])]+canvas.coords(bullet.id)) #make all coords ints for count,item in enumerate(bulletCoords): bulletCoords[count][1]=int(bulletCoords[count][1]) bulletCoords[count][2]=int(bulletCoords[count][2]) #send coords of everything #order of this is importiant network.addToSend([int(i) for i in canvas.coords(helper.player.id)]) network.addToSend(bulletCoords) network.addToSend(helper.bulletsToStopSending) network.addToSend(helper.player.lives) network.send() #loop through bullets opponent told you to delete for localBulletUuid in network.recievedBulletsToStopSending: for localbullet in helper.bullets: #if the recieved uuid matches a bullet if localBulletUuid==id(localbullet): #delete it from the screen canvas.delete(localbullet.id) #and the object lists helper.objects.remove(localbullet) helper.bullets.remove(localbullet) helper.bulletsToStopSending=[] #if there is no opponent, don't update Opponent and Opponent bullets if network.destIp: updateBullets() updateOpponent() # Schedule this function again root.after(10,update)
break else: if rekt == 1: guess = str(rWater) + ',' + str(cWater) print("CREDITS: Tofunmi") else: r, c = randomGuess() while dispBoard[r][c] != '.': r, c = randomGuess() guess = str(r) + ',' + str(c) hitList.remove(guess) ans = network.send(guess) if ans == 'win': break elif ans == 'wrong input': print("Your input was wrong") else: guessList = list(map(int, guess.split(','))) dispBoard[guessList[0]][guessList[1]] = ans time.sleep(2) if ans == 'win': guessList = list(map(int, guess.split(','))) dispBoard[guessList[0]][guessList[1]] = 'x' network.printBoard()
def _send(self, event, args=[]): log_event_send(event, args, label='RemoteInterface') network.send(self._sock, {'event': event, 'args': args})
def pvp(): global teams network = Network(players) if network.get_teamID() == "Server not available": return "Server not available" clock = pygame.time.Clock() key = 0 myID = int(network.get_teamID()) if myID is None: print("No server") screen.blit(pygame.Surface((info.width, info.height)), (info.left, info.top)) screen.blit(font20.render("Server unavailable", True, (180, 0, 0)), (info.left + 110, info.top + 140)) screen.blit( font20.render("Please select Single Player option", True, (180, 0, 0)), (info.left + 30, info.top + 190)) screen.blit( font20.render("Click mouse or press any key", True, (180, 0, 0)), (info.left + 125, info.top + 320)) screen.blit( font20.render("to return to the main menu", True, (180, 0, 0)), (info.left + 65, info.top + 370)) pygame.display.update(info) return teams = [Team(myID)] # this thread's team load_images() pygame.display.set_caption("PyForce - P" + str(myID)) # screen.blit(grid, gridrect) # screen.blit(pygame.Surface((490, 450)), (info.left, info.top)) # text = font20.render("These are your ships:", True, (0, 128, 0)) # screen.blit(text, (info.left + info.width // 2 - text.get_width() // 2, info.top + 50)) # screen.blit(shipImages[myID][0][0], (info.left + info.width // 2 - size // 2, info.top + 100, size, size)) # text = font20.render("Players in the game:", True, (180, 0, 0)) # screen.blit(text, (info.left + info.width // 2 - text.get_width() // 2, info.top + 190)) # pygame.display.update(info) # wait for opponent(s) users = 2 if players == 3 else players while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: if event.key == K_ESCAPE: return "Esc" data = network.send(teams[0].deets, True) if len(data) >= users: # enough players have joined break else: screen.blit(pygame.Surface((40, 40)), (info.left + info.width - 110, info.top + 5 + 60 * players + 150)) screen.blit(font40.render(str(len(data)), True, (180, 0, 0)), (info.left + info.width - 100, info.top + 5 + 60 * players + 150)) # text = font40.render(str(len(data)) + " of " + str(users), True, (180, 0, 0)) # screen.blit(pygame.Surface((info.width, 50)), (info.left, info.top + 230)) # screen.blit(text, (info.left + info.width // 2 - text.get_width() // 2, info.top + 230)) # # for d in data: # pygame.display.update(screen.blit(shipImages[imageMap[data[d].teamID]][0][0], # (info.left + info.width // 2 - 3 * size + 2 * size * data[d].teamID, # info.top + 300, size, size))) pygame.display.update( info) # (info.left, info.top + 100, 500, size)) clock.tick(10) screen.blit(font20.render("Setting up teams....", True, (180, 0, 0)), (info.left + 85, info.top + 290)) pygame.display.update(info) #pygame.display.update((info.left + 80, info.top + 240, 400, 200)) if players == 2: teams.append(Team(1 - myID, 2)) elif players == 3: teams.append(Team(1 - myID, 2)) # remote player # bot 1 (teams[2] automated by this thread) teams.append( Team(myID + 2, 0, gridleft + 14 * size, gridtop + 4 * size, 3, 7)) teams[2].ships[0].canTakeAHit = False teams[2].ships[0].rank = 0 network.send(teams[2].deets) teams[2].ships[0].target = teams[0].ships[0] # targeting this player # bot 2 (teams[3] automated by remote thread) teams.append( Team(3 - myID, 2, gridleft + 14 * size, gridtop + 4 * size, 3, 7)) teams[3].ships[0].canTakeAHit = False teams[3].ships[0].rank = 0 elif players == 4: teams.append(Team((myID + 1) % 4, 3)) teams.append(Team((myID + 2) % 4, 2)) teams.append(Team((myID + 3) % 4, 1)) users = 4 if players == 3 else players while True: deets = network.send(teams[0].deets) if len(deets) == users: break time.sleep(.1) # Assign enemy targets, get all deets for teamA in teams: teamA.deets = deets[teamA.teamID] for teamB in teams: if teamA.teamID != teamB.teamID: for ship in teamB.ships: teamA.enemy.append(ship) draw_screen() ship_hit = False # and we're off ready_set_go() # game loop while True: # move & send results teams[0].ships[0].move(key) # move self # teams[1].ships[0].move(0) # move remote ship (momentum) if players == 3: teams[2].ships[0].move(-6) # move assigned drone update(network) for team in teams: # check for collisions crash(team.ships[0]) if team.ships[0].hit: ship_hit = True team.ships[0].rect.left = -10000 - 1000 * team.teamID team.ships[0].update() team.lives -= 1 team.ships[0].inert = True if team.teamID == myID or (players == 3 and team.teamID == myID + 2): update(network) # send the bad news team.ships[0].hit = False team.ships[0].update() if ship_hit: # Make sure all threads are current t = time.time() while True: deets = update(network, True) for deet in deets: if not deets[deet].current and deets[deet].lives > 0: screen.blit(pygame.Surface((450, 200)), (info.left, info.top + 270)) text = font20.render("Player has been hit!", True, (180, 0, 0)) screen.blit(text, (info.left + info.width // 2 - text.get_width() // 2, info.top + 290)) text = font20.render( "Must update before continuing...", True, (180, 0, 0)) screen.blit(text, (info.left + info.width // 2 - text.get_width() // 2, info.top + 320)) pygame.display.update(info) if time.time() < t + 1: ship_hit = False break else: screen.blit(pygame.Surface((450, 200)), (info.left, info.top + 270)) text = font20.render("Player not responding", True, (180, 0, 0)) screen.blit( text, (info.left + info.width // 2 - text.get_width() // 2, info.top + 290)) text = font20.render("Sacrifices must be made...", True, (180, 0, 0)) screen.blit( text, (info.left + info.width // 2 - text.get_width() // 2, info.top + 320)) pygame.display.update(info) time.sleep(.5) ship_hit = False for team in teams: if team.teamID == deets[deet].teamID: deets[deet].lives -= 3 if deets[deet].lives <= 0: team.ships[0].inert = True deets[ deet].left = -10000 - 1000 * team.teamID deets[ deet].top = -10000 - 1000 * team.teamID network.send(deets[deet]) else: # All live teams are current break draw_screen() teams_left = 0 winner = None for team in teams: if team.lives > 0: teams_left += 1 winner = team # potential winner, anyway # if team's ship is inert, does it get revived? if team.ships[0].inert and not team.ships[0].shot: if team.teamID == myID or (players == 3 and team.teamID == myID + 2): # this thread team.ships[0].revive(5) else: team.ships[0].inert = False # ready_set_go() # Game over? if teams_left <= 1: # allow for explosion to complete update(network) delay = 10 # if len(booms) > 0 else 0 while delay: time.sleep(1.0 / 25) draw_screen() delay -= 1 return winner update(network) draw_screen() if key == K_SPACE: key = 0 # don't keep shooting # check for quit event, log keydown for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # time.sleep(10) if event.type == pygame.KEYDOWN: key = event.key draw_screen() clock.tick(25)
def _sendMove(self, direction): network.send(MOVE + direction)
#m *= 4 #0 pixels per second u.pos = (u.pos[0]+v[0],u.pos[1] + v[1]) d = pygame.display.set_mode((400,400)) units = [] me = int(sys.argv[3]) for x in range(6): u = Unit() u.pos = (x*20.,x*20.) u.dest = u.pos u.owner = x%2 units.append(u) raw_input() while True: orders = get_my_orders(units) network.send(int(sys.argv[2]),repr(orders)) i = eval(network.get()) all_orders = [] all_orders.extend(orders) all_orders.extend(i) # magic logic(units, all_orders) d.fill((0,0,0)) for u in units: f = 1 if u in selection: f = 0 pygame.draw.circle(d, (255*(u.owner!=me),255*(u.owner==me),0), u.pos, 16 if u.type==1 else 4,f) pygame.display.update() #print "cycle" #pygame.time.wait(10)
################################################################################ # Your turn to hit # You will get back either ' ', 'x', 'M' # # need to make your own logic to come up with a string "r,c" to send to opponent ################################################################################ b = 'minus' c = 'subtract' if hint > 0 and hints1loop > -1 and firstHit == False: guess = hintguess( hintCoordinates[0][0], hintCoordinates[0][1]) #will return a guess to be used ans = network.send(guess) time.sleep(0.5) win = b XMorSpace = ans elif firstHit == True and secondHit == False and hints2loop > -1: guess = hint2guess(firstHitCoordinates[0][0], firstHitCoordinates[0][1], hints2loop) ans = network.send(guess) #time.sleep(0.5) win = c XMorSpace = ans
def send_worker(file_name, destination, size): with open(input_list[1], "rb") as binary_file: network.send(binary_file, destination, port, size, file_name)
def main(): # PORT = int(sys.argv[1]) if len(sys.argv)>1 else 5000 MY_ADDR = (sys.argv[1], int(sys.argv[2])) MAP1_ADDR = (sys.argv[3], int(sys.argv[4])) MAP2_ADDR = (sys.argv[5], int(sys.argv[6])) RED_ADDR = (sys.argv[7], int(sys.argv[8])) PAXOS_ADDR = (sys.argv[9], int(sys.argv[10])) # PORT, PORT_M1, PORT_M2, PORT_RED, PORT_PAXOS = [int(p) for p in sys.argv[1:]] print("Hi from CLI on port", MY_ADDR) prev = None # previous cmd # When a msg comes back to me from the mapper, reducer, or PRM, # I'm expecting it to reply with a certain string. def replyfn(b): if b == b'Done!': debug('He seems to be done!') elif b == b'Enqueued msg!': debug("He says he'll do it. Not waiting for him!") elif b == b'Killed me.': debug('He said I killed him.') else: debug( "Hm, he replied with something I didn't expect: {}".format(b)) while True: cmdline = input('Cmd: ') if len(cmdline.strip()) == 0 and prev is not None: cmdline = prev # blank line repeats prev cmd tokens = cmdline.split() cmd = tokens[0] d = {'cmd': cmd} if cmd == 'help' or cmd == 'h': print(""" • map filename • reduce filename1 filename2 ... • replicate filename • stop • resume • total pos1 pos2 ... • print • merge pos1 pos2 • cat filename1 filename2 ... """) continue elif cmd == 'map': '''splits the file based on its size into 2 equal parts. The split has to cut the file in a space character, not in the middle of a word. Then it maps each half to a mapper using message passing.''' if len(tokens) < 2: print('USAGE: map filename') continue f = tokens[1] s = open(f, 'r').read() n = len(s) i = n // 2 while i < n: # break between words if s[i] == ' ': break i += 1 d1 = {'filename': f, 'offset': 0, 'size': i} d2 = {'filename': f, 'offset': i, 'size': n - i} network.send(MAP1_ADDR, d1) network.send(MAP2_ADDR, d2) elif cmd == 'reduce': '''sends a message (using sockets) to the reducer with the provided filenames. The reducer has to reduce the intermediate files to a final reduced file.''' if len(tokens) < 2: print('USAGE: reduce f_I_1 f_I_2') continue fs = tokens[1:] d = {'filenames': fs} network.send(RED_ADDR, d) elif cmd == 'replicate': '''sends a message to the PRM to replicate the file with other computing nodes. Notice that the PRM owns the log with all its log objects.''' if len(tokens) < 2: print('USAGE: replicate f_reduced') continue f = tokens[1] d.update({'filename': f}) network.send(PAXOS_ADDR, d) elif cmd == 'stop': '''moves the PRM to the stopped state. When the PRM in the stopped state, it does not handle any local replicate commands. In addition, it drops any log object replicating messages sent by other PRMs in other nodes. This is used to emulate failures and how Paxos can still achieve progress in the presence of N/2 − 1 failures.''' network.send(PAXOS_ADDR, d) elif cmd == 'resume': '''resumes the PRM back to the active state. A PRM in the active state should actively handle local replicate commands as well as log object repli- cating messages received by other PRMs.''' network.send(PAXOS_ADDR, d) # DATA QUERY CALLS #The CLI sends a query to the PRM, and the PRM prints # the answers to these queries in its stdout. There is no # need to pass the results back to the CLI. The supported data query calls are: elif cmd == 'total': '''sums up the counts of all the word in all the log positions pos1 pos2,...''' logpositions = [int(i) for i in tokens[1:]] if len(logpositions) == 0: print('USAGE: total logpos1 logpos2 ...') continue d.update({'logpositions': logpositions}) network.send(PAXOS_ADDR, d) elif cmd == 'print': '''prints the filenames of all the log objects.''' network.send(PAXOS_ADDR, d) elif cmd == 'merge': '''apply the reduce function in log objects in positions pos1 pos2. In other words, it adds up the occurrence of words in log objects in positions pos1 and pos2 and prints each word with its corresponding count.''' logpositions = [int(i) for i in tokens[1:]] if len(logpositions) == 0: print('USAGE: merge logpos1 logpos2 ...') continue d.update({'logpositions': logpositions}) network.send(PAXOS_ADDR, d) # Justin-specific commands elif cmd == 'cat': if len(tokens) < 2: print('USAGE: cat filename1 filename2 ...') continue fs = tokens[1:] for f in fs: print('File "{}":'.format(f)) print(open(f, 'r').read()) print('') elif cmd == 'kill' or cmd == 'k': [ network.send(p, d) for p in [MAP1_ADDR, MAP2_ADDR, RED_ADDR, PAXOS_ADDR] ] break elif cmd == 'q': break else: print('Not familiar with the command "{}", sry lol'.format(cmd)) prev = cmdline print('Bye bye!')