示例#1
0
def main():
    log.startLogging(sys.stdout)
    print "main"
    endpoint = get_endpoint()
    endpoint.connect(Factory.forProtocol(Echo))
    print "running reactor"
    reactor.run()
    def test_unix_already_listening(self):
        """
        A config with type = "unix" will create an endpoint for a UNIX socket
        at the given path, and delete it if required.
        """
        path = FilePath("/tmp").child(uuid4().hex).path
        self.addCleanup(os.remove, path)

        # Something is already there
        FilePath(path).setContent(b"")

        reactor = SelectReactor()
        config = {
            "type": "unix",
            "path": path
        }

        endpoint = create_listening_endpoint_from_config(config, self.cbdir,
                                                         reactor, self.log)
        self.assertTrue(isinstance(endpoint, UNIXServerEndpoint))

        factory = Factory.forProtocol(Echo)
        endpoint.listen(factory)

        self.assertIn(
            factory,
            [getattr(x, "factory", None) for x in reactor.getReaders()])
def proxy(upstream, endpoint, header):
    """
    Establish a new connection to ``endpoint`` and begin proxying between that
    connection and ``upstream``.

    :param IProtocol upstream: A connected protocol.  All data received by
        this protocol from this point on will be sent along to another newly
        established connection.

    :param IStreamClientEndpoint endpoint: An endpoint to use to establish a
        new connection.  All data received over this connection will be sent
        along to the upstream connection.

    :param bytes header: Some extra data to write to the new downstream
        connection before proxying begins.
    """
    def failed(reason):
        upstream.transport.resumeProducing()
        upstream.transport.abortConnection()
        return reason

    upstream.transport.pauseProducing()

    peer = upstream.transport.getPeer()
    action = start_action(
        action_type=u"grid-router:proxy",
        **{u"from": (peer.host, peer.port)}
    )
    with action.context():
        d = DeferredContext(endpoint.connect(Factory.forProtocol(_Proxy)))
        d.addCallbacks(
            lambda downstream: DeferredContext(downstream.take_over(upstream, header)),
            failed,
        )
        return d.addActionFinish()
示例#4
0
    def test_rawsocket_with_factory(self):
        """
        Speaking RawSocket when the connection is made will make UniSocket
        create a new RawSocket protocol and send the data to it.
        """
        t = StringTransport()

        class MyFakeRawSocket(Protocol):
            """
            A fake RawSocket factory which just echos data back.
            """
            def dataReceived(self, data):
                self.transport.write(data)

        fake_rawsocket = Factory.forProtocol(MyFakeRawSocket)
        f = UniSocketServerFactory(rawsocket_factory=fake_rawsocket)
        p = f.buildProtocol(None)

        p.makeConnection(t)
        t.protocol = p

        self.assertTrue(t.connected)
        p.dataReceived(b'\x7F0000000')
        p.dataReceived(b'moredata')

        self.assertTrue(t.connected)
        self.assertEqual(t.value(), b'\x7F0000000moredata')
示例#5
0
 def setUp(self):
     self.receiver = SavingEchoReceiver()
     self.protocol = WebSocketsProtocol(self.receiver)
     self.factory = Factory.forProtocol(lambda: self.protocol)
     self.transport = StringTransportWithDisconnection()
     self.protocol.makeConnection(self.transport)
     self.transport.protocol = self.protocol
示例#6
0
def init():
    """
    Init reactor and events.
    """
    reactor.listenTCP(PORT+1, CeltyFactory())
    reactor.listenTCP(PORT, SockJSFactory(Factory.forProtocol(CeltyProtocol)))
    i("Started twisted server at {}:{}", "localhost", PORT)
示例#7
0
    def test_websocket_with_map(self):
        """
        Speaking WebSocket when the connection is made will make UniSocket
        create a new WebSocket protocol and send the data to it.
        """
        t = StringTransport()

        class MyFakeWebSocket(Protocol):
            """
            A fake WebSocket factory which just echos data back.
            """
            def dataReceived(self, data):
                self.transport.write(data)

        fake_websocket = Factory.forProtocol(MyFakeWebSocket)
        websocket_map = OrderedDict({u"baz": None})
        websocket_map["ws"] = fake_websocket

        f = UniSocketServerFactory(websocket_factory_map=websocket_map)
        p = f.buildProtocol(None)

        p.makeConnection(t)
        t.protocol = p

        self.assertTrue(t.connected)
        p.dataReceived(b'GET /ws HTTP/1.1\r\nConnection: close\r\n\r\n')

        self.assertTrue(t.connected)
        self.assertEqual(t.value(),
                         b'GET /ws HTTP/1.1\r\nConnection: close\r\n\r\n')
示例#8
0
def main(reactor=reactor):
    arguments = vars(parser.parse_args())
    for description in arguments["endpoint"]:
        endpoint = serverFromString(reactor=reactor, description=description)

        wabbit = Factory.forProtocol(WabbitServer)
        endpoint.listen(wabbit)
    reactor.run()
