Esempio n. 1
0
 def esperarNotificacion(self, nomnot, funcion=lambda: None):
     """
     Código del hilo que vigila la notificación.
     self -> Objeto al que pertenece el hilo.
     nomnot es el nombre de la notificación a esperar.
     funcion es una función opcional que será llamada cuando se
     produzca la notificación.
     """
     if DEBUG: print "Inicia ejecución hilo"
     while self != None and self.continuar_hilo:
         if DEBUG: print "Entra en la espera bloqueante: %s" % nomnot
         self.abrir_cursor()
         self.cursor.execute("LISTEN %s;" % nomnot)
         self.conexion.commit()
         if select.select([self.cursor], [], [])!=([], [], []):
             if DEBUG: print "Notificación recibida"
             try:
                 self.comparar_swap()
             except SQLObjectChanged:
                 if DEBUG: 
                     print "pclases::esperarNotificacion -> Objeto cambiado"
                 funcion()
             except SQLObjectNotFound:
                 if DEBUG: print "Registro borrado"
                 funcion()
             # self.cerrar_cursor()
     else:
         if DEBUG: print "Hilo no se ejecuta"
     if DEBUG: print "Termina ejecución hilo"
Esempio n. 2
0
def get_n_packets(process):
    """
    @param process the process helper created with run_helper
    @return the number of packets that the helper prints on the stderr >= 0
            negative on errors.
    """
    if not WINDOWS:
        try:
            inp, out, err = select.select([process.stderr], [process.stderr],
                                          [process.stderr])
        except:
            # Here we could have select that hangs after a kill in stop
            return -1

        if process.stderr in inp:
            line = process.stderr.read()

            if not line:
                return -2
    else:
        try:
            # PeekNamedPipe is async here and doesn't block resulting
            # in gui freeze. So we use directly ReadFile here
            x = msvcrt.get_osfhandle(process.stderr.fileno())
            errCode, line = ReadFile(x, 1024, None)
        except:
            return -2

    # Here dumpcap use '\rPackets: %u ' while tcpdump 'Got %u\r'
    # over stderr file. We use simple split(' ')[1]

    try:
        return int(line.split(' ')[1])
    except:
        return -3
Esempio n. 3
0
 def run(self):
     try:
         while 1:
             if self.m_IsConnect != 1:
                 sleep(1)
                 continue
             else:
                 while 1:
                     infds, outfds, errfds = select.select([
                         self.m_s,
                     ], [
                         self.m_s,
                     ], [
                         self.m_s,
                     ], 1)
                     if len(infds) != 0:
                         if self.RecvData() != 0:
                             #self.m_IsConnect = 0
                             break
                     elif len(outfds) != 0:
                         if self.SendData() != 0:
                             #self.m_IsConnect = 0
                             break
                     else:
                         self.m_IsConnect = 0
                         break
                     # sleep(1)
     except socket.error, msg:
         print("Socket connect error! %s" % (msg))
         return -1
Esempio n. 4
0
def serve_until_quit(self):
    import select
    self.quit = False
    while not self.quit:
        rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
        if rd:
            self.last_request = time.time()
            self.handle_request()
Esempio n. 5
0
 def serve_until_stopped(self):
     import select
     abort = 0
     while not abort:
         rd, wr, ex = select.select([self.socket.fileno()], [], [],
                                    self.timeout)
         if rd:
             self.handle_request()
         abort = self.abort
Esempio n. 6
0
    def serve_until_stopped(self):
        import select

        abort = 0
        while not abort:
            rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort
Esempio n. 7
0
def UPCThread(threadName,delay):
	print 'Scan UPC now...'
	while (i==0):
		if (UPCShouldEnd == 1):
			thread.exit()
		i, o, e = select.select( [sys.stdin], [], [], 2 )
		print "You scan nothing!"
	
	if (i):
		UPC_code = sys.stdin.readline().strip()
		print "You scan", UPC_code
