def write(self, data): """ Queues a write on the socket. @param data: object to JSON-serialize and send @type data: JSON-serializable object """ try: s_data = json.dumps(data) except TypeError: # cannot serialize raise InvalidOperation, 'Cannot serialize this object' Socket.write(self, struct.pack('>L', len(s_data)) + s_data)
def run(self): sleep(0.2) sck = Socket(socket(AF_INET, SOCK_STREAM)) sck.connect(('127.0.0.1', TESTING_PORT)) sck.write('Hello World') self.utc.assertEquals(sck.read(1), '1') self.utc.assertEquals(sck.read(1), '2') sck.close()
def test_two_lshardmgrs_single_request(self): """Tests how to server allocates if there's a request and admittant lshardmgr connected, and a failing lshardmgr connected. This test is not deterministic, if it fails try again. """ self.LShardmgr('admit', fail=False).start() self.LShardmgr('faily', fail=True).start() sleep(0.01) for x in xrange(0, 20): s = socket(AF_INET, SOCK_STREAM) s.connect(('127.0.0.1', TESTING_PORT)) s = JSONSocket(Socket(s)) s.write({ 'request': 'allocate-shard', 'gugid': 'trololo', 'bpf_chunk': { 'map_name': 'Indianapolis', 'players': [] } }) rsp = s.read() self.assertEquals(rsp['response'], 'allocated') self.assertEquals(rsp['gugid'], 'trololo') s.close()
def run(self): s = socket(AF_INET, SOCK_STREAM) s.connect(('127.0.0.1', TESTING_PORT)) s = JSONSocket(Socket(s)) s.write(({ 'request': 'first-login', 'id_name': self.idname, 'shards': 1 })) s.settimeout(20) while not self._terminating: try: rd = s.read() except DataNotAvailable: s.write({'shards': 1}) continue except ChannelClosed: return # allocation request readed if self.fail: s.write({'response': 'recess', 'gugid': rd['gugid']}) else: s.write({ 'response': 'allocated', 'gugid': rd['gugid'], 'tcp-interface': 'a', 'udp-interface': 'b', 'tcp-port': 10, 'udp-port': 20 })
def run(self): sck = socket(AF_INET, SOCK_STREAM) sck.connect(('127.0.0.1', TESTING_PORT)) sck = Socket(sck) sck.settimeout(5) self.utc.assertEquals(sck.read(2), 'Ye') self.utc.assertEquals(sck.read(1), 's') sck.write('Hello World') sck.close()
def test_nonblocking_connect(self): class MySelectHandlingLayer(SelectHandlingLayer): def __init__(self, utc): SelectHandlingLayer.__init__(self) self.utc = utc self.ok = False def on_connected(self, channel): # at this point data should have been flushed self.ok = True mshl = MySelectHandlingLayer(self) sck = Socket(socket(AF_INET, SOCK_STREAM)) mshl.register_channel(sck) sck.connect(('www.yahoo.com', 80)) # that was just nonblocking a = time() while (time() - a < 30) and (not mshl.ok): mshl.select() self.assertEquals(mshl.ok, True)
def read(self, peek=False): """ Attempts to read a JSON frame. Throws DataNotAvailable on no data. If blocking and null-frame received will return None """ if self.blocking: try: frame = self.frames.popleft() return frame except IndexError: pass # we simply need to catch a frame # so no cached frames for us. Let's fetch one directly.. b_fln = Socket.read(self, 4) i_fln, = struct.unpack('>L', str(b_fln)) if i_fln == 0: return None pdata = Socket.read(self, i_fln) try: self.frames.append(json.loads(str(pdata))) except ValueError: # invalid JSON self.close() raise FatalException, 'Invalid JSON received' return self.frames.popleft() else: try: frame = self.frames.popleft() except IndexError: raise DataNotAvailable if peek: self.frames.appendleft(frame) return frame
def read(self, peek=False): """ Attempts to read a JSON frame. Throws DataNotAvailable on no data. If blocking and null-frame received will return None """ if self.blocking: try: frame = self.frames.popleft() return frame except IndexError: pass # we simply need to catch a new frame # so no cached frames for us. Let's fetch one directly.. b_fln = Socket.read(self, 4) i_fln, = struct.unpack('>L', str(b_fln)) if i_fln == 0: return None pdata = Socket.read(self, i_fln) try: self.frames.append(json.loads(str(pdata))) except ValueError: # invalid JSON self.close() raise FatalException, 'Invalid JSON received' return self.frames.popleft() else: try: frame = self.frames.popleft() except IndexError: raise DataNotAvailable if peek: self.frames.appendleft(frame) return frame
def run(self): """@param utc: unit test class""" sleep(0.1) sck = socket(AF_INET, SOCK_STREAM) sck.connect(('127.0.0.1', TESTING_PORT)) sck = Socket(sck) sck.write('Hello World') self.pkdata = sck.read(3, less=False, peek=True) self.data = sck.read(3) self.utc.assertRaises(ChannelClosed, sck.read, 1) sck.close()
def test_no_lshardmgrs_single_request(self): """Tests how to server fails if there's a request and NO lshardmgrs connected""" s = socket(AF_INET, SOCK_STREAM) s.connect(('127.0.0.1', TESTING_PORT)) s = JSONSocket(Socket(s)) s.write({ 'request': 'allocate-shard', 'gugid': 'trololo', 'bpf_chunk': { 'map_name': 'Indianapolis', 'players': [] } }) rsp = s.read() self.assertEquals(rsp['response'], 'recess') self.assertEquals(rsp['gugid'], 'trololo')
def run(self): """@param utc: unit test class""" sleep(0.1) sck = socket(AF_INET, SOCK_STREAM) sck.connect(('127.0.0.1', TESTING_PORT)) sck = Socket(sck) self.utc.assertEquals(sck.blocking, True) self.utc.assertEquals(sck.read(1), 'L') pkdata = sck.read(100, less=True, peek=True) data = sck.read(100, less=True) self.utc.assertEquals(pkdata, 'ong string? Not enough.') self.utc.assertEquals(data, 'ong string? Not enough.') self.utc.assertRaises(ChannelClosed, sck.read, 1) sck.close()
def test_single_lshardmgrs_single_request(self): """Tests how to server allocates if there's a request and admittant lshardmgr connected""" self.LShardmgr('admit', fail=False).start() sleep(0.01) s = socket(AF_INET, SOCK_STREAM) s.connect(('127.0.0.1', TESTING_PORT)) s = JSONSocket(Socket(s)) s.write({ 'request': 'allocate-shard', 'gugid': 'trololo', 'bpf_chunk': { 'map_name': 'Indianapolis', 'players': [] } }) rsp = s.read() self.assertEquals(rsp['response'], 'allocated') self.assertEquals(rsp['gugid'], 'trololo')
def on_readable(self): """Read JSON frames Empty frames are None. """ Socket.on_readable(self) self.last_received_data = time() while True: try: # peek the frame size (keep in mind we need to remove # if from the buffer later, it's only a peek!) b_fln = Socket.read(self, 4, peek=True) # this throws DataNotAvailable - we'll catch it later # this throws FatalException - let it propagate i_fln, = struct.unpack('>L', str(b_fln)) if i_fln == 0: # special case - frame size is zero. Consume it # and attempt another frame Socket.read(self, 4) continue # Now read the frame (alongside with it's size) pdata = Socket.read(self, i_fln+4) # this throws DataNotAvailable - we'll catch it later # this throws FatalException - let it propagate try: self.frames.append(json.loads(str(pdata[4:]))) except ValueError: # invalid JSON self.close() raise FatalException, 'Invalid JSON received' except DataNotAvailable: # all frames readed, good-bye break
def __init__(self, socket): """@type socket: L{satella.channels.sockets.Socket}""" Socket.__init__(self, socket.get_underlying_object()) self.frames = deque() self.last_received_data = time() self.who = None
def __init__(self, *args, **kwargs): self.on_connected_called = False Socket.__init__(self, *args, **kwargs)
def run(self): """Returns a tuple (IP, address) on success. Returns a string with error code on failure. Returns with False on silent errors""" print 'TRStartMatch(%s)' % self.alpha if self.alpha.invalid: return False # cannot make a match - it's been invalidated self.pdb.alphas.remove( self.alpha) # if alpha is valid then it's in the tables # Has everybody locked in? If no we need to forcibly lock them in if not self.alpha.has_everybody_locked_in(): for notlocked in self.alpha.get_those_who_did_not_lock(): # get applicable characters for player heroes = self.pdb.pdbhelper.get_available_heroes(notlocked) if len(heroes) == 0: # NO HEROES FOR PLAYER ?!?!?!?!?!? self._rollback() return '%s has no heroes to play with' if TRHeroPick(self.pdb, notlocked, choice(heroes)).start(slave=True) != None: self._rollback() return 'picking hero for %s failed' # ============= PRECONDITIONS SATISFIED. EVERYBODY ONLINE AND WITH A HERO PICKED # Sign off all players as entering PS_GAMMA for pid in self.alpha.team1 + self.alpha.team2: # sign off players as playing -> GAMMA pir = self.pdb.ensure(pid) pir.status = PS_GAMMA pir.alpha = None pir.queue = None # Ok, so let's examine the match... # Here we begin constructing tables players = [] for pid in self.alpha.team1 + self.alpha.team2: team_no = 0 if pid in self.alpha.team1 else 1 pd = { 'login': self.pdb.ensure(pid).login, 'password': self.pdb.pdbhelper.get_password_for_pid(pid), 'character': self.alpha.whom_picked_pid(pid), 'team': team_no } players.append(pd) bpf = { 'players': players, 'map_name': 'Town', } # Compute the GUGID gugid = '.'.join( map(str, self.alpha.team1) + map(str, self.alpha.team2)) # ALLOCATE THE MATCH!!! s = socket(AF_INET, SOCK_STREAM) try: s.connect(self.pdb.cshardmgr_interface) except SocketError: self._rollback() return 'internal error: no cshard uplink' s = JSONSocket(Socket(s)) s.settimeout(20) try: s.write({ 'request': 'allocate-shard', 'gugid': gugid, 'bpf_chunk': bpf }) rsp = s.read() except (FatalException, NonfatalException): self._rollback() return 'internal error: cshard replica failure' if 'response' not in rsp: self._rollback() return 'internal error: malformed cshard replica' if rsp['response'] == 'recess': self._rollback() return 'shard overload' conntriple = (rsp['tcp-interface'], rsp['tcp-port'], rsp['udp-port']) # create BetaGamma object team1 = dict([(pid, self.alpha.whom_picked_pid(pid)) for pid in self.alpha.team1]) team2 = dict([(pid, self.alpha.whom_picked_pid(pid)) for pid in self.alpha.team2]) bg = BetaGamma(team1, team2, gugid, self.alpha.qname) self.pdb.betagammas.append(bg) # Set the target server for players for pid in self.alpha.team1 + self.alpha.team2: self.pdb.ensure(pid).conn_triple = conntriple self.pdb.ensure(pid).betagamma = bg return conntriple
def __init__(self, socket): """@type socket: L{satella.channels.sockets.Socket}""" Socket.__init__(self, socket.get_underlying_object()) self.frames = deque() self.last_received_data = time()