Exemple #1
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            var connections = TcpConnectionManager.GetCurrentTcpConnections();

            //this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = connections;
        }
Exemple #2
0
        private Guid AddSubscription(Guid replicaId, bool isPromotable, out TcpConnectionManager manager)
        {
            var tcpConn = new DummyTcpConnection()
            {
                ConnectionId = replicaId
            };

            manager = new TcpConnectionManager(
                "Test Subscription Connection manager", TcpServiceType.External, new ClientTcpDispatcher(),
                InMemoryBus.CreateTest(), tcpConn, InMemoryBus.CreateTest(),
                new InternalAuthenticationProvider(
                    new Core.Helpers.IODispatcher(InMemoryBus.CreateTest(), new NoopEnvelope()),
                    new StubPasswordHashAlgorithm(), 1, false),
                new AuthorizationGateway(new TestAuthorizationProvider()),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { },
                _connectionPendingSendBytesThreshold, _connectionQueueSizeThreshold);
            var subRequest = new ReplicationMessage.ReplicaSubscriptionRequest(
                Guid.NewGuid(),
                new NoopEnvelope(),
                manager,
                0,
                Guid.NewGuid(),
                new Epoch[0],
                PortsHelper.GetLoopback(),
                LeaderId,
                replicaId,
                isPromotable);

            Service.Handle(subRequest);
            return(tcpConn.ConnectionId);
        }
Exemple #3
0
        static void ConnectAsClient()
        {
            int count = 0;

            var server     = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3666);
            var connection = new TcpConnectionManager("ClientConnection", Guid.NewGuid(),
                                                      server,
                                                      new TcpClientConnector(),
                                                      false,
                                                      null,
                                                      false,
                                                      new EchoFramer(),
                                                      (c, d) =>
            {
                var message = UTF8NoBom.GetString(d);
                Console.WriteLine("Client: message from server: {0}", message);

                var messageCount = Interlocked.Increment(ref count);
                c.Send(UTF8NoBom.GetBytes(string.Format("client says: {0} message received.", messageCount)));

                if (messageCount == 50)
                {
                    c.Close();
                }
            },
                                                      (c) => {
                Console.WriteLine("Client: connected.");
                c.Send(UTF8NoBom.GetBytes("Hello server."));
            },
                                                      (c, e) => {
                Console.WriteLine("Client: connection lost.");
            });

            connection.StartReceiving();
        }
        public void TestCallbacks()
        {
            log4net.Config.XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));

            TcpConnectionManager connectionManager = new TcpConnectionManager();

            connectionManager.OnConnectionFound += HandleConnectionManagerOnConnectionFound;

            incomingGenerators = new List <TcpStreamGenerator>();
//            outgoingGenerators = new List<TcpStreamGenerator>();

            // open the offline file
            var dev = new CaptureFileReaderDevice(captureFilename);

            dev.Open();
            Assert.True(dev != null, "failed to open " + captureFilename);

            RawCapture rawCapture;

            while ((rawCapture = dev.GetNextPacket()) != null)
            {
                var p         = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
                var tcpPacket = p.Extract <TcpPacket>();
                Console.WriteLine("tcpPacket.PayloadData.Length {0}", tcpPacket.PayloadData.Length);

                connectionManager.ProcessPacket(rawCapture.Timeval, tcpPacket);
            }

            dev.Close();

            int expectedCallbackCount = 5;

            Assert.Equal(expectedCallbackCount, callbackCount);
        }