Esempio n. 8
0
 def run(self):
     buffer = []
     while not self.stop.is_set():
         (rd, _, _) = select.select([self.comm_file], [], [], 0.5)
         if rd:
             buffer.append(self.comm_file.read())
             while self.contains_message_end(buffer):
                 (buffer, parsed_message) = self.parse_message(buffer)
                 if self.is_asynchronous_message(parsed_message):
                     self.asynchronous_messages.push(parsed_message)
                 else:
                     self.synchronous_messages.push(parsed_message)
Esempio n. 9
0
 def run(self):
     buffer = []
     while not self.stop.is_set():
         (rd, _, _) = select.select([self.comm_file], [], [], 0.5)
         if rd:
             buffer.append(self.comm_file.read())
             while self.contains_message_end(buffer):
                 (buffer, parsed_message) = self.parse_message(buffer)
                 if self.is_asynchronous_message(parsed_message):
                     self.asynchronous_messages.push(parsed_message)
                 else:
                     self.synchronous_messages.push(parsed_message)
Esempio n. 10
0
def syncfileswithwiki(localdir, link, comment="", force=False):
    from urllib import urlretrieve
    from select import select
    from glob import glob
    #list localfiles
    listfiles = map(lambda d: os.path.split(d)[1],
                    glob(os.path.join(localdir, '*')))
    localfiles = {}
    #   timeoff=time.altzone if time.localtime().tm_isdst==1 else time.timezone
    for listfile in listfiles:
        try:
            filetime = int(os.path.getmtime(os.path.join(localdir, listfile)))
            localfiles[listfile] = filetime
        except:
            continue


#      print "local",listfile,filetime,timer2s(filetime),timeoff
#list remotefiles
    remotefiles = grubwikifile(link)
    if not isinstance(remotefiles, dict): return False
    # return
    #compare remote and local
    auto = os.getenv("BEAMUPDATE")
    askforupdate = False
    for k in remotefiles.keys():
        if not localfiles.has_key(
                k) or remotefiles[k][0] - localfiles[k] > 7200:
            changelog = getchangelog()
            if not askforupdate:
                print "%s found newer version,changelog:\n%s\n" % (comment,
                                                                   changelog)
            if auto == "ask" and not askforupdate and not force:
                print "do you want to update it?(Y/y,will default update after 30 secs)"
                i, o, e = select.select([sys.stdin], [], [], 30)
                if i: ifupdate = sys.stdin.readline().strip()
                else: ifupdate = "y"
                if not ifupdate in ["Y", "y"]:
                    print "skip update"
                    return False
                else:
                    "will update the %s" % comment
            askforupdate = True
            if auto != "0" or force:
                try:
                    urlretrieve(remotefiles[k][1], os.path.join(localdir, k))
                    print "%s %s updated,time old:%s new:%s,it is better to rerun script again" % (
                        comment, k, localfiles[k], remotefiles[k][0])
                except Exception as e:
                    print "failed to update %s,please check your network connection" % comment
                    print e
                    return False
    return True
def get_char_with_break():
    import sys, tty, termios, select
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    s = ''
    try:
        tty.setraw(sys.stdin.fileno())
        if select.select([sys.stdin,], [], [], 0.0)[0]:
            s = sys.stdin.read(1)
            print 's: ', s

    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

    return s
Esempio n. 12
0
def syncfileswithwiki(localdir,link,comment="",force=False):
    from urllib import urlretrieve
    from select import select
    from glob import glob
    #list localfiles
    listfiles=map(lambda d:os.path.split(d)[1],glob(os.path.join(localdir,'*')))
    localfiles={}
 #   timeoff=time.altzone if time.localtime().tm_isdst==1 else time.timezone
    for listfile in listfiles:
      try:
          filetime=int(os.path.getmtime(os.path.join(localdir,listfile)))
          localfiles[listfile]=filetime
      except:continue
