def find_predecessor(self, id): """Find the predecessor of an id. Used to refresh other nodes finger tables/successors""" if id == self.identifier: return self.predecessor pred = self while id not in Interval( pred.identifier, protocol.Client(self).connect(pred).successor.identifier).form( "(]"): pred = protocol.Client(self).connect(pred).closest_preceding(id) return pred
def run(self): """ Main worker thread for B3. """ self.bot('Start listening ...') self.screen.write( 'Startup complete : B3 is running! Let\'s get to work!\n\n') self.screen.write( '(If you run into problems, check %s in the B3 root directory for ' 'detailed log info)\n' % self.config.getpath('b3', 'logfile')) self.updateDocumentation() while self.working: # While we are working, connect # to the Homefront server if self._paused: if self._pauseNotice is False: self.bot( 'PAUSED - not parsing any lines: B3 will be out of sync' ) self._pauseNotice = True else: if self._serverConnection is None: self.bot('Connecting to Homefront server ...') self._serverConnection = protocol.Client( self, self._rconIp, self._rconPort, self._rconPassword, keepalive=True) # hook on handle_close to protocol.Client self._original_connection_handle_close_method = self._serverConnection.handle_close self._serverConnection.handle_close = self._handle_connection_close # listen for incoming HF packets self._serverConnection.add_listener(self.routePacket) # setup Rcon self.output.set_homefront_client(self._serverConnection) self._nbConsecutiveConnFailure = 0 while self.working and not self._paused \ and (self._serverConnection.connected or not self._serverConnection.authed): #self.verbose2("\t%s" % (time.time() - self._serverConnection.last_pong_time)) if time.time() - self._serverConnection.last_pong_time > 6 \ and self._serverConnection.last_ping_time < self._serverConnection.last_pong_time: self._serverConnection.ping() asyncore.loop(timeout=3, use_poll=True, count=1) self.bot('Stop listening...') with self.exiting: self._serverConnection.close() if self.exitcode: sys.exit(self.exitcode)
def init_finger_table(self, other): print 'node said succ is %s' % other self.successor = other self.predecessor = protocol.Client(self).connect( self.successor).predecessor protocol.Client(self).connect(self.successor).notify_predecessor(self) protocol.Client(self).connect(self.predecessor).notify_successor(self) for i in range(1, self.m): ## Extend range for the known successor if self.finger[i + 1].start in Interval( self.identifier, self.finger[i].node.identifier).form('[)'): self.finger[i + 1].node = self.finger[i].node else: ## Or find the next node self.finger[i + 1].node = protocol.Client(self).connect( other).find_successor(self.finger[i + 1].start)
def __init__(self, noshell=1): global flist, root root = Tk(className="Idle") fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) # the following causes lockups and silent failures when debugging # changes to EditorWindow.__init__ ; the console works fine for idle # debugging in any case, so disable this unnescesary stuff. #dbg=OnDemandOutputWindow(flist) #dbg.set_title('IDLE Debugging Messages') #sys.stdout = PseudoFile(dbg,['stdout']) #sys.stderr = PseudoFile(dbg,['stderr']) try: self.server = protocol.Server(connection_hook=self.address_ok) protocol.publish('IDLE', self.connect) self.main(sys.argv[1:], noshell) return except protocol.connectionLost: try: client = protocol.Client() IDLE = client.getobject('IDLE') if IDLE: try: IDLE.remote(sys.argv[1:]) except usageError, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) return except protocol.connectionLost: pass #maybe the following should be handled by a tkmessagebox for #users who don't start idle from a console?? print """\ IDLE cannot run. IDLE needs to use a specific TCP/IP port (7454) in order to execute and debug programs. IDLE is unable to bind to this port, and so cannot start. Here are some possible causes of this problem: 1. TCP/IP networking is not installed or not working on this computer 2. Another program is running that uses this port 3. Another copy of IDLE stopped responding but is still bound to the port 4. Personal firewall software is preventing IDLE from using this port IDLE makes and accepts connections only with this computer, and does not communicate over the internet in any way. It's use of port 7454 should not be a security risk on a single-user machine. """ dbg.owin.gotoline(1) dbg.owin.remove_selection() root.mainloop() # wait for user to read message
def notify_successor(self, other): if other.identifier in Interval(self.identifier, self.successor.identifier): self.successor = other self.app_instance.on_new_node(other) else: try: protocol.Client(self).connect(self.successor).hello(self) except protocol.exception: self.successor = other
def find_successor(self, id): """Find this id successor - using our finger table or fwding the question on the circle""" if self.successor == self: return self try: pred = self.find_predecessor(id) return protocol.Client(self).connect(pred).successor except protocol.exception, e: pass
def update_finger_table(self, other): """If this node is better than some in our finger tables, update""" touched = False for i in range(2, self.m): if other.identifier in Interval( self.identifier, self.finger[i].node.identifier).form('[)'): self.finger[i].node = other touched = True if touched: protocol.Client(self).connect( self.predecessor).update_finger_table(other)
def lost(self, other): self.app_instance.on_lost_node(other) if other.identifier == self.successor.identifier: self.successor = self.next_successor protocol.Client(self).connect( self.successor).notify_predecessor(self) for i in range(1, self.m): if self.finger[i + 1].node.identifier == other.identifier: self.finger[i + 1].node = self.finger[i].node if self.predecessor.identifier == other.identifier: self.predecessor = self.find_predecessor(self.identifier)
def broadcast(self, stop_at, data): self.app_instance.on_broadcast(data) for i in range(1, self.m): # skip redundant finger if self.finger[i].node.identifier != \ self.finger[i+1].node.identifier and self.finger[i].node != self: if self.finger[i].node.identifier in Interval( self.identifier, stop_at).form('()'): n = self.finger[i].node if self.finger[i + 1].node.identifier in Interval( self.identifier, stop_at).form('()'): new_stop_at = self.finger[i + 1].node.identifier else: new_stop_at = stop_at protocol.Client(self).connect(n).broadcast( new_stop_at, data) if self.finger[self.m].node.identifier in Interval( self.identifier, stop_at).form('()'): protocol.Client(self).connect(self.finger[self.m].node).broadcast( self.identifier, data) return True
def check_successor(self): try: i = protocol.Client(self).connect(self.successor).predecessor if i.identifier in Interval(self.identifier, self.successor.identifier).form('()'): self.successor = i protocol.Client(self).connect( self.successor).notify_predecessor(self) elif self.identifier in Interval( i.identifier, self.successor.identifier).form('()'): protocol.Client(self).connect( self.successor).notify_predecessor(self) except protocol.exception: try: protocol.Client(self).connect(self.next_successor).hello(self) except protocol.exception: print 'No backup yet, fixme/waiting' return if self.successor.identifier == self.predecessor.identifier: # special case for two-nodes network assert (self.next_successor.identifier == self.identifier) self.predecessor = self self.lost(self.successor)
def run(self): """Main worker thread for B3""" self.bot('Start listening ...') self.screen.write( 'Startup Complete : B3 is running! Let\'s get to work!\n\n') self.screen.write( '(If you run into problems, check %s for detailed log info)\n' % self.config.getpath('b3', 'logfile')) #self.screen.flush() self.updateDocumentation() while self.working: """ While we are working, connect to the Homefront server """ if self._paused: if self._pauseNotice == False: self.bot( 'PAUSED - Not parsing any lines, B3 will be out of sync.' ) self._pauseNotice = True else: if self._serverConnection is None: self.bot('Connecting to Homefront server ...') self._serverConnection = protocol.Client( self, self._rconIp, self._rconPort, self._rconPassword, keepalive=True) self._serverConnection.add_listener(self.routePacket) self.output.set_homefront_client(self._serverConnection) self._nbConsecutiveConnFailure = 0 while self.working and not self._paused \ and (self._serverConnection.connected or not self._serverConnection.authed): #self.verbose2("\t%s" % (time.time() - self._serverConnection.last_pong_time)) if time.time() - self._serverConnection.last_pong_time > 6 \ and self._serverConnection.last_ping_time < self._serverConnection.last_pong_time: self._serverConnection.ping() asyncore.loop(timeout=3, use_poll=True, count=1) self.bot('Stop listening.') if self.exiting.acquire(1): self._serverConnection.close() if self.exitcode: sys.exit(self.exitcode)
def move_keys(self): """Send keys I have where my predecessor is a successor of the key""" if self.predecessor.identifier == self.identifier: # we did not rejoin, better skip this part print 'I am my own predecessor now' return for k in self.app_instance.keys(): if ChordHash(k, self.m).value in Interval( self.identifier, self.predecessor.identifier).form('(]'): v = self.app_instance.on_get(k) print '%s xfering key %s to %s' % ( self, ChordHash(k, self.m).value, self.predecessor, ) protocol.Client(self).connect(self.predecessor).put(k, v) self.app_instance.on_delete(k)
def join(self, url): """Join other node, and constructs our finger table with other help""" if self.successor != self: raise Exception('Already joined the network') try: other = protocol.Client(self).connect_url(url).joined(self) if other: self.init_finger_table(other) else: return False except protocol.exception: return False t = threading.Thread(None, self.run_stabilization) t.daemon = True t.start() return True
def server_main(args): '''Runs the Sudoku server @param args: ArgParse collected arguments ''' # Starting server LOG.info('%s version %s started ...' % (___NAME, ___VER)) # Declaring TCP socket __server_socket = socket(AF_INET, SOCK_STREAM) LOG.debug('Server socket created, descriptor %d' % __server_socket.fileno()) # Bind TCP Socket print(args) sock_address = ("127.0.0.1", args.port) try: __server_socket.bind(sock_address) except soc_error as e: LOG.error('Can\'t start Sudoku server, error : %s' % str(e)) exit(1) LOG.debug('Server socket bound on %s:%d' % __server_socket.getsockname()) # Put TCP socket into listening state __server_socket.listen(7000) LOG.info('Accepting requests on TCP %s:%d' % __server_socket.getsockname()) # Declare client socket, set to None client_socket = None # Declare list of all active game sessions sessions = {} # Declare list for all names in active use names = [] # Declare list of Client objects users = [] # Declare list of all possible sudoku boards fn = 'application/server/sudoku_db' boards = read_games_from_file(fn) # Declare Pyro4 daemon in separate thread daemon = URIhandler() daemon.start() # Start new thread to advertise server broadcaster = BroadcastHandler(sock_address) broadcaster.start() # Serve forever while 1: try: LOG.debug('Awaiting new client connections ...') # Accept client's connection store the client socket into # client_socket and client address into source client_socket, source = __server_socket.accept( ) #Change as required by service discovery LOG.debug('New client connected from %s:%d' % source) p = protocol.Client(sessions, names, boards, users) p_uri = daemon.register(p) LOG.debug('New URI: %s' % str(p_uri)) users.append(p) client_socket.sendall( str(p_uri)) #Change as required by service discovery client_socket = None except KeyboardInterrupt as e: LOG.debug('Ctrl+C issued ...') LOG.info('Terminating server ...') __server_socket.close() break # If we were interrupted, make sure client socket is also closed if client_socket != None: protocol.disconnect_client(client_socket) # Close server socket __server_socket.close() LOG.debug('Server socket closed') exit(0)
class FrontlineParser(b3.parser.Parser): """ The Frontline B3 parser class. """ gameName = "frontline" privateMsg = True OutputClass = rcon.Rcon PunkBuster = None prefix = '%s: ' _async_responses = {} # dict to hold rcon asynchronous responses _serverConnection = None _original_connection_handle_close_method = None _rconUser = None # frontline engine does not support color code, so we # need this property in order to get stripColors working _reColor = re.compile(r'(\^[0-9])') _connectionTimeout = 30 _playerlistInterval = 3 _nbConsecutiveConnFailure = 0 _server_banlist = {} _line_length = 200 _line_color_prefix = '' #################################################################################################################### # # # PARSER INITIALIZATION # # # #################################################################################################################### def startup(self): """ Called after the parser is created before run(). """ self.debug("startup()") # create the server client self.clients.newClient('Server', guid='Server', name='Server', hide=True, pbid='Server', team=b3.TEAM_UNKNOWN) self.cron.add( b3.cron.CronTab(self.retrievePlayerList, second='*/%s' % self._playerlistInterval)) def run(self): """ Main worker thread for B3. """ try: self._rconUser = self.config.get("server", "rcon_user") except NoOptionError, err: self.error("Cannot find rcon_user in B3 main config file. %s", err) raise SystemExit("incomplete config") self.screen.write( 'Startup complete : B3 is running! Let\'s get to work!\n\n') self.screen.write( '(If you run into problems, check %s in the B3 root directory for ' 'detailed log info)\n' % self.config.getpath('b3', 'logfile')) self.updateDocumentation() self.bot('Start listening...') while self.working: # While we are working, connect to the Frontline server if self._paused: if not self._pauseNotice: self.bot( 'PAUSED - not parsing any lines: B3 will be out of sync' ) self._pauseNotice = True else: if self._serverConnection is None: self.bot( 'connecting to Frontline server %s:%s with user %s...', self._rconIp, self._rconPort, self._rconUser) self._serverConnection = protocol.Client( self, self._rconIp, self._rconPort, self._rconUser, self._rconPassword, keepalive=True) # hook on handle_close to protocol.Client self._original_connection_handle_close_method = self._serverConnection.handle_close self._serverConnection.handle_close = self._handle_connection_close # listen for incoming HF packets self._serverConnection.add_listener(self.routePacket) # setup Rcon self.output.set_frontline_client(self._serverConnection) self._nbConsecutiveConnFailure = 0 while self.working and not self._paused \ and (self._serverConnection.connected or not self._serverConnection.authed): asyncore.loop(timeout=3, use_poll=True, count=1) self.bot('Stop listening...') with self.exiting: self._serverConnection.close() if self.exitcode: sys.exit(self.exitcode)
import socket import protocol HEAD = protocol.HEAD TAIL = protocol.TAIL DISCONNECT_MESSAGE = '!DISCONNECT' client = protocol.Client() client.connect() try: PKT_BUFFER = int(input("Enter packet buffer size: ")) except: PKT_BUFFER = 10 first_acknowledgement = str(PKT_BUFFER) client.send(first_acknowledgement) packet = protocol.Packet(PKT_BUFFER) message = "Hello, I am a client. I am sending this message. Happy coding!" packet.append_msg(message) active = True while active: # input() buffer = protocol.from_network_layer(packet) if buffer == None: print(f"[NOTE] No more message left.") more_msg = input( "Enter new message to send OR press ENTER to DISCONNECT: ") if more_msg:
def successor(self, value): self.finger[1].node = value if value != self: self.next_successor = protocol.Client(self).connect( value).successor
class FrontlineParser(b3.parser.Parser): ''' The Frontline B3 parser class ''' gameName = "frontline" privateMsg = True OutputClass = rcon.Rcon PunkBuster = None _serverConnection = None _rconUser = None # frontline engine does not support color code, so we need this property # in order to get stripColors working _reColor = re.compile(r'(\^[0-9])') _connectionTimeout = 30 _playerlistInterval = 3 _server_banlist = {} _settings = {'line_length': 200, 'min_wrap_length': 200} # dict to hold rcon asynchronous responses _async_responses = {} prefix = '%s: ' def startup(self): self.debug("startup()") for regexp, func in _gameevents_mapping: self.debug("%s maps to %s", regexp, func) # create the 'Server' client #self.clients.newClient('Server', guid='Server', name='Server', hide=True, pbid='Server', team=b3.TEAM_UNKNOWN) # start crontab to trigger playerlist events self.cron + b3.cron.CronTab(self.retrievePlayerList, second='*/%s' % self._playerlistInterval) #self.queryServerInfo() def routePacket(self, packet): if packet is None: self.warning('cannot route empty packet') else: if not packet.startswith('PlayerList:'): self.console("%s" % packet.strip()) hfunc, param_dict = getGameEventHandler(packet) if hfunc: event = hfunc(self, **param_dict) if event: self.queueEvent(event) else: self.warning('TODO handle packet : %s' % packet) self.queueEvent(self.getEvent('EVT_UNKNOWN', packet)) def run(self): """Main worker thread for B3""" try: self._rconUser = self.config.get("server", "rcon_user") except NoOptionError, err: self.error("cannot find rcon_user in B3 main config file. %s", err) raise SystemExit("incomplete config") self.screen.write('Startup Complete : B3 is running! Let\'s get to work!\n\n') self.screen.write('(If you run into problems, check %s for detailed log info)\n' % self.config.getpath('b3', 'logfile')) #self.screen.flush() self.updateDocumentation() self.bot('Start listening ...') while self.working: """ While we are working, connect to the Frontline server """ if self._paused: if self._pauseNotice == False: self.bot('PAUSED - Not parsing any lines, B3 will be out of sync.') self._pauseNotice = True else: if self._serverConnection is None: self.bot('Connecting to Frontline server %s:%s with user %s ...', self._rconIp, self._rconPort, self._rconUser) self._serverConnection = protocol.Client(self, self._rconIp, self._rconPort, self._rconUser, self._rconPassword, keepalive=True) # hook on handle_close to protocol.Client self._original_connection_handle_close_method = self._serverConnection.handle_close self._serverConnection.handle_close = self._handle_connection_close # listen for incoming HF packets self._serverConnection.add_listener(self.routePacket) # setup Rcon self.output.set_frontline_client(self._serverConnection) self._nbConsecutiveConnFailure = 0 while self.working and not self._paused \ and (self._serverConnection.connected or not self._serverConnection.authed): asyncore.loop(timeout=3, use_poll=True, count=1) self.bot('Stop listening.') with self.exiting: self._serverConnection.close() if self.exitcode: sys.exit(self.exitcode)
def update_others(self): """Notify nodes that we might be interesting for in terms of finger table""" for i in range(self.m, 0, -1): node = self.find_predecessor((self.identifier - 2**i) % 2**self.m) protocol.Client(self).connect(node).update_finger_table(self)