Exemple #5
0
        private void ConnectToMaster(VNodeInfo master)
        {
            Debug.Assert(_state == VNodeState.PreReplica);

            var masterEndPoint = GetMasterEndPoint(master, _useSsl);

            if (_connection != null)
            {
                _connection.Stop(string.Format("Reconnecting from old master [{0}] to new master: [{1}].",
                                               _connection.RemoteEndPoint, masterEndPoint));
            }

            _connection = new TcpConnectionManager(_useSsl ? "master-secure" : "master-normal",
                                                   Guid.NewGuid(),
                                                   _tcpDispatcher,
                                                   _publisher,
                                                   masterEndPoint,
                                                   _connector,
                                                   _useSsl,
                                                   _sslTargetHost,
                                                   _sslValidateServer,
                                                   _networkSendQueue,
                                                   _authProvider,
                                                   _heartbeatInterval,
                                                   _heartbeatTimeout,
                                                   OnConnectionEstablished,
                                                   OnConnectionClosed);
            _connection.StartReceiving();
        }
        when_send_queue_size_is_larger_than_threshold_should_close_connection()
        {
            var mre = new ManualResetEventSlim();

            var messageSize = _connectionPendingSendBytesThreshold;
            var evnt        = new EventRecord(0, 0, Guid.NewGuid(), Guid.NewGuid(), 0, 0, "testStream", 0, DateTime.Now,
                                              PrepareFlags.None, "eventType", new byte[messageSize], new byte[0]);
            var record  = ResolvedEvent.ForUnresolvedEvent(evnt, null);
            var message = new ClientMessage.ReadEventCompleted(Guid.NewGuid(), "testStream", ReadEventResult.Success,
                                                               record, StreamMetadata.Empty, false, "");

            var dummyConnection = new DummyTcpConnection();

            dummyConnection.SendQueueSize = ESConsts.MaxConnectionQueueSize + 1;

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.External, new ClientTcpDispatcher(2000),
                InMemoryBus.CreateTest(), dummyConnection, InMemoryBus.CreateTest(),
                new InternalAuthenticationProvider(InMemoryBus.CreateTest(),
                                                   new Core.Helpers.IODispatcher(InMemoryBus.CreateTest(), new NoopEnvelope()), null, 1, false),
                new AuthorizationGateway(new TestAuthorizationProvider()),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { mre.Set(); },
                ESConsts.UnrestrictedPendingSendBytes, ESConsts.MaxConnectionQueueSize);

            tcpConnectionManager.SendMessage(message);

            if (!mre.Wait(2000))
            {
                Assert.Fail("Timed out waiting for connection to close");
            }
        }
        private void ProcessPackets(ICaptureDevice dev,
                                    TcpConnectionManager tcpConnectionManager)
        {
            // reset the expected message index at the start of the test run
            expectedMessageIndex = 0;

            GetPacketStatus status;
            PacketCapture   e;

            while ((status = dev.GetNextPacket(out e)) == GetPacketStatus.PacketRead)
            {
                var rawCapture = e.GetPacket();
                var p          = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

                var tcpPacket = p.Extract <TcpPacket>();

                // skip non-tcp packets, http is a tcp based protocol
                if (p == null)
                {
                    continue;
                }

                log.Debug("passing packet to TcpConnectionManager");
                tcpConnectionManager.ProcessPacket(rawCapture.Timeval,
                                                   tcpPacket);
            }

            // did we get all of the messages?
            Assert.Equal(expectedMessages.Count, expectedMessageIndex);
        }
        public void when_handling_trusted_write_on_internal_service()
        {
            ManualResetEvent waiter = new ManualResetEvent(false);
            ClientMessage.WriteEvents publishedWrite = null;
            var evnt = new Event(Guid.NewGuid(), "TestEventType", true, new byte[] { }, new byte[] { });
            var write = new TcpClientMessageDto.WriteEvents(
                Guid.NewGuid().ToString(),
                ExpectedVersion.Any,
                new[] { new TcpClientMessageDto.NewEvent(evnt.EventId.ToByteArray(), evnt.EventType, evnt.IsJson ? 1 : 0, 0, evnt.Data, evnt.Metadata) },
                false);

            var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), write.Serialize());
            var dummyConnection = new DummyTcpConnection();
            var publisher = InMemoryBus.CreateTest();

            publisher.Subscribe(new AdHocHandler<ClientMessage.WriteEvents>(x => {
                publishedWrite = x;
                waiter.Set();
            }));

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.Internal, new ClientTcpDispatcher(),
                publisher, dummyConnection, publisher, new InternalAuthenticationProvider(new Core.Helpers.IODispatcher(publisher, new NoopEnvelope()), new StubPasswordHashAlgorithm(), 1),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { });

            tcpConnectionManager.ProcessPackage(package);

            if (!waiter.WaitOne(TimeSpan.FromSeconds(5)))
            {
                throw new Exception("Timed out waiting for events.");
            }
            Assert.AreEqual(evnt.EventId, publishedWrite.Events.First().EventId, "Expected the published write to be the event that was sent through the tcp connection manager to be the event {0} but got {1}", evnt.EventId, publishedWrite.Events.First().EventId);
        }
            public ReplicaSubscriptionRequest(Guid correlationId,
                                              IEnvelope envelope,
                                              TcpConnectionManager connection,
                                              long logPosition,
                                              Guid chunkId,
                                              Epoch[] lastEpochs,
                                              IPEndPoint replicaEndPoint,
                                              Guid masterId,
                                              Guid subscriptionId,
                                              bool isPromotable)
            {
                Ensure.NotEmptyGuid(correlationId, "correlationId");
                Ensure.NotNull(envelope, "envelope");
                Ensure.NotNull(connection, "connection");
                Ensure.Nonnegative(logPosition, "logPosition");
                Ensure.NotNull(lastEpochs, "lastEpochs");
                Ensure.NotNull(replicaEndPoint, "ReplicaEndPoint");
                Ensure.NotEmptyGuid(masterId, "masterId");
                Ensure.NotEmptyGuid(subscriptionId, "subscriptionId");

                CorrelationId   = correlationId;
                Envelope        = envelope;
                Connection      = connection;
                LogPosition     = logPosition;
                ChunkId         = chunkId;
                LastEpochs      = lastEpochs;
                ReplicaEndPoint = replicaEndPoint;
                MasterId        = masterId;
                SubscriptionId  = subscriptionId;
                IsPromotable    = isPromotable;
            }