def server_setup(port):
    f = SockJSFactory(Factory.forProtocol(TwistedChatConnection))

    reactor.listenTCP(port, f)

    os.system('open static/index_twisted.html')

    reactor.run()
 def factory(self):
     """
     :return: A protocol factory for a Foolscap proxy server.
     """
     f = Factory.forProtocol(_FoolscapProxy)
     f.reactor = self._reactor
     f.route_mapping = self.route_mapping
     return f
示例#11
0
def main(reactor):
    pemBytes = FilePath(b"ca-private-cert.pem").getContent()
    certificateAuthority = Certificate.loadPEM(pemBytes)
    myCertificate = PrivateCertificate.loadPEM(pemBytes)
    serverEndpoint = SSL4ServerEndpoint(
        reactor, 4321, myCertificate.options(certificateAuthority)
    )
    serverEndpoint.listen(Factory.forProtocol(ReportWhichClient))
    return Deferred()
示例#12
0
 def go(self, reactor):
     """
     
     """
     mgr = MPMManager(reactor)
     endpoint = TCP4ServerEndpoint(reactor, 8123)
     yield endpoint.listen(Factory.forProtocol(
         lambda: SendToSubprocess(mgr)))
     yield Deferred()
示例#13
0
 def initServer(self):
     """
     Инициализация сервера
     :return : defer.Deferred
     """
     self.serverEndpoint = serverFromString(self.reactor, b"tcp:9879")
     factory = Factory.forProtocol(lambda: AMP(locator=PongLocator()))
     savePort = lambda p: self.save('serverPort', p)  # given port
     return self.serverEndpoint.listen(factory).addCallback(savePort)
示例#14
0
 def initClient(self):
     """
     Инициализация клиента
     :return : defer.Deferred
     """
     clientEndpoint = clientFromString(self.reactor, b"tcp:host=localhost:port=9879")
     protocolFactory = Factory.forProtocol(AMP)
     saveProtocol = lambda p: self.save('clientProtocol', p)  # given protocol
     return clientEndpoint.connect(protocolFactory).addCallback(saveProtocol)
示例#15
0
 def initServer(self):
     """
     Инициализация сервера
     :return : defer.Deferred
     """
     self.serverEndpoint = serverFromString(self.reactor, b'tcp:9879')
     factory = Factory.forProtocol(
         lambda: AMP(locator=DiffMatchPatchAlgorithm(None, initialText=constants.initialText)))
     savePort = lambda p: save(self, 'serverPort', p)  # given port
     return self.serverEndpoint.listen(factory).addCallback(savePort)
示例#16
0
 def test_overflowBytesSentToWrappedProtocol(self):
     """
     Test if non-header bytes are passed to the wrapped protocol.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(address.IPv6Address("TCP", b"::1", 8080))
     transport = StringTransportWithDisconnection()
     proto.makeConnection(transport)
     proto.dataReceived(b"PROXY TCP6 ::1 ::2 8080 8888\r\nHTTP/1.1 / GET")
     self.assertEqual(proto.wrappedProtocol.data, b"HTTP/1.1 / GET")
示例#17
0
    def setup_transport(self):
        config = self.get_static_config()
        self.client_factory = Factory.forProtocol(self.protocol_class)
        self.client_factory.vumi_transport = self

        prefix = "%s:ussd_codes" % (config.transport_name,)
        self.session_manager = yield SessionManager.from_redis_config(
            config.redis_manager, prefix, config.ussd_session_lifetime)
        self.client_service = self.get_service(
            config.twisted_endpoint, self.client_factory)
示例#18
0
 def test_overflowBytesSentToWrappedProtocolChunks(self):
     """
     Test if header streaming passes extra data appropriately.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(address.IPv6Address("TCP", b"::1", 8080))
     transport = StringTransportWithDisconnection()
     proto.makeConnection(transport)
     proto.dataReceived(self.IPV6HEADER[:18])
     proto.dataReceived(self.IPV6HEADER[18:] + b"HTTP/1.1 / GET")
     self.assertEqual(proto.wrappedProtocol.data, b"HTTP/1.1 / GET")
示例#19
0
 def _initServer(self, locator, serverConnString):
     """
     Инициализация сервера
     :type serverConnString: str строка подключения для serverFromString
     :return : defer.Deferred
     """
     self.history_line.clean()
     self.serverEndpoint = serverFromString(self.reactor, serverConnString)
     savePort = lambda p: save(self, 'serverPort', p)  # given port
     self.serverFactory = Factory.forProtocol(lambda: AMP(locator=locator))
     return self.serverEndpoint.listen(self.serverFactory).addCallback(savePort)