#      print "local",listfile,filetime,timer2s(filetime),timeoff
    #list remotefiles
    remotefiles=grubwikifile(link)
    if not isinstance(remotefiles,dict):return False
   # return
    #compare remote and local
    auto=os.getenv("BEAMUPDATE")
    askforupdate=False
    for k in remotefiles.keys():
      if not localfiles.has_key(k) or remotefiles[k][0]-localfiles[k]>7200:
          changelog=getchangelog()
          if not askforupdate:print "%s found newer version,changelog:\n%s\n"%(comment,changelog)
          if auto=="ask" and not askforupdate and not force:
            print "do you want to update it?(Y/y,will default update after 30 secs)"
            i,o,e =select.select([sys.stdin],[],[],30)
            if i:ifupdate=sys.stdin.readline().strip()
            else:ifupdate="y"
            if not ifupdate in ["Y","y"]:
                print "skip update"
                return False
            else:"will update the %s"%comment
          askforupdate=True
          if auto!="0" or force:
            try:
                urlretrieve(remotefiles[k][1],os.path.join(localdir,k))
                print "%s %s updated,time old:%s new:%s,it is better to rerun script again"%(comment,k,localfiles[k],remotefiles[k][0])
            except Exception as e:
                print "failed to update %s,please check your network connection"%comment
                print e
                return False
    return True
Esempio n. 13
0
def sender():
	global DONE
	readPorts = [sockSend]
	MessageId = 1
	Length = 100
 	# step 1
 	for i in range(0, NUMFRAGS):
 		#Test retry time out (WORKS!)
 		if (i != 4):
 			if (i != 5):
		 		fragment = fragment_factory(MessageId, Length, NUMFRAGS, DATA, '{0:032b}'.format(1 << i), "Hello: " + str(i))
		 		sockSend.sendto(fragment, (UDP_IP, UDP_PORT_RECEIVER))

 		#added

 	while (not globalSendEnd):
 		ready_to_read, dont_care, don_care = select.select(readPorts, [],[],1)
 		if (len(ready_to_read) == 1):
 			data, addr = sockSend.recvfrom(65535)

 			print "SRR states to send fragments: "

 			#find out which fragments need resending
 			listOfMissingFrags = SRRdecoder(data)
 			for missing in listOfMissingFrags:
 				print "Missing Fragment Number:" + str(missing)
 				if (missing != 5):
	 				fragment = fragment_factory(MessageId, Length, NUMFRAGS, DATA, '{0:032b}'.format(1 << missing), "Hello: " + str(i))
	 				sockSend.sendto(fragment, (UDP_IP, UDP_PORT_RECEIVER))
 			


 		if (DONE):
 			break
 		#added

	sockSend.close()
	print "sender closed"
Esempio n. 14
0
def get_n_packets(process):
    """
    @param process the process helper created with run_helper
    @return the number of packets that the helper prints on the stderr >= 0
            negative on errors.
    """
    if not WINDOWS:
        try:
            inp, out, err = select.select([process.stderr],
                                          [process.stderr],
                                          [process.stderr])
        except:
            # Here we could have select that hangs after a kill in stop
            return -1

        if process.stderr in inp:
            line = process.stderr.read()

            if not line:
                return -2
    else:
        try:
            # PeekNamedPipe is async here and doesn't block resulting
            # in gui freeze. So we use directly ReadFile here
            x = msvcrt.get_osfhandle(process.stderr.fileno())
            errCode, line = ReadFile(x, 1024, None)
        except:
            return -2

    # Here dumpcap use '\rPackets: %u ' while tcpdump 'Got %u\r'
    # over stderr file. We use simple split(' ')[1]

    try:
        return int(line.split(' ')[1])
    except:
        return -3
