Пример #1
0
 def listenIn(self, port, callbackObject, useSSL=False):
     """
     Creates a server using its arguments.
     @attention: This is a non-blocking operation. Please, check if the connection is ready BEFORE
     you send anything through it.
     Args:
         port: The port to listen in. If it's not free, a NetworkManagerException will be raised.
         callbackObject: the callback object that will process all the incoming
             packages received through this connection.
         useSSL: if True, the SSL version 4 protocol will be used. Otherwise, we'll stick
             to TCP version 4.
     Returns:
         Nothing
     """
     if self.__connectionPool.has_key(('', port)):
         raise NetworkManagerException("The port " + str(port) +
                                       " is already in use")
     # The port is free => proceed
     # Allocate the connection resources
     (queue, thread) = self.__allocateConnectionResources(callbackObject)
     # Create the NetworkConnection object
     connection = ServerConnection(useSSL, self.__certificatesDirectory,
                                   port, queue, thread, callbackObject)
     try:
         # Establish it
         connection.establish(None)
         if (connection.getError() == None):
             # Register the new connection
             self.__connectionPool[('', port)] = connection
         else:
             raise ConnectionException(str(connection.getError()))
     except ConnectionException as e:
         raise NetworkManagerException(e.message)
Пример #2
0
 def sendPacket(self, host, port, packet):
     """
     Sends a packet through the specified port and IP address.
     Args:
         port: The port assigned to the connection that will be used to send the packet.
         packet: The packet to send.
     Returns:
         Nothing
     Raises:
         NetworkManagerException: a NetworkManagerException will be raised if 
         - there were errors while establishing the connection, or 
         - if the connection was abnormally closed, or
         - if the connection is a server connection and it's not ready yet, or
         - if the supplied port is free
     """
     if not self.__connectionPool.has_key((host, port)):
         raise NetworkManagerException(
             "There's nothing attached to the port " + str(port))
     connection = self.__connectionPool[(host, port)]
     self.__detectConnectionErrors(connection)
     if not connection.isReady():
         if (connection.isServerConnection()):
             raise NetworkManagerException(
                 "No clients have connected to this port yet")
         else:
             raise NetworkManagerException(
                 "The connection is not ready yet")
     connection.registerPacket()
     self.__outgoingDataQueue.queue(packet.getPriority(),
                                    (connection, packet))
Пример #3
0
 def connectTo(self, host, port, timeout, callbackObject, useSSL=False):
     """
     Connects to a remote server using its arguments
     @attention: This is a blocking operation. The calling thread will be blocked until
     the connection is established or until a timeout error is detected.
     Args:
         host: host IP address
         port: the port where the host is listenning
         timeout: timeout in seconds. 
         callbackObject: the callback object that will process all the incoming
             packages received through this connection.
     Returns:
         Nothing
     Raises:
         NetworkManagerException: If no answer is received after timeout
             seconds, the connection process will be aborted and a 
             NetworkManagerException will be raised.
     """
     if self.__connectionPool.has_key((host, port)):
         raise NetworkManagerException("The port " + str(port) +
                                       " is already in use")
     # The port is free => proceed
     # Allocate the connection resources
     (queue, thread) = self.__allocateConnectionResources(callbackObject)
     # Create and configure the endpoint
     factory = _CygnusCloudProtocolFactory(queue)
     if (not useSSL):
         endpoint = TCP4ClientEndpoint(reactor, host, port, timeout, None)
     else:
         keyPath = self.__certificatesDirectory + "/" + "server.key"
         certificatePath = self.__certificatesDirectory + "/" + "server.crt"
         try:
             endpoint = SSL4ClientEndpoint(
                 reactor, host, port,
                 ssl.DefaultOpenSSLContextFactory(keyPath, certificatePath))
         except Exception:
             raise NetworkManagerException(
                 "The key, the certificate or both were not found")
     endpoint.connect(factory)
     # Wait until the connection is ready
     time = 0
     while factory.isDisconnected() and time <= timeout:
         sleep(0.01)
         time += 0.01
     if factory.isDisconnected():
         raise NetworkManagerException("The host " + host + ":" +
                                       str(port) +
                                       " seems to be unreachable")
     # Create the new connection
     connection = _NetworkConnection(False, host, port, factory, queue,
                                     thread, callbackObject)
     # Add the new connection to the connection pool
     self.__connectionPool[(host, port)] = connection