示例#20
0
 def test_invalidHeaderDisconnects(self):
     """
     Test if invalid headers result in connectionLost events.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(address.IPv4Address("TCP", b"127.1.1.1", 8080))
     transport = StringTransportWithDisconnection()
     transport.protocol = proto
     proto.makeConnection(transport)
     proto.dataReceived(b"NOTPROXY anything can go here\r\n")
     self.assertFalse(transport.connected)
def ServerSetup(port):
    f = SockJSFactory(Factory.forProtocol(TwistedChatConnection))

    reactor.listenTCP(port, f)

    os.system('open /Users/kurtisjungersen/COS/NotificationCenterFiles/'
              'SockJS_Testing/benchmarking/Static/index_Twisted.html')

    reactor.run()

#ServerSetup(8020)
示例#22
0
 def test_invalidHeaderDisconnects(self):
     """
     Test if invalid headers result in connectionLost events.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(address.IPv6Address("TCP", b"::1", 8080))
     transport = StringTransportWithDisconnection()
     transport.protocol = proto
     proto.makeConnection(transport)
     proto.dataReceived(b"\x00" + self.IPV4HEADER[1:])
     self.assertFalse(transport.connected)
示例#23
0
 def __init__(self, reactor, endpoint, elements, encoding):
     self.__reactor = reactor
     self.__elements = elements
     self.__encoding = encoding
     
     # ClientService (which does reconnecting) is only since 16.1 and we currently want to support 13.2 due to MacPorts and Debian versions
     # cs = ClientService(endpoint, Factory.forProtocol(_ControllerProtocol))
     # cs.startService()
     factory = Factory.forProtocol(_ControllerProtocol)
     self.__protocol = None
     endpoint.connect(factory).addCallback(self.__got_protocol)
示例#24
0
文件: cabsagent.py 项目: caedm/cabs
def start_ssl_cmd_server():
    with open(settings["Agent_Cert"], 'r') as certfile:
        certdata = certfile.read()
    if settings["Agent_Priv_Key"] != settings["Agent_Cert"]:
        with open(settings.get("Agent_Priv_Key"), 'r') as keyfile:
            certdata += keyfile.read()
    with open(settings.get("Broker_Cert"), 'r') as f:
        authdata = f.read()
    certificate = PrivateCertificate.loadPEM(certdata)
    authority = Certificate.loadPEM(authdata)
    factory = Factory.forProtocol(CommandHandler)
    reactor.listenSSL(int(settings.get("Command_Port")), factory, certificate.options(authority))
示例#25
0
 def test_overflowBytesSentToWrappedProtocolAfter(self):
     """
     Test if wrapper writes all data to wrapped protocol after parsing.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(address.IPv6Address("TCP", b"::1", 8080))
     transport = StringTransportWithDisconnection()
     proto.makeConnection(transport)
     proto.dataReceived(b"PROXY TCP6 ::1 ::2 ")
     proto.dataReceived(b"8080 8888\r\nHTTP/1.1 / GET")
     proto.dataReceived(b"\r\n\r\n")
     self.assertEqual(proto.wrappedProtocol.data, b"HTTP/1.1 / GET\r\n\r\n")
 def test_invalidPartialHeaderDisconnects(self):
     """
     Test if invalid headers result in connectionLost events.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(
         address.IPv4Address("TCP", b"127.1.1.1", 8080), )
     transport = StringTransportWithDisconnection()
     transport.protocol = proto
     proto.makeConnection(transport)
     proto.dataReceived(b"PROXY TCP4 1.1.1.1\r\n")
     proto.dataReceived(b"2.2.2.2 8080\r\n")
     self.assertFalse(transport.connected)
示例#27
0
        def _listening(factory):
            d = client_endpoint.connect(Factory.forProtocol(TestProtocol))

            @d.addCallback
            def _(proto):
                p.append(proto)

                proto.transport.write(
                    Connect(client_id="test123",
                            flags=ConnectFlags(clean_session=False)).serialise())

                proto.transport.write(
                    Publish(duplicate=False, qos_level=1, retain=False, topic_name="test", payload=b"{}", packet_identifier=1).serialise())
 def test_overflowBytesSentToWrappedProtocolAfter(self):
     """
     Test if wrapper writes all data to wrapped protocol after parsing.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(address.IPv6Address("TCP", b"::1",
                                                       8080), )
     transport = StringTransportWithDisconnection()
     proto.makeConnection(transport)
     proto.dataReceived(b"PROXY TCP6 ::1 ::2 ")
     proto.dataReceived(b"8080 8888\r\nHTTP/1.1 / GET")
     proto.dataReceived(b"\r\n\r\n")
     self.assertEqual(proto.wrappedProtocol.data, b"HTTP/1.1 / GET\r\n\r\n")
示例#29
0
 def __init__(self, ipcWorker):
     super().__init__()
     self.ipcWorker = ipcWorker
     self.endpoints = [[
         TCP6ServerEndpoint(reactor, port) for port in range(5250, 5260)
     ]]
     self.connections = defaultdict(set)
     self.connectionsCache = defaultdict(dict)
     self.waiters = defaultdict(set)
     self.factory = Factory.forProtocol(RegionServer)
     self.factory.service = self
     self.ports = []
     self.events = EventGroup("connected", "disconnected")
示例#30
0
 def test_invalidHeaderDisconnects(self):
     """
     Test if invalid headers result in connectionLost events.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(
         address.IPv4Address('TCP', b'127.1.1.1', 8080),
     )
     transport = StringTransportWithDisconnection()
     transport.protocol = proto
     proto.makeConnection(transport)
     proto.dataReceived(b'NOTPROXY anything can go here\r\n')
     self.assertFalse(transport.connected)