Exemple #10
0
 public static void Destroy()
 {
     Logging.WriteLine("Destroying PhoenixEmu environment...");
     if (GetGame() != null)
     {
         GetGame().Destroy();
         Game = null;
     }
     if (GetConnectionManager() != null)
     {
         Logging.WriteLine("Destroying connection manager.");
         GetConnectionManager().GetListener().Destroy();
         GetConnectionManager().DestroyManager();
         ConnectionManager = null;
     }
     if (GetDatabase() != null)
     {
         try
         {
             Logging.WriteLine("Destroying database manager.");
             MySqlConnection.ClearAllPools();
             DatabaseManager = null;
         }
         catch { }
     }
     Logging.WriteLine("Uninitialized successfully. Closing.");
 }
Exemple #11
0
        public void when_handling_trusted_write_on_internal_service()
        {
            ManualResetEvent waiter = new ManualResetEvent(false);

            ClientMessage.WriteEvents publishedWrite = null;
            var evnt  = new Event(Guid.NewGuid(), "TestEventType", true, new byte[] { }, new byte[] { });
            var write = new TcpClientMessageDto.WriteEvents(
                Guid.NewGuid().ToString(),
                ExpectedVersion.Any,
                new[] { new TcpClientMessageDto.NewEvent(evnt.EventId.ToByteArray(), evnt.EventType, evnt.IsJson ? 1 : 0, 0, evnt.Data, evnt.Metadata) },
                false);

            var package         = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), write.Serialize());
            var dummyConnection = new DummyTcpConnection();
            var publisher       = InMemoryBus.CreateTest();

            publisher.Subscribe(new AdHocHandler <ClientMessage.WriteEvents>(x => {
                publishedWrite = x;
                waiter.Set();
            }));

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.Internal, new ClientTcpDispatcher(),
                publisher, dummyConnection, publisher, new InternalAuthenticationProvider(new Core.Helpers.IODispatcher(publisher, new NoopEnvelope()), new StubPasswordHashAlgorithm(), 1),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { });

            tcpConnectionManager.ProcessPackage(package);

            if (!waiter.WaitOne(TimeSpan.FromSeconds(5)))
            {
                throw new Exception("Timed out waiting for events.");
            }
            Assert.AreEqual(evnt.EventId, publishedWrite.Events.First().EventId, "Expected the published write to be the event that was sent through the tcp connection manager to be the event {0} but got {1}", evnt.EventId, publishedWrite.Events.First().EventId);
        }
        public void when_handling_trusted_write_on_external_service()
        {
            var package = new TcpPackage(TcpCommand.WriteEvents, TcpFlags.TrustedWrite, Guid.NewGuid(), null, null,
                                         new byte[] { });

            var dummyConnection = new DummyTcpConnection();

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.External, new ClientTcpDispatcher(2000),
                InMemoryBus.CreateTest(), dummyConnection, InMemoryBus.CreateTest(),
                new InternalAuthenticationProvider(
                    InMemoryBus.CreateTest(), new Core.Helpers.IODispatcher(InMemoryBus.CreateTest(), new NoopEnvelope()),
                    new StubPasswordHashAlgorithm(), 1, false),
                new AuthorizationGateway(new TestAuthorizationProvider()),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { },
                _connectionPendingSendBytesThreshold, _connectionQueueSizeThreshold);

            tcpConnectionManager.ProcessPackage(package);

            var data            = dummyConnection.ReceivedData.Last();
            var receivedPackage = TcpPackage.FromArraySegment(data);

            Assert.AreEqual(receivedPackage.Command, TcpCommand.BadRequest, "Expected Bad Request but got {0}",
                            receivedPackage.Command);
        }
        public void Test()
        {
            connectionStatistics.OnMeasurementFound += HandleConnectionStatisticsOnMeasurementFound;
            connectionStatistics.OnMeasurementEvent += HandleConnectionStatisticsOnMeasurementEvent;
            captureFilename = capturePre + captureFN;

            // open the offline file
            var dev = new CaptureFileReaderDevice(captureFilename);

            dev.Open();
            Assert.True(dev != null, "failed to open " + captureFilename);

            var tcpConnectionManager = new TcpConnectionManager();

            tcpConnectionManager.OnConnectionFound += HandleTcpConnectionManagerOnConnectionFound;

            RawCapture rawCapture;

            while ((rawCapture = dev.GetNextPacket()) != null)
            {
                var p         = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
                var tcpPacket = p.Extract <TcpPacket>();

                if (tcpPacket != null)
                {
//                    Console.WriteLine("{0}", tcpPacket.ToString());

                    tcpConnectionManager.ProcessPacket(rawCapture.Timeval, tcpPacket);
                }
            }
        }
        when_send_queue_size_is_smaller_than_threshold_should_not_close_connection()
        {
            var mre = new ManualResetEventSlim();

            var messageSize = _connectionPendingSendBytesThreshold;
            var evnt        = new EventRecord(0, 0, Guid.NewGuid(), Guid.NewGuid(), 0, 0, "testStream", 0, DateTime.Now,
                                              PrepareFlags.None, "eventType", new byte[messageSize], new byte[0]);
            var record  = ResolvedEvent.ForUnresolvedEvent(evnt, null);
            var message = new ClientMessage.ReadEventCompleted(Guid.NewGuid(), "testStream", ReadEventResult.Success,
                                                               record, StreamMetadata.Empty, false, "");

            var dummyConnection = new DummyTcpConnection();

            dummyConnection.SendQueueSize = ESConsts.MaxConnectionQueueSize - 1;

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.External, new ClientTcpDispatcher(2000),
                InMemoryBus.CreateTest(), dummyConnection, InMemoryBus.CreateTest(),
                new InternalAuthenticationProvider(InMemoryBus.CreateTest(),
                                                   new Core.Helpers.IODispatcher(InMemoryBus.CreateTest(), new NoopEnvelope()), null, 1, false),
                new AuthorizationGateway(new TestAuthorizationProvider()),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { mre.Set(); },
                ESConsts.UnrestrictedPendingSendBytes, ESConsts.MaxConnectionQueueSize);

            tcpConnectionManager.SendMessage(message);

            var data            = dummyConnection.ReceivedData.Last();
            var receivedPackage = TcpPackage.FromArraySegment(data);

            Assert.AreEqual(receivedPackage.Command, TcpCommand.ReadEventCompleted,
                            "Expected ReadEventCompleted but got {0}", receivedPackage.Command);
        }
 public TestNode(RoutingManager routingManager, TcpConnectionManager connectionManager, DataManager dataManager, EncryptionManager encryptionManager)
 {
     this.routingManager    = routingManager;
     this.connectionManager = connectionManager;
     this.dataManager       = dataManager;
     this.encryptionManager = encryptionManager;
 }