Пример #4
0
    def listenIn(self, port, callbackObject, useSSL=False):
        """
        Creates a server using its arguments.
        @attention: This is a non-blocking operation. Please, check if the connection is ready BEFORE
        you send anything through it.
        Args:
            port: The port to listen in. If it's not free, a NetworkManagerException will be raised.
            callbackObject: the callback object that will process all the incoming
                packages received through this connection.
        Returns:
            Nothing
        """
        if self.__connectionPool.has_key(('127.0.0.1', port)):
            raise NetworkManagerException("The port " + str(port) +
                                          " is already in use")
        # The port is free => proceed
        # Allocate the connection resources
        (queue, thread) = self.__allocateConnectionResources(callbackObject)
        # Create and configure the endpoint
        if (not useSSL):
            endpoint = TCP4ServerEndpoint(reactor, port)
        else:
            keyPath = self.__certificatesDirectory + "/" + "server.key"
            certificatePath = self.__certificatesDirectory + "/" + "server.crt"
            try:
                endpoint = SSL4ServerEndpoint(
                    reactor, port,
                    ssl.DefaultOpenSSLContextFactory(keyPath, certificatePath))
            except Exception:
                raise NetworkManagerException(
                    "The key, the certificate or both were not found")
        factory = _CygnusCloudProtocolFactory(queue)
        # Create the connection
        connection = _NetworkConnection(True, '', port, factory, queue, thread,
                                        callbackObject)

        # Create the deferred to retrieve the IListeningPort object
        def registerListeningPort(port):
            connection.setListeningPort(port)

        def onError(failure):
            connection.setError(failure)

        deferred = endpoint.listen(factory)
        deferred.addCallback(registerListeningPort)
        deferred.addErrback(onError)
        connection.setDeferred(deferred)
        # Register the new connection
        self.__connectionPool[('', port)] = connection
Пример #5
0
 def connectTo(self,
               host,
               port,
               timeout,
               callbackObject,
               useSSL=True,
               reconnect=False):
     """
     Connects to a remote server using its arguments
     @attention: This is a blocking operation. The calling thread will be blocked until
     the connection is established or until a timeout error is detected.
     Args:
         host: host IP address
         port: the port where the host is listenning
         timeout: timeout in seconds. 
         callbackObject: the callback object that will process all the incoming
             packages received through this connection.
         useSSL: if True, the SSL version 4 protocol will be used. Otherwise, we'll stick
             to TCP version 4.
         reconnect: if True, the network subsystem will try to reconnect to the server
             when the connection is lost.
     Returns:
         Nothing
     Raises:
         NetworkManagerException: If no answer is received after timeout
             seconds, the connection process will be aborted and a 
             NetworkManagerException will be raised.
     """
     if self.__connectionPool.has_key((host, port)):
         raise NetworkManagerException("The port " + str(port) +
                                       " is already in use")
     # The port is free => proceed
     # Allocate the connection resources
     (queue, thread) = self.__allocateConnectionResources(callbackObject)
     # Create the NetworkConnection object
     connection = ClientConnection(useSSL, self.__certificatesDirectory,
                                   host, port, queue, thread, reconnect,
                                   callbackObject)
     # Try to establish the connection
     try:
         if (connection.establish(timeout)):
             # The connection could be created => add it to the connection pool
             self.__connectionPool[(host, port)] = connection
         else:
             # Raise an exception
             raise NetworkManagerException(str(connection.getError()))
     except ConnectionException as e:
         raise NetworkManagerException(e.message)
Пример #6
0
 def __detectConnectionErrors(self, connection):
     """
     Checks if the given connection is in an error state or was unexpectedly closed.
     Args:
         connection: the connection to monitor.
     Returns:
         Nothing
     """
     if connection.isInErrorState():
         # Something bad has happened => close the connection, warn the user
         self.__connectionPool.pop(
             (connection.getHost(), connection.getPort()))
         raise NetworkManagerException(str(connection.getError()))
     if (connection.wasUnexpectedlyClosed()):
         self.__connectionPool.pop(
             (connection.getHost(), connection.getPort()))
         raise NetworkManagerException(
             "The connection was closed abnormally")
Пример #7
0
 def closeConnection(self, host, port):
     """
     Closes a connection
     Args:
         port: The port assigned to the connection. If it's free, a NetworkManagerException will be
         raised.
     Returns:
         Nothing
     """
     if not self.__connectionPool.has_key((host, port)):
         raise NetworkManagerException(
             "There's nothing attached to the port " + str(port))
     # Retrieve the connection
     connection = self.__connectionPool[(host, port)]
     # Ask the connection to close
     connection.close()
Пример #8
0
 def createPacket(self, priority):
     """
     Creates an empty data packet and returns it
     Args:
         priority: The new packet's priority. 
     Returns:
         a new data packet.
     Raises:
         NetworkManagerException: this exception will be raised when the packet's priority
         is not a positive integer.
     """
     if not isinstance(priority, int) or priority < 0:
         raise NetworkManagerException(
             "Data packets\' priorities MUST be positive integers")
     p = _Packet(Packet_TYPE.DATA, priority)
     return p
Пример #9
0
 def isConnectionReady(self, host, port):
     """
     Checks wether a connection is ready or not.
     Args:
         port: the port assigned to the connection.
     Returns:
         True if the connection is ready or False otherwise.
     Raises:
         NetworkManagerException: a NetworkManagerException will be raised if 
             - there were errors while establishing the connection, or if
             - the connection was abnormally closed, or if
             - the supplied port is free
     """
     if not self.__connectionPool.has_key((host, port)):
         raise NetworkManagerException("The port " + str(port) +
                                       " is not in use")
     connection = self.__connectionPool[(host, port)]
     self.__detectConnectionErrors(connection)
     return connection.isReady()