示例#31
0
 def test_overflowBytesSentToWrappedProtocolChunks(self):
     """
     Test if header streaming passes extra data appropriately.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(
         address.IPv6Address('TCP', b'::1', 8080),
     )
     transport = StringTransportWithDisconnection()
     proto.makeConnection(transport)
     proto.dataReceived(self.IPV6HEADER[:18])
     proto.dataReceived(self.IPV6HEADER[18:] + b'HTTP/1.1 / GET')
     self.assertEqual(proto.wrappedProtocol.data, b'HTTP/1.1 / GET')
示例#32
0
 def test_invalidHeaderDisconnects(self):
     """
     Test if invalid headers result in connectionLost events.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(
         address.IPv6Address('TCP', b'::1', 8080),
     )
     transport = StringTransportWithDisconnection()
     transport.protocol = proto
     proto.makeConnection(transport)
     proto.dataReceived(b'\x00' + self.IPV4HEADER[1:])
     self.assertFalse(transport.connected)
示例#33
0
def start_ssl_cmd_server():
    with open(settings["Broker_Cert"], 'r') as certfile:
        certdata = certfile.read()
    if settings["Broker_Priv_Key"] != settings["Broker_Cert"]:
        with open(settings.get("Broker_Priv_Key"), 'r') as keyfile:
            certdata += keyfile.read()
    with open(settings["Trusted_Clients"], 'r') as f:
        authdata = f.read()
    certificate = internet.ssl.PrivateCertificate.loadPEM(certdata)
    authority = internet.ssl.Certificate.loadPEM(authdata)
    factory = Factory.forProtocol(CommandHandler)
    reactor.listenSSL(int(settings.get("Command_Port")), factory,
                      certificate.options(authority))
示例#34
0
        def _listening(factory):
            d = client_endpoint.connect(Factory.forProtocol(TestProtocol))

            @d.addCallback
            def _(proto):
                p.append(proto)

                proto.transport.write(
                    Connect(client_id=u"test123",
                            flags=ConnectFlags(clean_session=False)).serialise())

                proto.transport.write(
                    Publish(duplicate=False, qos_level=1, retain=False, topic_name=u"test", payload=b"{}", packet_identifier=1).serialise())