Exemple #16
0
        when_limit_pending_and_sending_message_larger_than_pending_bytes_threshold_but_no_bytes_pending_should_not_close_connection()
        {
            var messageSize = _connectionPendingSendBytesThreshold + 1000;
            var evnt        = new EventRecord(0, 0, Guid.NewGuid(), Guid.NewGuid(), 0, 0, "testStream", 0, DateTime.Now,
                                              PrepareFlags.None, "eventType", new byte[messageSize], new byte[0]);
            var record  = ResolvedEvent.ForUnresolvedEvent(evnt, null);
            var message = new ClientMessage.ReadEventCompleted(Guid.NewGuid(), "testStream", ReadEventResult.Success,
                                                               record, StreamMetadata.Empty, false, "");

            var dummyConnection = new DummyTcpConnection();

            dummyConnection.PendingSendBytes = 0;

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.External, new ClientTcpDispatcher(),
                InMemoryBus.CreateTest(), dummyConnection, InMemoryBus.CreateTest(),
                new InternalAuthenticationProvider(
                    new Core.Helpers.IODispatcher(InMemoryBus.CreateTest(), new NoopEnvelope()), null, 1, false),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { },
                _connectionPendingSendBytesThreshold, _connectionQueueSizeThreshold);

            tcpConnectionManager.SendMessage(message);

            var data            = dummyConnection.ReceivedData.Last();
            var receivedPackage = TcpPackage.FromArraySegment(data);

            Assert.AreEqual(receivedPackage.Command, TcpCommand.ReadEventCompleted,
                            "Expected ReadEventCompleted but got {0}", receivedPackage.Command);
        }
Exemple #17
0
        public static void Main()
        {
            // Usage - first, instantiate an IDevice.
            // Then, instantiate an IConnection, and pass both the device and connection into
            // an instantiated IConnectionManager.  Then pass the IConnectionManager to an instantiated
            // IController. Finally, initialize the device, passing in your controller.
            // Any components should be added in your particular Device class
            // Any commands added should be placed in the CommandHandler class - instructions included.

            var device            = new Device();
            var serverConnection  = new SingleDataConnection(IPAddress.Parse("192.168.168.101"), 420);
            var connectionManager = new TcpConnectionManager(device, serverConnection)
            {
                KeepAliveActive = true, KeepAliveTime = 30000
            };
            var netduino = new NetDuinoPlus2(connectionManager);

            device.Init(netduino);

            while (true)
            {
                Debug.Print("Available RAM: " + Debug.GC(true));
                Thread.Sleep(30000);
            }
        }