Esempio n. 15
0
def receiver():
	global sendSRR
	global DONE
	received = False
	counter = 0
	attempts = 0
	potentialRead = [sockRec]

	lastFragTimer = TimerReset(5, lastFragExpired)
	retryTimer = TimerReset(5, retryExpired)
	#ListOfMessages = []

	FirstProto = 0
	FirstMid = 0

	bitFragsArrived = []
	for i in range(0, NUMFRAGS):
		bitFragsArrived.append('0')

	while (not globalIsOver):
		ready_to_read, dont_care, don_care = select.select(potentialRead, [],[],1)
		if (len(ready_to_read) == 1):
			data, addr = sockRec.recvfrom(65535)
			ready_to_read = None
			print "received message:", data
			counter = counter + 1

			#Decode Fragment
			thisFrag = decode_fragment(data)

			#Check that it's a valid fragment
			if thisFrag["PacketType"] != DATA:
				print "invalid fragment"
				break

			#Print contents of Fragment
			print "Contents of this Fragment is: "
			printFragmentDict(thisFrag)
			print "\n"

			fragIndex = thisFrag["FragMask"]
			bitFragsArrived[fragIndex] = '1'
			print "bitFragsArrived:"
			print bitFragsArrived
			print fragIndex

			#if this is the first fragment to arrive, save msg id
			if counter == 1:
				FirstProto = thisFrag["Proto"]
				FirstMid = thisFrag["MessageId"]
			else:
				if thisFrag["Proto"] != FirstProto:
					print "NOT THE SAME PROTOCOL!"
					break
				if thisFrag["MessageId"] != FirstMid:
					print "NOT THE SAME MESSAGE ID!"
					break

			if fragIndex == 0:
				lastFragTimer.start()
				
			if (fragIndex == 31) and (attempts == 0):
				lastFragTimer.cancel()
				attempts = 1
				if checkAllFragArrived(bitFragsArrived) == False:
					retryTimer.start()

			if checkAllFragArrived(bitFragsArrived) == True:
				print "Yay all fragments arrived!"
				break

		if (sendSRR):
			#Reset send signal 
			sendSRR = False

			FragMaskToSend = "".join(bitFragsArrived)
			SrcMessage = fragment_factory(1, 100, 1, SRC, FragMaskToSend, "")
			sockRec.sendto(SrcMessage, (UDP_IP, UDP_PORT_SENDER))

	DONE = True
	sockRec.close()
	print "receiver closed"
Esempio n. 16
0
def main():
    # Загружаем какой адрес слушать.
    try:
        if '-a' in sys.argv:
            listen_address = sys.argv[sys.argv.index('-a') + 1]
        else:
            listen_address = ''
    except IndexError:
        print(
            'После параметра \'a\' - необходимо указать адресб который будет слушать сервер.'
        )
        sys.exit(1)

    # Загружаем ,на какой порт обращаться.
    try:
        if '-p' in sys.argv:
            listen_port = int(sys.argv[sys.argv.index('-p') + 1])
        else:
            listen_port = DEFAULT_PORT
        if listen_port < 1024 or listen_port > 65535:
            raise ValueError
    except IndexError:
        print('После параметра \'p\' - необходимо указать номер порта.')
        sys.exit(1)
    except ValueError:
        print(
            'В качестве порта может указано толко число в диапазоне от 1024 до 65535'
        )
        sys.exit(1)

    # Готовим сокет.
    transport = socket.socket()
    transport.bind((listen_address, listen_port))
    # список клиентов , очередь сообщений
    clients = []
    messages = []
    # Слушаем порт.
    transport.listen(MAX_CONNECTIONS)

    while True:
        #client, client_address = transport.accept()
        try:
            client, client_address = transport.accept()
            # message_from_client = get_message(client)
            # response = process_client_message(message_from_client)
            # send_message(client, response)
            # client.close()
        except OSError:
            pass
        else:
            clients.append(client)

        recv_data_lst = []
        send_data_lst = []
        err_lst = []
        # Проверяем на наличие ждущих клиентов
        try:
            if clients:
                recv_data_lst, send_data_lst, err_lst = select.select(
                    clients, clients, [], 0)
        except OSError:
            pass

        # принимаем сообщения и если там есть сообщения,
        # кладём в словарь,если ошибка ,исключаем клиента.
        if recv_data_lst:
            for client_with_message in recv_data_lst:
                try:
                    process_client_message(get_message(client_with_message),
                                           messages, client_with_message)
                except:
                    clients.remove(process_client_message)

        # Если есть сообщение для отправки ожидающие клиенты, отправляем им сообщение.
        message_from_client = get_message(client)
        response = process_client_message(message_from_client)
        # send_message(client, response)
        print(messages)
        print(send_data_lst)
        if messages and send_data_lst:

            del messages[0]
            for waiting_client in send_data_lst:
                try:
                    send_message(waiting_client, message_from_client)
                except:
                    clients.remove(waiting_client)