示例#35
0
 def test_validUNIXHeaderResolves_getPeerHost(self):
     """
     Test if UNIX headers result in the correct host and peer data.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(address.UNIXAddress(b"/home/test/sockets/server.sock"))
     transport = StringTransportWithDisconnection()
     proto.makeConnection(transport)
     proto.dataReceived(self.UNIXHEADER)
     self.assertEqual(proto.getPeer().name, b"/home/tests/mysockets/sock")
     self.assertEqual(proto.wrappedProtocol.transport.getPeer().name, b"/home/tests/mysockets/sock")
     self.assertEqual(proto.getHost().name, b"/home/tests/mysockets/sock")
     self.assertEqual(proto.wrappedProtocol.transport.getHost().name, b"/home/tests/mysockets/sock")
示例#36
0
def start():
    readConfigFile()
    t = Thread(target=heartbeat_loop)
    t.daemon = True
    t.start()

    if settings.get("Agent_Priv_Key") is None:
        endpoint = endpoints.TCP4ServerEndpoint(reactor, int(settings.get("Command_Port")))
        endpoint.listen(Factory.forProtocol(CommandHandler))
    else:
        start_ssl_cmd_server()
    logging.info("running the reactor")
    reactor.run()
示例#37
0
文件: ipc.py 项目: laoyin/maas
 def __init__(self, reactor, workers=None, socket_path=None):
     super(IPCMasterService, self).__init__()
     self.reactor = reactor
     self.workers = workers
     self.socket_path = socket_path
     if self.socket_path is None:
         self.socket_path = get_ipc_socket_path()
     if os.path.exists(self.socket_path):
         os.remove(self.socket_path)
     self.endpoint = UNIXServerEndpoint(reactor, self.socket_path)
     self.port = None
     self.connections = {}
     self.factory = Factory.forProtocol(IPCMaster)
     self.factory.service = self
示例#38
0
def start():
    readConfigFile()
    t = Thread(target=heartbeat_loop)
    t.daemon = True
    t.start()

    if settings.get("Agent_Priv_Key") is None:
        endpoint = endpoints.TCP4ServerEndpoint(
            reactor, int(settings.get("Command_Port")))
        endpoint.listen(Factory.forProtocol(CommandHandler))
    else:
        start_ssl_cmd_server()
    logging.info("running the reactor")
    reactor.run()
示例#39
0
文件: tap.py 项目: hynek/tnw
    def startService(self):
        MultiService.startService(self)

        staticPath = FilePath(__file__).sibling("static")
        root = NoListDirFile(staticPath.path)
        root.putChild('api', SockJSResource(
            Factory.forProtocol(DaneDoctorProtocol))
        )

        webService = StreamServerEndpointService(
            serverFromString(self._reactor, "tcp:8080"),
            Site(root)
        )
        webService.setServiceParent(self)
示例#40
0
    def _authorized_request(self,
                            token,
                            headers,
                            kubernetes_host=b"example.invalid."):
        """
        Get an agent using ``authenticate_with_serviceaccount`` and issue a
        request with it.

        :return bytes: The bytes of the request the agent issues.
        """
        server = AccumulatingProtocol()
        factory = Factory.forProtocol(lambda: server)
        factory.protocolConnectionMade = None

        reactor = create_reactor()
        reactor.listenTCP(80, factory)

        t = FilePath(self.useFixture(TempDir()).path)
        t = t.asBytesMode()
        serviceaccount = t.child(b"serviceaccount")
        serviceaccount.makedirs()

        serviceaccount.child(b"ca.crt").setContent(_CA_CERT_PEM)
        serviceaccount.child(b"token").setContent(token)

        environ = encode_environ({
            u"KUBERNETES_SERVICE_HOST":
            kubernetes_host.decode("ascii"),
            u"KUBERNETES_SERVICE_PORT":
            u"443"
        })
        self.patch(os, "environ", environ)

        agent = authenticate_with_serviceaccount(
            reactor,
            path=serviceaccount.asTextMode().path,
        )

        d = agent.request(b"GET", b"http://" + kubernetes_host, headers)
        assertNoResult(self, d)
        [(host, port, factory, _, _)] = reactor.tcpClients

        addr = HOST_MAP.get(kubernetes_host.decode("ascii"), None)
        self.expectThat((host, port), Equals((addr, 80)))

        pump = ConnectionCompleter(reactor).succeedOnce()
        pump.pump()

        return server.data
示例#41
0
 def test_preDataReceived_getPeerHost(self) -> None:
     """
     Before any data is received the HAProxy protocol will return the same peer
     and host as the IP connection.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(
         address.IPv4Address("TCP", "127.0.0.1", 8080), )
     transport = StringTransportWithDisconnection(
         hostAddress=mock.sentinel.host_address,
         peerAddress=mock.sentinel.peer_address,
     )
     proto.makeConnection(transport)
     self.assertEqual(proto.getHost(), mock.sentinel.host_address)
     self.assertEqual(proto.getPeer(), mock.sentinel.peer_address)
示例#42
0
文件: fixtures.py 项目: zhangrb/maas
    def addCluster(self, protocol):
        """Add a new stub cluster using the given `protocol`.

        The `protocol` should be an instance of `amp.AMP`.

        :return: py:class:`twisted.test.iosim.IOPump`
        """
        server_factory = Factory.forProtocol(RegionServer)
        server_factory.service = self.rpc
        server = server_factory.buildProtocol(addr=None)
        return iosim.connect(
            server, iosim.makeFakeServer(server),
            protocol, iosim.makeFakeClient(protocol),
            debug=False,  # Debugging is useful, but too noisy by default.
        )
示例#43
0
    def connect(self, reconnecting=False):
        if self.connecting and not reconnecting:
            return
        self.connecting = True
        endPoint = TCP4ClientEndpoint(reactor, self.host, self.port, 10)
        d = endPoint.connect(Factory.forProtocol(GraphiteProtocol))

        def success(connection):
            self.connecting = False
            log.msg('Connected to %s' % self)
            self.connection = connection

        def failed(error):
            log.err('Connect to %s failed: %s' % (self, error))
            reactor.callLater(10, self.connect, True)
        d.addCallbacks(success, failed)
示例#44
0
文件: kern.py 项目: gar-syn/congo-lab
class EWBalance (Machine):

    protocolFactory = Factory.forProtocol(QueuedLineReceiver)
    name = "Kern EW Balance"

    def setup (self):

        # setup variables
        self.weight = Stream(title = "Weight", type = float, unit = "g")
        self.status = Property(title = "Status", type = "str")

    def start (self):
        def interpret_weight (result: str):
            result_state = result[-1]
            # result_type = result[-2]
            result_unit = result[-4:2]

            if result_state == "E":
                self.status._push("error")
                return
            elif result_state == "S":
                self.status._push("stable")
            elif result_state == "U":
                self.status._push("fluctuating")

            # result_type != "G" --> out of range.
            
            if result_unit != " G":
                raise Exception("Balance units should be set to grams.")

            result_value = float(result[:-5])

            self.weight._push(result_value)

        def monitor_weight ():
            self.protocol.write("O8").addCallback(interpret_weight)

        self._tick(monitor_weight, 1)

    def stop (self):
        self._stopTicks()

    def reset (self):
        return defer.succeed('OK')

    def tare (self):
        return self.protocol.write("T ", expectReply = False, wait = 5)