Exemple #18
0
 private void Disconnect()
 {
     if (_connection != null)
     {
         _connection.Stop(string.Format("Node state changed to {0}. Closing replication connection.", _state));
         _connection = null;
     }
 }
			public ReplicaSubscription(IPublisher tcpSendPublisher, TcpConnectionManager connection,
				Guid subscriptionId, EndPoint replicaEndPoint, bool isPromotable) {
				_tcpSendPublisher = tcpSendPublisher;
				_connection = connection;
				SubscriptionId = subscriptionId;
				ReplicaEndPoint = replicaEndPoint;
				IsPromotable = isPromotable;
			}
 public BluemeshNode(RoutingManager routingManager, TcpConnectionManager connectionManager, DataManager dataManager, EncryptionManager encryptionManager, bool doLogMap)
 {
     this.RoutingManager    = routingManager;
     this.ConnectionManager = connectionManager;
     this.DataManager       = dataManager;
     this.EncryptionManager = encryptionManager;
     this.DoLogMap          = doLogMap;
 }
        private void UnsubscribeFromStream(string eventStreamId, Guid correlationId, TcpConnectionManager connection)
        {
            List <Tuple <Guid, TcpConnectionManager> > subscribers;

            if (_subscriptions.TryGetValue(eventStreamId, out subscribers))
            {
                subscribers.Remove(Tuple.Create(correlationId, connection));
            }
        }
Exemple #22
0
 private void OnConnectionClosed(TcpConnectionManager connectionManager, SocketError error)
 {
     if (_running)
     {
         _bus.Publish(new ProjectionMessage.CoreService.Stop()); //TODO: duplicate stop sent here
         Thread.Sleep(1000);                                     //TODO: use scheduler service
         Connect();
     }
 }
Exemple #23
0
        private static HackerNode CreateNode(IConnectionConfig connectionConfig, IRoutingConfig routingConfig, string storagePath)
        {
            var encryptionManager = new EncryptionManager(((TcpAddress)connectionConfig.LocalAddress).Endpoint, connectionConfig.KeySendCooldown);
            var connectionManager = new TcpConnectionManager(connectionConfig, routingConfig, encryptionManager);
            var routingManager    = new RoutingManager(connectionManager, routingConfig);
            var dataManager       = new DataManager(LoadStorage(storagePath) ?? new DataStorage(), storagePath, routingManager, encryptionManager);

            return(new HackerNode(routingManager, connectionManager, dataManager, encryptionManager, routingConfig.DoLogMap));
        }
Exemple #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerModeViewModel"/> class.
        /// </summary>
        /// <param name="viewShell">The view shell.</param>
        public ServerModeViewModel(ViewShellBaseViewModel viewShell) : base(viewShell)
        {
            ViewShellViewModel shell = (ViewShellViewModel)this.ViewShell;

            TcpConnectionManager tcpConnectionManager = new TcpConnectionManager(shell.TcpListener, 1600);

            this.server  = new Server(tcpConnectionManager);
            shell.Server = this.server;
            this.server.Start();
        }
Exemple #25
0
 public ServerNode(int tcpPort, List <IPEndPoint> knownEndPoints, DataManager dataManager)
 {
     _knownEndPoints       = knownEndPoints;
     _dataManager          = dataManager;
     _tcpConnectionManager = new TcpConnectionManager(tcpPort, new DefaultWireProtocol());
     _tcpConnectionManager.ConnectorConnected += OnTcpClientConnected;
     _tcpConnectors = new List <IConnector>();
     _knowedServerNodesConnectors = new List <IConnector>();
     _totalDataQunatity           = BytesHelper.GetDataSizeInBytes(_dataManager.GetEmployees().ToList());
 }
Exemple #26
0
        public TcpNETServer(IParamsTcpServer parameters, TcpHandler handler = null)
        {
            _parameters        = parameters;
            _connectionManager = new TcpConnectionManager();

            _handler = handler ?? new TcpHandler(_parameters);
            _handler.ConnectionEvent += OnConnectionEvent;
            _handler.MessageEvent    += OnMessageEventAsync;
            _handler.ErrorEvent      += OnErrorEvent;
            _handler.ServerEvent     += OnServerEvent;
        }
Exemple #27
0
        public void Setup()
        {
            _dispatcher = new ClientTcpDispatcher();

            var dummyConnection = new DummyTcpConnection();

            _connection = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.External, new ClientTcpDispatcher(),
                InMemoryBus.CreateTest(), dummyConnection, InMemoryBus.CreateTest(), new InternalAuthenticationProvider(
                    new Core.Helpers.IODispatcher(InMemoryBus.CreateTest(), new NoopEnvelope()), new StubPasswordHashAlgorithm(), 1),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { }, Opts.ConnectionPendingSendBytesThresholdDefault);
        }
        /// <summary>
        /// Constructs an instance of the SyncSocketReadingStream class.
        /// </summary>
        /// <param name="tcpConnectionManager">TCP Connection Manager.</param>
        /// <param name="tcpSocketInfo">The connection.</param>
        /// <param name="receiveTimeout">The moment at which the message must be received entirely.</param>
        /// <param name="automaticallyContinueReading">Indicates whether this instance will automatically initiate reading of the next message from the specified connection.</param>
        public SyncSocketReadingStream(TcpConnectionManager tcpConnectionManager, TcpSocketInfo tcpSocketInfo, int receiveTimeout, bool automaticallyContinueReading)
        {
            this._readBuffer = BufferPool.ObtainBuffer();

            this._tcpConnectionManager         = tcpConnectionManager;
            this._tcpSocketInfo                = tcpSocketInfo;
            this._receiveTimeout               = receiveTimeout;
            this._automaticallyContinueReading = automaticallyContinueReading;

            // first, complete receiving of the first header
            // it may read up the entire message and release the underlying connection
            ReadNextPortion(true);
        }
Exemple #29
0
        public TcpNETServer(IParamsTcpServer parameters,
                            byte[] certificate,
                            string certificatePassword,
                            TcpHandler handler = null)
        {
            _parameters        = parameters;
            _connectionManager = new TcpConnectionManager();

            _handler = handler ?? new TcpHandler(_parameters, certificate, certificatePassword);
            _handler.ConnectionEvent += OnConnectionEvent;
            _handler.MessageEvent    += OnMessageEventAsync;
            _handler.ErrorEvent      += OnErrorEvent;
            _handler.ServerEvent     += OnServerEvent;
        }
Exemple #30
0
        public TcpMessage.TcpSend[] GetTcpSendsFor(TcpConnectionManager connection)
        {
            var sentMessages = new List <TcpMessage.TcpSend>();

            while (TcpSends.TryDequeue(out var msg))
            {
                if (msg.ConnectionManager == connection)
                {
                    sentMessages.Add(msg);
                }
            }

            return(sentMessages.ToArray());
        }