def _build_test_server():
    """Construct a test server

    This builds an HTTP channel, wrapped with a TLSMemoryBIOProtocol

    Returns:
        TLSMemoryBIOProtocol
    """
    server_factory = Factory.forProtocol(HTTPChannel)
    # Request.finish expects the factory to have a 'log' method.
    server_factory.log = _log_request

    server_tls_factory = TLSMemoryBIOFactory(
        ServerTLSContext(), isClient=False, wrappedFactory=server_factory
    )

    return server_tls_factory.buildProtocol(None)
示例#46
0
def main():
    conn_counter = ConnCounter()

    path = sys.argv[1] if len(sys.argv) > 1 else '/tmp/p4crap-server.socket'
    reactor.listenUNIX(path, pb.PBServerFactory(conn_counter))

    serverport = int(sys.argv[2]) if len(sys.argv) > 2 else 8000
    load_factor = float(sys.argv[3]) if len(sys.argv) > 3 else 10
    f = Factory.forProtocol(ConnCounterProtocol)
    f.conn_counter = conn_counter
    f.load_factor = load_factor
    reactor.listenTCP(serverport, f)
    load_sampler = task.LoopingCall(conn_counter.sample_load)
    load_sampler.start(LOAD_SAMPLING_INTERVAL)

    reactor.callWhenRunning(print, '[server] reactor running')
    reactor.run()
示例#47
0
    def dataReceived(self,data):

        print data
        #convert string to original data type
        index = ast.literal_eval(data)
        destination_IP = index["NEVIP"]

        print  "\n""\n [Recieved from WEB2PY(TREE-TOP)] got \n" + data
        print destination_IP

        endpoint = TCP4ClientEndpoint(reactor,"%s" % destination_IP ,8001)

        #NOTE: nested function
        def clientProtocol():
            return Clientp(data)

        endpoint.connect(Factory.forProtocol(clientProtocol))
示例#48
0
    def passTo(self, host, protocol):
        orig_socket = protocol.transport.socket

        if not host:
            host = b'default'
        try:
            for vhost in self.vhosts:
                if vhost.hostname.match(host):
                    dest_socket = vhost.socket
                    endpoint = UNIXClientEndpoint(reactor, dest_socket)
                    connected = endpoint.connect(Factory.forProtocol(Protocol))
                    connected.addCallback(
                        partial(self.passClientTo, orig_socket))
                    connected.addBoth(partial(self.disconnect, protocol))
                    return
        finally:
            pass
示例#49
0
def connectableEndpoint(debug=False):
    """
    Create an endpoint that can be fired on demand.

    @param debug: A flag; whether to dump output from the established
        connection to stdout.
    @type debug: L{bool}

    @return: A client endpoint, and an object that will cause one of the
        L{Deferred}s returned by that client endpoint.
    @rtype: 2-L{tuple} of (L{IStreamClientEndpoint}, L{ConnectionCompleter})
    """
    reactor = MemoryReactorClock()
    clientEndpoint = TCP4ClientEndpoint(reactor, "0.0.0.0", 4321)
    serverEndpoint = TCP4ServerEndpoint(reactor, 4321)
    serverEndpoint.listen(Factory.forProtocol(Protocol))
    return clientEndpoint, ConnectionCompleter(reactor)
示例#50
0
    def connect(self, reconnecting=False):
        if self.connecting and not reconnecting:
            return
        self.connecting = True
        end_point = TCP4ClientEndpoint(reactor, self.host, self.port, 10)
        d = end_point.connect(Factory.forProtocol(GraphiteProtocol))

        def success(connection):
            self.connecting = False
            log.msg('Connected to %s' % self)
            self.connection = connection

        def failed(error):
            log.err('Connect to %s failed: %s' % (self, error))
            reactor.callLater(10, self.connect, True)

        d.addCallbacks(success, failed)
示例#51
0
    def _authorized_request(self, token, headers):
        """
        Get an agent using ``authenticate_with_serviceaccount`` and issue a
        request with it.

        :return bytes: The bytes of the request the agent issues.
        """
        server = AccumulatingProtocol()
        factory = Factory.forProtocol(lambda: server)
        factory.protocolConnectionMade = None

        reactor = MemoryReactor()
        reactor.listenTCP(80, factory)

        t = FilePath(self.useFixture(TempDir()).join(b""))
        serviceaccount = t.child(b"serviceaccount")
        serviceaccount.makedirs()

        serviceaccount.child(b"ca.crt").setContent(_CA_CERT_PEM)
        serviceaccount.child(b"token").setContent(token)

        self.patch(
            os,
            "environ",
            {
                b"KUBERNETES_SERVICE_HOST": b"example.invalid.",
                b"KUBERNETES_SERVICE_PORT": b"443",
            },
        )

        agent = authenticate_with_serviceaccount(
            reactor,
            path=serviceaccount.path,
        )
        agent.request(b"GET", b"http://example.invalid.", headers)

        [(host, port, factory, _, _)] = reactor.tcpClients

        self.expectThat((host, port), Equals((b"example.invalid.", 80)))

        pump = ConnectionCompleter(reactor).succeedOnce()
        pump.pump()

        return server.data
示例#52
0
def main(reactor):
    pem = generate_certs.and_generate()
    caPem = FilePath(b"ca-private-cert.pem").getContent()
    clientEndpoint = SSL4ClientEndpoint(
        reactor,
        u"localhost",
        4321,
        optionsForClientTLS(u"the-authority", Certificate.loadPEM(caPem),
                            PrivateCertificate.loadPEM(pem)),
    )
    clientEndpoint = SSL4ClientEndpoint(
        reactor,
        u"localhost",
        4321,
        optionsForClientTLS(u"the-authority", Certificate.loadPEM(caPem),
                            PrivateCertificate.loadPEM(pem)),
    )
    proto = yield clientEndpoint.connect(Factory.forProtocol(SendAnyData))
    yield proto.deferred
示例#53
0
文件: _impl.py 项目: glyph/secretly
    def askForPassword(self, reactor, prompt, title, description):
        """
        The documentation appears to be here only:
        https://github.com/gpg/pinentry/blob/287d40e879f767dbcb3d19b3629b872c08d39cf4/pinentry/pinentry.c#L1444-L1464

        TODO: multiple backends for password-prompting.
        """
        argv = self.argv()
        assuan = yield (ProcessEndpoint(reactor, argv[0], argv,
                                        os.environ.copy()).connect(
                                            Factory.forProtocol(SimpleAssuan)))
        try:
            yield assuan.issueCommand(b"SETPROMPT", prompt.encode("utf-8"))
            yield assuan.issueCommand(b"SETTITLE", title.encode("utf-8"))
            yield assuan.issueCommand(b"SETDESC", description.encode("utf-8"))
            response = yield assuan.issueCommand(b"GETPIN")
        finally:
            assuan.issueCommand(b"BYE")
        returnValue(response.data.decode("utf-8"))
def main():
    try:
        # Create end point
        endpoint = TCP4ServerEndpoint(
            reactor=reactor,
            port=8000,
            interface='127.0.0.1',
        )

        # Start listening
        endpoint.listen(Factory.forProtocol(EchoProtocol))

        # Run reactor
        reactor.run()

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Stop gracefully
        pass
示例#55
0
    def __init__(
        self,
        host: str,
        port: int,
        maximum_buffer: int = 1000,
        level=logging.NOTSET,
        _reactor=None,
    ):
        super().__init__(level=level)
        self.host = host
        self.port = port
        self.maximum_buffer = maximum_buffer

        self._buffer = deque()  # type: Deque[logging.LogRecord]
        self._connection_waiter = None  # type: Optional[Deferred]
        self._producer = None  # type: Optional[LogProducer]

        # Connect without DNS lookups if it's a direct IP.
        if _reactor is None:
            from twisted.internet import reactor

            _reactor = reactor

        try:
            ip = ip_address(self.host)
            if isinstance(ip, IPv4Address):
                endpoint = TCP4ClientEndpoint(
                    _reactor, self.host,
                    self.port)  # type: IStreamClientEndpoint
            elif isinstance(ip, IPv6Address):
                endpoint = TCP6ClientEndpoint(_reactor, self.host, self.port)
            else:
                raise ValueError("Unknown IP address provided: %s" %
                                 (self.host, ))
        except ValueError:
            endpoint = HostnameEndpoint(_reactor, self.host, self.port)

        factory = Factory.forProtocol(Protocol)
        self._service = ClientService(endpoint, factory, clock=_reactor)
        self._service.startService()
        self._stopping = False
        self._connect()
示例#56
0
 def test_validUNIXHeaderResolves_getPeerHost(self):
     """
     Test if UNIX headers result in the correct host and peer data.
     """
     factory = HAProxyWrappingFactory(Factory.forProtocol(StaticProtocol))
     proto = factory.buildProtocol(
         address.UNIXAddress(b'/home/test/sockets/server.sock'), )
     transport = StringTransportWithDisconnection()
     proto.makeConnection(transport)
     proto.dataReceived(self.UNIXHEADER)
     self.assertEqual(proto.getPeer().name, b'/home/tests/mysockets/sock')
     self.assertEqual(
         proto.wrappedProtocol.transport.getPeer().name,
         b'/home/tests/mysockets/sock',
     )
     self.assertEqual(proto.getHost().name, b'/home/tests/mysockets/sock')
     self.assertEqual(
         proto.wrappedProtocol.transport.getHost().name,
         b'/home/tests/mysockets/sock',
     )