Exemple #31
0
        public void ConnectionCreation()
        {
            // store the logging value
            var oldThreshold = LoggingConfiguration.GlobalLoggingLevel;

            // disable logging to improve performance
            LoggingConfiguration.GlobalLoggingLevel = log4net.Core.Level.Off;

            string captureFN       = "tcp_test.pcap";
            string captureFilename = capturePre + captureFN;

            // open the offline file
            var dev = new CaptureFileReaderDevice(captureFilename);

            dev.Open();
            Assert.True(dev != null, "failed to open " + captureFilename);

            var tcpConnectionManager = new TcpConnectionManager();

            tcpConnectionManager.OnConnectionFound += HandleTcpConnectionManagerOnConnectionFound;

            connectionsFound = 0;
            var             startTime = DateTime.Now;
            PacketCapture   e;
            GetPacketStatus status;

            while ((status = dev.GetNextPacket(out e)) == GetPacketStatus.PacketRead)
            {
                var rawCapture = e.GetPacket();
                var p          = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
                var tcpPacket  = p.Extract <TcpPacket>();

                if (tcpPacket != null)
                {
//                    Console.WriteLine("{0}", tcpPacket.ToString());

                    tcpConnectionManager.ProcessPacket(rawCapture.Timeval, tcpPacket);
                }
            }
            var endTime = DateTime.Now;

            // restore logging
            LoggingConfiguration.GlobalLoggingLevel = oldThreshold;

            var rate = new Utils.Rate(startTime, endTime, connectionsFound, "Connections found");

            Console.WriteLine(rate.ToString());
        }
 private ReplicationMessage.ReplicaSubscriptionRequest UnwrapReplicaSubscriptionRequest(TcpPackage package, IEnvelope envelope, TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<ReplicationMessageDto.SubscribeReplica>();
     var vnodeTcpEndPoint = new IPEndPoint(new IPAddress(dto.Ip), dto.Port);
     var lastEpochs = dto.LastEpochs.Safe().Select(x => new Epoch(x.EpochPosition, x.EpochNumber, new Guid(x.EpochId))).ToArray();
     return new ReplicationMessage.ReplicaSubscriptionRequest(package.CorrelationId,
                                                              envelope, 
                                                              connection,
                                                              dto.LogPosition,
                                                              new Guid(dto.ChunkId), 
                                                              lastEpochs,
                                                              vnodeTcpEndPoint,
                                                              new Guid(dto.MasterId), 
                                                              new Guid(dto.SubscriptionId), 
                                                              dto.IsPromotable);
 }
        public void when_handling_trusted_write_on_external_service()
        {
            var package = new TcpPackage(TcpCommand.WriteEvents, TcpFlags.TrustedWrite, Guid.NewGuid(), null, null, new byte[] { });

            var dummyConnection = new DummyTcpConnection();

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.External, new ClientTcpDispatcher(),
                InMemoryBus.CreateTest(), dummyConnection, InMemoryBus.CreateTest(), new InternalAuthenticationProvider(new Core.Helpers.IODispatcher(InMemoryBus.CreateTest(), new NoopEnvelope()), new StubPasswordHashAlgorithm(), 1),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { });

            tcpConnectionManager.ProcessPackage(package);

            var data = dummyConnection.ReceivedData.Last();
            var receivedPackage = TcpPackage.FromArraySegment(data);
           
            Assert.AreEqual(receivedPackage.Command, TcpCommand.BadRequest, "Expected Bad Request but got {0}", receivedPackage.Command);
        }
 public ConnectionEstablished(TcpConnectionManager connection)
 {
     Connection = connection;
 }
            public ReplicaSubscriptionRequest(Guid correlationId,
                                              IEnvelope envelope, 
                                              TcpConnectionManager connection, 
                                              long logPosition, 
                                              Guid chunkId,
                                              Epoch[] lastEpochs,
                                              IPEndPoint replicaEndPoint, 
                                              Guid masterId,
                                              Guid subscriptionId,
                                              bool isPromotable)
            {
                Ensure.NotEmptyGuid(correlationId, "correlationId");
                Ensure.NotNull(envelope, "envelope");
                Ensure.NotNull(connection, "connection");
                Ensure.Nonnegative(logPosition, "logPosition");
                Ensure.NotNull(lastEpochs, "lastEpochs");
                Ensure.NotNull(replicaEndPoint, "ReplicaEndPoint");
                Ensure.NotEmptyGuid(masterId, "masterId");
                Ensure.NotEmptyGuid(subscriptionId, "subscriptionId");

                CorrelationId = correlationId;
                Envelope = envelope;
                Connection = connection;
                LogPosition = logPosition;
                ChunkId = chunkId;
                LastEpochs = lastEpochs;
                ReplicaEndPoint = replicaEndPoint;
                MasterId = masterId;
                SubscriptionId = subscriptionId;
                IsPromotable = isPromotable;
            }
 private ClientMessage.PersistentSubscriptionNackEvents UnwrapPersistentSubscriptionNackEvents(
     TcpPackage package, IEnvelope envelope, IPrincipal user, string login, string pass,
     TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.PersistentSubscriptionNakEvents>();
     if (dto == null) return null;
     return new ClientMessage.PersistentSubscriptionNackEvents(
         Guid.NewGuid(), package.CorrelationId, envelope, dto.SubscriptionId,
         dto.Message, (ClientMessage.PersistentSubscriptionNackEvents.NakAction)dto.Action,
         dto.ProcessedEventIds.Select(x => new Guid(x)).ToArray(), user);
 }
 private ClientMessage.UnsubscribeFromStream UnwrapUnsubscribeFromStream(TcpPackage package, IEnvelope envelope, TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.UnsubscribeFromStream>();
     if (dto == null) return null;
     return new ClientMessage.UnsubscribeFromStream(connection, package.CorrelationId, dto.EventStreamId);
 }
 private static ClientMessage.ReadStreamEventsForward UnwrapReadStreamEventsForward(TcpPackage package,
                                                                                    IEnvelope envelope,
                                                                                    TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.ReadStreamEventsForward>();
     if (dto == null) return null;
     return new ClientMessage.ReadStreamEventsForward(package.CorrelationId,
                                                      envelope,
                                                      dto.EventStreamId,
                                                      dto.StartIndex,
                                                      dto.MaxCount,
                                                      dto.ResolveLinkTos);
 }
 private ClientMessage.SubscribeToAllStreams UnwrapSubscribeToAllStreams(TcpPackage package, IEnvelope envelope, TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<ClientMessageDto.SubscribeToAllStreams>();
     return new ClientMessage.SubscribeToAllStreams(connection, new Guid(dto.CorrelationId));
 }
        private ClientMessage.UpdatePersistentSubscription UnwrapUpdatePersistentSubscription(
            TcpPackage package, IEnvelope envelope, IPrincipal user, string username, string password,
            TcpConnectionManager connection)
        {

            var dto = package.Data.Deserialize<TcpClientMessageDto.UpdatePersistentSubscription>();
            if (dto == null) return null;

            var namedConsumerStrategy = dto.NamedConsumerStrategy;
            if (string.IsNullOrEmpty(namedConsumerStrategy))
            {
                namedConsumerStrategy = dto.PreferRoundRobin
                  ? SystemConsumerStrategies.RoundRobin
                  : SystemConsumerStrategies.DispatchToSingle;
            }

            return new ClientMessage.UpdatePersistentSubscription(Guid.NewGuid(), package.CorrelationId, envelope,
                dto.EventStreamId, dto.SubscriptionGroupName, dto.ResolveLinkTos, dto.StartFrom,
                dto.MessageTimeoutMilliseconds,
                dto.RecordStatistics, dto.MaxRetryCount, dto.BufferSize, dto.LiveBufferSize,
                dto.ReadBatchSize, dto.CheckpointAfterTime, dto.CheckpointMinCount,
                dto.CheckpointMaxCount, dto.SubscriberMaxCount, namedConsumerStrategy,
                user, username, password);
        }
 private ClientMessage.SubscribeToStream UnwrapSubscribeToStream(TcpPackage package,
                                                                 IEnvelope envelope,
                                                                 IPrincipal user,
                                                                 string login,
                                                                 string pass,
                                                                 TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.SubscribeToStream>();
     if (dto == null) return null;
     return new ClientMessage.SubscribeToStream(Guid.NewGuid(), package.CorrelationId, envelope,
                                                connection.ConnectionId, dto.EventStreamId, dto.ResolveLinkTos, user);
 }
 private ReplicationMessage.ReplicaSubscribed UnwrapReplicaSubscribed(TcpPackage package, IEnvelope envelope, TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<ReplicationMessageDto.ReplicaSubscribed>();
     return new ReplicationMessage.ReplicaSubscribed(new Guid(dto.MasterId),
                                                     new Guid(dto.SubscriptionId),
                                                     dto.SubscriptionPosition,
                                                     connection.RemoteEndPoint);
 }
 private ReplicationMessage.ReplicaLogPositionAck UnwrapReplicaLogPositionAck(TcpPackage package, IEnvelope envelope, TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<ReplicationMessageDto.ReplicaLogPositionAck>();
     return new ReplicationMessage.ReplicaLogPositionAck(new Guid(dto.SubscriptionId), dto.ReplicationLogPosition);
 }
 private ClientMessage.DeletePersistentSubscription UnwrapDeletePersistentSubscription(
     TcpPackage package, IEnvelope envelope, IPrincipal user, string username, string password,
     TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.CreatePersistentSubscription>();
     if (dto == null) return null;
     return new ClientMessage.DeletePersistentSubscription(Guid.NewGuid(), package.CorrelationId, envelope,
                     dto.EventStreamId, dto.SubscriptionGroupName, user);
 }
 public ConnectionClosed(TcpConnectionManager connection, SocketError socketError)
 {
     Connection = connection;
     SocketError = socketError;
 }
 public TcpSend(TcpConnectionManager connectionManager, Message message)
 {
     ConnectionManager = connectionManager;
     Message = message;
 }
 public Connected(TcpConnectionManager connection)
 {
     _connection = connection;
 }
 private static ClientMessage.ReadAllEventsForward UnwrapReadAllEventsForward(TcpPackage package, IEnvelope envelope, TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.ReadAllEventsForward>();
     if (dto == null) return null;
     return new ClientMessage.ReadAllEventsForward(package.CorrelationId,
                                                   envelope,
                                                   dto.CommitPosition,
                                                   dto.PreparePosition,
                                                   dto.MaxCount,
                                                   dto.ResolveLinkTos);
 }
Exemple #49
0
 public UnsubscribeFromAllStreams(TcpConnectionManager connection, Guid correlationId)
 {
     Connection = connection;
     CorrelationId = correlationId;
 }
 private ClientMessage.UnsubscribeFromAllStreams UnwrapUnsubscribeFromAllStreams(TcpPackage package, IEnvelope envelope, TcpConnectionManager connection)
 {
     //var dto = package.Data.Deserialize<HttpClientMessageDto.UnsubscribeFromAllStreams>();
     return new ClientMessage.UnsubscribeFromAllStreams(connection, package.CorrelationId);
 }
 public SubscribeToStream(TcpConnectionManager connection, Guid correlationId, string eventStreamId, bool resolveLinkTos)
 {
     Connection = connection;
     CorrelationId = correlationId;
     EventStreamId = eventStreamId;
     ResolveLinkTos = resolveLinkTos;
 }
Exemple #52
0
 public UnsubscribeFromStream(TcpConnectionManager connection, Guid correlationId, string eventStreamId)
 {
     Connection = connection;
     CorrelationId = correlationId;
     EventStreamId = eventStreamId;
 }
 private ClientMessage.ConnectToPersistentSubscription UnwrapConnectToPersistentSubscription(
     TcpPackage package, IEnvelope envelope, IPrincipal user, string login, string pass,
     TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.ConnectToPersistentSubscription>();
     if (dto == null) return null;
     return new ClientMessage.ConnectToPersistentSubscription(Guid.NewGuid(), package.CorrelationId, envelope,
         connection.ConnectionId, dto.SubscriptionId, dto.EventStreamId, dto.AllowedInFlightMessages, connection.RemoteEndPoint.ToString(), user);
 }