示例#57
0
    def start(self) -> None:

        # Connect without DNS lookups if it's a direct IP.
        try:
            ip = ip_address(self.host)
            if isinstance(ip, IPv4Address):
                endpoint = TCP4ClientEndpoint(
                    self.hs.get_reactor(), self.host, self.port
                )
            elif isinstance(ip, IPv6Address):
                endpoint = TCP6ClientEndpoint(
                    self.hs.get_reactor(), self.host, self.port
                )
        except ValueError:
            endpoint = HostnameEndpoint(self.hs.get_reactor(), self.host, self.port)

        factory = Factory.forProtocol(Protocol)
        self._service = ClientService(endpoint, factory, clock=self.hs.get_reactor())
        self._service.startService()
        self._connect()
示例#58
0
def factoryFromFlow(flow):
    """
    Convert a flow function into an L{IProtocolFactory}.

    A "flow function" is a function which takes a L{fount <IFount>} and an
    L{drain <IDrain>}.

    L{factoryFromFlow} takes such a function and creates an L{IProtocolFactory}
    which, upon each new connection, provides the flow function with an
    L{IFount} and an L{IDrain} representing the read end and the write end of
    the incoming connection, respectively.

    @param flow: a 2-argument callable, taking (fount, drain).
    @type flow: L{callable}

    @return: a protocol factory.
    @rtype: L{IProtocolFactory}
    """
    from twisted.internet.protocol import Factory
    return Factory.forProtocol(lambda: _ProtocolPlumbing(flow))
示例#59
0
class Sartorious(Machine):

    protocolFactory = Factory.forProtocol(QueuedLineReceiver)
    name = "Sartorious Balance"

    def setup(self):

        # setup variables
        self.weight = Stream(title="Weight", type=float, unit="g")

    def start(self):
        def interpret_weight(result: str) -> float:

            result_value = float((result[-14:-4]).replace(" ", ""))

            self.weight._push(result_value)

        to_monitor = []

        def addMonitor(command, fn, variable: Stream):
            def interpret(result):
                variable._push(fn(result), now())

            to_monitor.append((command, interpret))

        addMonitor("P", interpret_weight, self.weight)

        def monitor():
            for cmd, fn in to_monitor:
                self.protocol.write(cmd).addCallback(fn)

        self._monitor = self._tick(monitor, 1)

    def stop(self):
        self._stopTicks()

    def reset(self):
        return defer.succeed('OK')

    def tare(self):
        return self.protocol.write("T", expectReply=False, wait=5)
示例#60
0
    def connect_samsung(self, p_device_obj):
        def cb_connectedNow(SamsungClient):
            LOG.debug('Connected Now')
            SamsungClient.send_command('1PWRQSTN')

        def eb_failed(fail_reason):
            LOG.warn(
                "initial Samsung connection failed: {}".format(fail_reason))
            l_ReconnectingService.stopService()

        l_reactor = self.m_pyhouse_obj._Twisted.Reactor
        try:
            # l_host = convert.long_to_str(p_device_obj.IPv4)
            l_host = 'samsung-tv'
            l_port = p_device_obj.Port
            l_endpoint_str = 'tcp:{}:port={}'.format(l_host, l_port)
            l_endpoint = clientFromString(l_reactor, l_endpoint_str)
            l_factory = Factory.forProtocol(SamsungProtocol)
            l_ReconnectingService = ClientService(l_endpoint, l_factory)
            l_ReconnectingService.setName('Samsung ')
            waitForConnection = l_ReconnectingService.whenConnected(
                failAfterFailures=1)
            LOG.debug('Endpoint: {}'.format(l_endpoint_str))
            LOG.debug('{}'.format(
                PrettyFormatAny.form(l_endpoint, 'Endpoint', 190)))
            LOG.debug('{}'.format(
                PrettyFormatAny.form(l_factory, 'Factory', 190)))
            LOG.debug('{}'.format(
                PrettyFormatAny.form(l_ReconnectingService, 'ReconnectService',
                                     190)))

            waitForConnection.addCallbacks(cb_connectedNow, eb_failed)
            l_ReconnectingService.startService()
            p_device_obj._Endpoint = l_endpoint
            p_device_obj._Factory = l_factory
            p_device_obj._isRunning = True
            LOG.info("Started Samsung - Host:{}; Port:{}".format(
                l_host, l_port))
        except Exception as e_err:
            LOG.error('Error found: {}'.format(e_err))
        pass