public SocketFrameHandler_0_9(AmqpTcpEndpoint endpoint)
        {
            m_endpoint = endpoint;
            m_socket = new TcpClient();
            m_socket.Connect(endpoint.HostName, endpoint.Port);
            // disable Nagle's algorithm, for more consistently low latency 
            m_socket.NoDelay = true;

            Stream netstream = m_socket.GetStream();
            m_reader = new NetworkBinaryReader(netstream);
            m_writer = new NetworkBinaryWriter(netstream);
        }
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
            Func<AddressFamily, ITcpClient> socketFactory,
            int connectionTimeout, int readTimeout, int writeTimeout)
        {
            Endpoint = endpoint;
            m_socket = null;
            if (Socket.OSSupportsIPv6)
            {
                try
                {
                    m_socket = socketFactory(AddressFamily.InterNetworkV6);
                    Connect(m_socket, endpoint, connectionTimeout);
                }
                catch (ConnectFailureException) // could not connect using IPv6
                {
                    m_socket = null;
                }
                // Mono might raise a SocketException when using IPv4 addresses on
                // an OS that supports IPv6
                catch (SocketException)
                {
                    m_socket = null;
                }
            }
            if (m_socket == null)
            {
                m_socket = socketFactory(AddressFamily.InterNetwork);
                Connect(m_socket, endpoint, connectionTimeout);
            }

            Stream netstream = m_socket.GetStream();
            netstream.ReadTimeout  = readTimeout;
            netstream.WriteTimeout = writeTimeout;

            if (endpoint.Ssl.Enabled)
            {
                try
                {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
            }
            m_reader = new NetworkBinaryReader(new BufferedStream(netstream));
            m_writer = new NetworkBinaryWriter(new BufferedStream(netstream));

            m_writeableStateTimeout = writeTimeout;
        }
Exemplo n.º 3
0
        public void TestCreateConnectionWithAutoRecoveryUsesInvalidAmqpTcpEndpoint()
        {
            var cf = new ConnectionFactory();

            cf.AutomaticRecoveryEnabled = true;
            var ep = new AmqpTcpEndpoint("localhost", 1234);

            Assert.That(() =>
            {
                using (var conn = cf.CreateConnection(new System.Collections.Generic.List <AmqpTcpEndpoint> {
                    ep
                }));
            }, Throws.TypeOf <BrokerUnreachableException>());
        }
        private ITcpClient ConnectUsingAddressFamily(AmqpTcpEndpoint endpoint,
                                                     Func <AddressFamily, ITcpClient> socketFactory,
                                                     int timeout, AddressFamily family)
        {
            ITcpClient socket = socketFactory(family);

            try {
                ConnectOrFail(socket, endpoint, timeout);
                return(socket);
            } catch (ConnectFailureException e) {
                socket.Dispose();
                throw e;
            }
        }
Exemplo n.º 5
0
 private IConnection CreateConnection(AmqpConfiguration configuration)
 {
     try
     {
         var endpoint = new AmqpTcpEndpoint(configuration.Host, configuration.Port, _sslOption);
         return(_connectionFactory.CreateConnection(new List <AmqpTcpEndpoint> {
             endpoint
         }));
     }
     catch (Exception ex)
     {
         throw new FiksIOAmqpConnectionFailedException($"Unable to create connection. Host: {configuration.Host}; Port: {configuration.Port}; UserName:{_connectionFactory.UserName}; SslOption.Enabled: {_sslOption?.Enabled};SslOption.ServerName: {_sslOption?.ServerName}", ex);
     }
 }
Exemplo n.º 6
0
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
                                  ConnectionFactoryBase.ObtainSocket socketFactory,
                                  int timeout)
        {
            m_endpoint = endpoint;
            m_socket   = null;
            if (Socket.OSSupportsIPv6)
            {
                try
                {
                    m_socket = socketFactory(AddressFamily.InterNetworkV6);
                    Connect(m_socket, endpoint, timeout);
                }
                catch (ConnectFailureException) // could not connect using IPv6
                {
                    m_socket = null;
                }
                // Mono might raise a SocketException when using IPv4 addresses on
                // an OS that supports IPv6
                catch (SocketException)
                {
                    m_socket = null;
                }
            }
            if (m_socket == null)
            {
                m_socket = socketFactory(AddressFamily.InterNetwork);
                Connect(m_socket, endpoint, timeout);
            }

            Stream netstream = m_socket.GetStream();

            netstream.ReadTimeout  = timeout;
            netstream.WriteTimeout = timeout;

            if (endpoint.Ssl.Enabled)
            {
                try
                {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
            }
            m_reader = new NetworkBinaryReader(new BufferedStream(netstream));
            m_writer = new NetworkBinaryWriter(new BufferedStream(netstream));
        }
Exemplo n.º 7
0
        public void TestCreateConnectionWithForcedAddressFamily()
        {
            var cf = new ConnectionFactory
            {
                HostName = "not_localhost"
            };
            var ep = new AmqpTcpEndpoint("localhost")
            {
                AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork
            };

            cf.Endpoint = ep;
            using (IConnection conn = cf.CreateConnection()) { };
        }
Exemplo n.º 8
0
        public void TestCreateConnectionWithAutoRecoveryUsesAmqpTcpEndpoint()
        {
            var cf = new ConnectionFactory
            {
                AutomaticRecoveryEnabled = true,
                HostName = "not_localhost",
                Port     = 1234
            };
            var ep = new AmqpTcpEndpoint("localhost");

            using (IConnection conn = cf.CreateConnection(new System.Collections.Generic.List <AmqpTcpEndpoint> {
                ep
            })) { }
        }
Exemplo n.º 9
0
        private async Task <Socket> ConnectUsingAddressFamily(AmqpTcpEndpoint endpoint,
                                                              Func <AddressFamily, Socket> socketFactory,
                                                              int timeout, AddressFamily family)
        {
            Socket socket = socketFactory(family);

            try {
                await ConnectOrFail(socket, endpoint, timeout);

                return(socket);
            } catch (ConnectFailureException e) {
                socket.Dispose();
                throw e;
            }
        }
Exemplo n.º 10
0
        public static IFrameHandler CreateFrameHandler(
#pragma warning disable RCS1175 // Unused this parameter.
#pragma warning disable IDE0060 // Remove unused parameter
            this IProtocol protocol,
#pragma warning restore IDE0060 // Remove unused parameter
#pragma warning restore RCS1175 // Unused this parameter.
            AmqpTcpEndpoint endpoint,
            Func <AddressFamily, ITcpClient> socketFactory,
            int connectionTimeout,
            int readTimeout,
            int writeTimeout)
        {
            return(new SocketFrameHandler(endpoint, socketFactory,
                                          connectionTimeout, readTimeout, writeTimeout));
        }
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
                                  Func <AddressFamily, ITcpClient> socketFactory,
                                  TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
        {
            Endpoint = endpoint;

            if (ShouldTryIPv6(endpoint))
            {
                try
                {
                    _socket = ConnectUsingIPv6(endpoint, socketFactory, connectionTimeout);
                }
                catch (ConnectFailureException)
                {
                    _socket = null;
                }
            }

            if (_socket == null && endpoint.AddressFamily != AddressFamily.InterNetworkV6)
            {
                _socket = ConnectUsingIPv4(endpoint, socketFactory, connectionTimeout);
            }

            Stream netstream = _socket.GetStream();

            netstream.ReadTimeout  = (int)readTimeout.TotalMilliseconds;
            netstream.WriteTimeout = (int)writeTimeout.TotalMilliseconds;

            if (endpoint.Ssl.Enabled)
            {
                try
                {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
            }
            _reader = new BufferedStream(netstream, _socket.Client.ReceiveBufferSize);
            _writer = new BufferedStream(netstream, _socket.Client.SendBufferSize);

            WriteTimeout = writeTimeout;
            _frameWriter = Task.Run(WriteFrameImpl);
        }
        public IEnumerable <AmqpTcpEndpoint> All()
        {
            _lastNode = _nodes[_nextHostIndex % _nodes.Length];

            var hostName = _lastNode.HostName;
            var port     = _lastNode.Port ?? _settings.Port;

            Interlocked.Increment(ref _nextHostIndex);

            LogContext.Debug?.Log("Returning next host: {Host}:{Port}", hostName, port);

            var endpoint = new AmqpTcpEndpoint(hostName, port);

            _settings.ApplySslOptions(endpoint.Ssl);

            yield return(endpoint);
        }
Exemplo n.º 13
0
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
                                  Func <AddressFamily, ITcpClient> socketFactory,
                                  int connectionTimeout, int readTimeout, int writeTimeout)
        {
            Endpoint = endpoint;

            if (ShouldTryIPv6(endpoint))
            {
                try
                {
                    m_socket = ConnectUsingIPv6(endpoint, socketFactory, connectionTimeout);
                }
                catch (ConnectFailureException)
                {
                    m_socket = null;
                }
            }

            if (m_socket == null && endpoint.AddressFamily != AddressFamily.InterNetworkV6)
            {
                m_socket = ConnectUsingIPv4(endpoint, socketFactory, connectionTimeout);
            }

            Stream netstream = m_socket.GetStream();

            netstream.ReadTimeout  = readTimeout;
            netstream.WriteTimeout = writeTimeout;

            if (endpoint.Ssl.Enabled)
            {
                try
                {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                    _ssl      = true;
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
            }
            m_reader = new NetworkBinaryReader(new BufferedStream(netstream, m_socket.Client.ReceiveBufferSize));
            m_writer = new NetworkBinaryWriter(netstream);

            m_writeableStateTimeout = writeTimeout;
        }
Exemplo n.º 14
0
        private async Task <IModel> ConnectAsync(CancellationToken cancellationToken)
        {
            ExceptionDispatchInfo?edi = null;

            for (var i = 0; i < 5; i++)
            {
                try
                {
                    AmqpTcpEndpoint endpoint;
                    var             connectionString = _configuration["connectionstring:rabbit"];
                    if (connectionString == null)
                    {
                        var host = _configuration["service:rabbit:host"];
                        var port = int.Parse(_configuration["service:rabbit:port"]);
                        endpoint = new AmqpTcpEndpoint(host, port);
                    }
                    else
                    {
                        endpoint = new AmqpTcpEndpoint(new Uri(connectionString));
                    }

                    var factory = new ConnectionFactory()
                    {
                        Endpoint = endpoint,
                    };

                    var connection = factory.CreateConnection();
                    return(connection.CreateModel());
                }
                catch (Exception ex)
                {
                    if (i == 4)
                    {
                        edi = ExceptionDispatchInfo.Capture(ex);
                    }

                    _logger.LogError(0, ex, "Failed to start listening to rabbit mq");
                }

                await Task.Delay(5000, cancellationToken);
            }

            edi !.Throw();
            throw null; //unreachable
        }
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
                                  ConnectionFactory.ObtainSocket socketFactory,
                                  int timeout)
        {
            m_endpoint = endpoint;
            m_socket = null;
            if (Socket.OSSupportsIPv6)
            {
                try
                {
                    m_socket = socketFactory(AddressFamily.InterNetworkV6);
                    Connect(m_socket, endpoint, timeout);
                }
                catch (ConnectFailureException) // could not connect using IPv6
                {
                    m_socket = null;
                }
                catch (SocketException) // Mono might raise a SocketException when using IPv4 addresses on an OS that supports IPv6
                {
                    m_socket = null;
                }
            }
            if (m_socket == null)
            {
                m_socket = socketFactory(AddressFamily.InterNetwork);
                Connect(m_socket, endpoint, timeout);
            }

            Stream netstream = m_socket.GetStream();
            if (endpoint.Ssl.Enabled)
            {
                try
                {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl, timeout);
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
            }
            m_reader = new NetworkBinaryReader(new BufferedStream(netstream));
            m_writer = new NetworkBinaryWriter(new BufferedStream(netstream));
        }
Exemplo n.º 16
0
        public static LoggerSinkConfiguration RabbitMq(
            this LoggerSinkConfiguration configuration,
            Action <RabbitMqSinkOptions> optionsSetup,
            AmqpTcpEndpoint endpoint,
            Action <ConnectionFactory> connectionFactorySetup,
            IBinaryFormatter binaryFormatter,
            LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose,
            LoggingLevelSwitch levelSwitch         = null,
            string clientProviderName = null)
        {
            RabbitMqSinkOptions options = configuration.Create(optionsSetup);

            RabbitMqSink rabbitMqSink = new RabbitMqSink(options, endpoint, connectionFactorySetup, binaryFormatter,
                                                         clientProviderName);

            configuration.Sink(rabbitMqSink, restrictedToMinimumLevel, levelSwitch);

            return(configuration);
        }
Exemplo n.º 17
0
        public void Connect(string amqpUri, TimeSpan timeout)
        {
            var amqpTcpEndpoint = new AmqpTcpEndpoint(new Uri(amqpUri));

            Logger.Current.Write(string.Format("Establishing connection to host:{0}, port:{1}",
                                               amqpTcpEndpoint.HostName, amqpTcpEndpoint.Port), TraceEventType.Information);
            _connectionFactory = new ConnectionFactory
            {
                Uri = amqpUri
            };

            _messagePublisher = new MessagePublisher(_connectionFactory.UserName,
                                                     _configurationModel.PublishRouteConfiguration,
                                                     _configurationModel.ConsumeRouteConfiguration,
                                                     _configurationModel.DefaultSerializationStrategy,
                                                     _configurationModel.ConnectionDownQueueStrategy);
            InitializeConnection(_connectionFactory, timeout);
            RegisterAutoSubscriptions(_configurationModel);
        }
Exemplo n.º 18
0
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
                                  Func <StreamSocket> socketFactory,
                                  int connectionTimeout,
                                  int _readTimeout,
                                  int _writeTimeout)
        {
            Endpoint = endpoint;

            m_socket = socketFactory();
            Connect(m_socket, endpoint, connectionTimeout);

            if (endpoint.Ssl.Enabled)
            {
                IAsyncAction ar = null;
                try
                {
                    var cts = new CancellationTokenSource();
                    if (this.defaultTimeout.HasValue)
                    {
                        cts.CancelAfter(this.defaultTimeout.Value);
                    }

                    ar = this.m_socket.UpgradeToSslAsync(
                        SocketProtectionLevel.Ssl, new HostName(endpoint.Ssl.ServerName));
                    ar.AsTask(cts.Token).Wait();
                    ar.GetResults();
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
                finally
                {
                    if (ar != null)
                    {
                        ar.Close();
                    }
                }
            }
            m_reader = new NetworkBinaryReader(m_socket.InputStream.AsStreamForRead());
            m_writer = new NetworkBinaryWriter(m_socket.OutputStream.AsStreamForWrite());
        }
Exemplo n.º 19
0
        private void Connect(StreamSocket socket, AmqpTcpEndpoint endpoint, int timeout)
        {
            IAsyncAction ar = null;

            try
            {
                var cts = new CancellationTokenSource();
                if (this.defaultTimeout.HasValue)
                {
                    cts.CancelAfter(this.defaultTimeout.Value);
                }

                ar = socket.ConnectAsync(new HostName(endpoint.HostName), endpoint.Port.ToString(), SocketProtectionLevel.PlainSocket);
                if (!ar.AsTask(cts.Token).Wait(timeout))
                {
                    socket.Dispose();
                    throw new TimeoutException("Connection to " + endpoint + " timed out");
                }
                ar.GetResults();
            }
            catch (ArgumentException e)
            {
                throw new ConnectFailureException("Connection failed", e);
            }
            catch (Exception e)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                throw new ConnectFailureException("Connection failed", e);
            }
            finally
            {
                if (ar != null)
                {
                    ar.Close();
                }
            }
        }
Exemplo n.º 20
0
        public SocketFrameHandler_0_9(AmqpTcpEndpoint endpoint)
        {
            m_endpoint = endpoint;
            m_socket = new TcpClient();
            m_socket.Connect(endpoint.HostName, endpoint.Port);
            // disable Nagle's algorithm, for more consistently low latency 
            m_socket.NoDelay = true;

            Stream netstream = m_socket.GetStream();
            if (endpoint.Ssl.Enabled) {
                try {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                } catch (Exception) {
                    Close();
                    throw;
                }
            }
            m_reader = new NetworkBinaryReader(new BufferedStream(netstream));
            m_writer = new NetworkBinaryWriter(new BufferedStream(netstream));
        }
Exemplo n.º 21
0
        public virtual void SetAddresses(string addresses)
        {
            if (!string.IsNullOrEmpty(addresses))
            {
                var endpoints = AmqpTcpEndpoint.ParseMultiple(addresses);
                if (endpoints.Length > 0)
                {
                    Addresses = endpoints.ToList();
                    if (PublisherConnectionFactory != null)
                    {
                        AbstractPublisherConnectionFactory.SetAddresses(addresses);
                    }

                    return;
                }
            }

            _logger?.LogInformation("SetAddresses() called with an empty value, will be using the host+port properties for connections");
            Addresses = null;
        }
Exemplo n.º 22
0
        public static LoggerAuditSinkConfiguration RabbitMq(
            this LoggerAuditSinkConfiguration configuration,
            Action <RabbitMqSinkOptions> optionsSetup,
            AmqpTcpEndpoint endpoint,
            Action <ConnectionFactory> connectionFactorySetup,
            LogEventJsonConverterOptions jsonConverterOptions = null,
            LogEventLevel restrictedToMinimumLevel            = LogEventLevel.Verbose,
            LoggingLevelSwitch levelSwitch = null,
            string clientProviderName      = null)
        {
            RabbitMqSinkOptions options = configuration.Create(optionsSetup);

            RabbitMqSink rabbitMqSink = new RabbitMqSink(options, endpoint, connectionFactorySetup,
                                                         new JsonToUtf8BytesFormatter(jsonConverterOptions ?? new LogEventJsonConverterOptions()),
                                                         clientProviderName);

            configuration.Sink(rabbitMqSink, restrictedToMinimumLevel, levelSwitch);

            return(configuration);
        }
Exemplo n.º 23
0
        public void ToAmqpTcpEndpoints()
        {
            Assert.IsNull(Rabbit.ToAmqpTcpEndpoints(null));

            IList <Uri> list     = new List <Uri>();
            string      uri1Text = "amqps://*****:*****@localhost:5671/";
            Uri         uri1     = new Uri(uri1Text);

            list.Add(uri1);

            IList <AmqpTcpEndpoint> expected = Rabbit.ToAmqpTcpEndpoints(list);

            Assert.IsNotNull(expected);
            Assert.IsTrue(expected.Count > 0);
            AmqpTcpEndpoint amqpTcpEndpoint1 = expected[0];

            Assert.AreEqual("localhost", amqpTcpEndpoint1.HostName);
            Assert.AreEqual(5671, amqpTcpEndpoint1.Port);
            Assert.IsTrue(amqpTcpEndpoint1.Protocol.ApiName.Contains("AMQP"));
            Assert.IsTrue(amqpTcpEndpoint1.Ssl.Enabled);
        }
        private void Init(AmqpTcpEndpoint endpoint)
        {
            m_delegate = new Connection(m_factory, false,
                                        m_factory.CreateFrameHandler(endpoint),
                                        this.ClientProvidedName);

            AutorecoveringConnection         self             = this;
            EventHandler <ShutdownEventArgs> recoveryListener = (_, args) =>
            {
                lock (recoveryLockTarget)
                {
                    if (ShouldTriggerConnectionRecovery(args))
                    {
                        try
                        {
                            self.BeginAutomaticRecovery();
                        }
                        catch (Exception e)
                        {
                            // TODO: logging
#if NETFX_CORE
                            System.Diagnostics.Debug.WriteLine(
#else
                            Console.WriteLine(
#endif
                                "BeginAutomaticRecovery() failed: {0}", e);
                        }
                    }
                }
            };

            lock (m_eventLock)
            {
                ConnectionShutdown += recoveryListener;
                if (!m_recordedShutdownEventHandlers.Contains(recoveryListener))
                {
                    m_recordedShutdownEventHandlers.Add(recoveryListener);
                }
            }
        }
Exemplo n.º 25
0
        public IConnection CreateConnection()
        {
            var connectionString = _configuration.RabbitMqConnectionString;

            if (connectionString == null)
            {
                _logger?.Fatal("Not connection string found for RabbitMQ. Can not create a bus. Aborting...");
                throw new ConfigurationErrorsException("Could not find a connection string for RabbitMQ. Please add a connection string in the <connectionStrings> section of the application's configuration file. For example: <add name=\"RabbitMQ\" connectionString=\"host=localhost\" />");
            }

            try
            {
                _factory.Uri = new Uri(connectionString);

                if (!_configuration.LogSensitiveData && !String.IsNullOrWhiteSpace(_factory.Uri.UserInfo))
                {
                    connectionString = connectionString.Replace($"{_factory.Uri.UserInfo}@", "*** BLOCKED ***@");
                }

                if (_configuration.RabbitMqAutomaticRecoveryEnabled && _factory is ConnectionFactory connectionFactory)
                {
                    connectionFactory.AutomaticRecoveryEnabled = true;
                }

                if (_configuration.RabbitMqClusterHosts == null)
                {
                    _logger?.Verbose("Creating RabbitMQ connection. connection-string={RabbitConnectionString}, automatic-recovery-enabled={RabbitAutomaticRecoveryEnabled}", connectionString, _configuration.RabbitMqAutomaticRecoveryEnabled);
                    return(_factory.CreateConnection());
                }

                _logger?.Verbose("Creating RabbitMQ cluster connection. connection-string={RabbitConnectionString}, cluster-hosts={RabbitClusterHosts}, automatic-recovery-enabled={RabbitAutomaticRecoveryEnabled}", connectionString, _configuration.RabbitMqClusterHosts, _configuration.RabbitMqAutomaticRecoveryEnabled);

                return(_factory.CreateConnection(AmqpTcpEndpoint.ParseMultiple(_configuration.RabbitMqClusterHosts)));
            }
            catch (Exception ex)
            {
                _logger?.Fatal(ex, "Cannot connect to RabbitMQ using the provided configuration.");
                throw;
            }
        }
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
            Func<StreamSocket> socketFactory,
            int connectionTimeout,
            int _readTimeout,
            int _writeTimeout)
        {
            Endpoint = endpoint;

            m_socket = socketFactory();
            Connect(m_socket, endpoint, connectionTimeout);

            if (endpoint.Ssl.Enabled)
            {
                IAsyncAction ar = null;
                try
                {
                    var cts = new CancellationTokenSource();
                    if (this.defaultTimeout.HasValue)
                        cts.CancelAfter(this.defaultTimeout.Value);

                    ar = this.m_socket.UpgradeToSslAsync(
                        SocketProtectionLevel.Ssl, new HostName(endpoint.Ssl.ServerName));
                    ar.AsTask(cts.Token).Wait();
                    ar.GetResults();
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
                finally
                {
                    if (ar != null)
                        ar.Close();
                }
            }
            m_reader = new NetworkBinaryReader(m_socket.InputStream.AsStreamForRead());
            m_writer = new NetworkBinaryWriter(m_socket.OutputStream.AsStreamForWrite());
        }
Exemplo n.º 27
0
        private void ApplySettings(ConnectionFactory connectionFactory, ConnectionSettings settings)
        {
            var endpoint = settings.Endpoint;

            if (!string.IsNullOrWhiteSpace(settings.Connection))
            {
                endpoint = _configuration?.GetSection(settings.Connection).Value;
            }

            if (!string.IsNullOrWhiteSpace(endpoint))
            {
                connectionFactory.Endpoint = AmqpTcpEndpoint.Parse(endpoint);
            }

            if (settings.UserName != null)
            {
                connectionFactory.UserName = settings.UserName;
            }

            if (settings.Password != null)
            {
                connectionFactory.Password = settings.Password;
            }

            if (settings.HostName != null)
            {
                connectionFactory.HostName = settings.HostName;
            }

            if (settings.Port.HasValue)
            {
                connectionFactory.Port = settings.Port.Value;
            }

            if (settings.VirtualHost != null)
            {
                connectionFactory.VirtualHost = settings.VirtualHost;
            }
        }
Exemplo n.º 28
0
        public SocketFrameHandler_0_9(AmqpTcpEndpoint endpoint)
        {
            m_endpoint = endpoint;
            m_socket   = new TcpClient();
            m_socket.Connect(endpoint.HostName, endpoint.Port);
            // disable Nagle's algorithm, for more consistently low latency
            m_socket.NoDelay = true;

            Stream netstream = m_socket.GetStream();

            if (endpoint.Ssl.Enabled)
            {
                try {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                } catch (Exception) {
                    Close();
                    throw;
                }
            }
            m_reader = new NetworkBinaryReader(new BufferedStream(netstream));
            m_writer = new NetworkBinaryWriter(new BufferedStream(netstream));
        }
Exemplo n.º 29
0
        private IAutorecoveringConnection Connect()
        {
            var endpoints = configuration.Hosts.Select(x =>
            {
                var endpoint = new AmqpTcpEndpoint(x.Host, x.Port);
                if (x.Ssl.Enabled)
                {
                    endpoint.Ssl = x.Ssl;
                }
                else if (configuration.Ssl.Enabled)
                {
                    endpoint.Ssl = configuration.Ssl;
                }
                return(endpoint);
            }).ToArray();

            var connection = connectionFactory.CreateConnection(endpoints) as IAutorecoveringConnection;

            if (connection == null)
            {
                throw new NotSupportedException("Non-recoverable connection is not supported");
            }

            connection.ConnectionShutdown  += OnConnectionShutdown;
            connection.ConnectionBlocked   += OnConnectionBlocked;
            connection.ConnectionUnblocked += OnConnectionUnblocked;
            connection.RecoverySucceeded   += OnConnectionRecovered;

            logger.InfoFormat(
                "Connected to broker {broker}, port {port}",
                connection.Endpoint.HostName,
                connection.Endpoint.Port
                );

            eventBus.Publish(new ConnectionCreatedEvent(connection.Endpoint));

            return(connection);
        }
Exemplo n.º 30
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthorization();

            services.AddCodeFirstGrpc();

            services.AddSingleton(sp =>
            {
                AmqpTcpEndpoint endpoint;
                var connectionString = Configuration["connectionstring:rabbit"];
                if (connectionString == null)
                {
                    var host = Configuration["service:rabbit:host"];
                    var port = int.Parse(Configuration["service:rabbit:port"]);
                    endpoint = new AmqpTcpEndpoint(host, port);
                }
                else
                {
                    endpoint = new AmqpTcpEndpoint(new Uri(connectionString));
                }

                var factory = new ConnectionFactory()
                {
                    Endpoint = endpoint,
                };
                var connection = factory.CreateConnection();
                var channel    = connection.CreateModel();

                channel.QueueDeclare(queue: "orders",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);
                return(channel);
            });
        }
 private ITcpClient ConnectUsingIPv4(AmqpTcpEndpoint endpoint,
                                     Func <AddressFamily, ITcpClient> socketFactory,
                                     TimeSpan timeout)
 {
     return(ConnectUsingAddressFamily(endpoint, socketFactory, timeout, AddressFamily.InterNetwork));
 }
 private bool ShouldTryIPv6(AmqpTcpEndpoint endpoint)
 {
     return(Socket.OSSupportsIPv6 && endpoint.AddressFamily != AddressFamily.InterNetwork);
 }
Exemplo n.º 33
0
 public void TestMultipleNone()
 {
     AmqpTcpEndpoint[] es = AmqpTcpEndpoint.ParseMultiple("  ");
     Assert.AreEqual(0, es.Length);
 }
Exemplo n.º 34
0
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
                                  Func <AddressFamily, ITcpClient> socketFactory,
                                  TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
        {
            Endpoint           = endpoint;
            _frameHeaderBuffer = new byte[6];
            var channel = Channel.CreateUnbounded <ReadOnlyMemory <byte> >(
                new UnboundedChannelOptions
            {
                AllowSynchronousContinuations = false,
                SingleReader = true,
                SingleWriter = false
            });

            _channelReader = channel.Reader;
            _channelWriter = channel.Writer;

            // Resolve the hostname to know if it's even possible to even try IPv6
            IPAddress[] adds = Dns.GetHostAddresses(endpoint.HostName);
            IPAddress   ipv6 = TcpClientAdapterHelper.GetMatchingHost(adds, AddressFamily.InterNetworkV6);

            if (ipv6 == default(IPAddress))
            {
                if (endpoint.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    throw new ConnectFailureException("Connection failed", new ArgumentException($"No IPv6 address could be resolved for {endpoint.HostName}"));
                }
            }
            else if (ShouldTryIPv6(endpoint))
            {
                try
                {
                    _socket = ConnectUsingIPv6(new IPEndPoint(ipv6, endpoint.Port), socketFactory, connectionTimeout);
                }
                catch (ConnectFailureException)
                {
                    // We resolved to a ipv6 address and tried it but it still didn't connect, try IPv4
                    _socket = null;
                }
            }

            if (_socket == null)
            {
                IPAddress ipv4 = TcpClientAdapterHelper.GetMatchingHost(adds, AddressFamily.InterNetwork);
                if (ipv4 == default(IPAddress))
                {
                    throw new ConnectFailureException("Connection failed", new ArgumentException($"No ip address could be resolved for {endpoint.HostName}"));
                }
                _socket = ConnectUsingIPv4(new IPEndPoint(ipv4, endpoint.Port), socketFactory, connectionTimeout);
            }

            Stream netstream = _socket.GetStream();

            netstream.ReadTimeout  = (int)readTimeout.TotalMilliseconds;
            netstream.WriteTimeout = (int)writeTimeout.TotalMilliseconds;

            if (endpoint.Ssl.Enabled)
            {
                try
                {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
            }

            _reader = new BufferedStream(netstream, _socket.Client.ReceiveBufferSize);
            _writer = new BufferedStream(netstream, _socket.Client.SendBufferSize);

            WriteTimeout = writeTimeout;
            _writerTask  = Task.Run(WriteLoop, CancellationToken.None);
        }
Exemplo n.º 35
0
 public abstract IFrameHandler CreateFrameHandler(AmqpTcpEndpoint endpoint);
 private void Connect(ITcpClient socket, AmqpTcpEndpoint endpoint, int timeout)
 {
     try
     {
         socket.ConnectAsync(endpoint.HostName, endpoint.Port)
                     .TimeoutAfter(timeout)
                     .ConfigureAwait(false)
                     .GetAwaiter()//this ensures exceptions aren't wrapped in an AggregateException
                     .GetResult();
     }
     catch (ArgumentException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (SocketException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (NotSupportedException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (TimeoutException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
 }
 private void Connect(TcpClient socket, AmqpTcpEndpoint endpoint, int timeout)
 {
     IAsyncResult ar = null;
     try
     {
         ar = socket.BeginConnect(endpoint.HostName, endpoint.Port, null, null);
         if (!ar.AsyncWaitHandle.WaitOne(timeout, false))
         {
             socket.Close();
             throw new TimeoutException("Connection to " + endpoint + " timed out");
         }
         socket.EndConnect(ar);
     }
     catch (ArgumentException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (SocketException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     finally
     {
         if (ar != null)
             ar.AsyncWaitHandle.Close();
     }
 }
        private void Connect(StreamSocket socket, AmqpTcpEndpoint endpoint, int timeout)
        {
            IAsyncAction ar = null;
            try
            {
                var cts = new CancellationTokenSource();
                if (this.defaultTimeout.HasValue)
                    cts.CancelAfter(this.defaultTimeout.Value);

                ar = socket.ConnectAsync(new HostName(endpoint.HostName), endpoint.Port.ToString(), SocketProtectionLevel.PlainSocket);
                if (!ar.AsTask(cts.Token).Wait(timeout))
                {
                    socket.Dispose();
                    throw new TimeoutException("Connection to " + endpoint + " timed out");
                }
                ar.GetResults();
            }
            catch (ArgumentException e)
            {
                throw new ConnectFailureException("Connection failed", e);
            }
            catch (Exception e)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                throw new ConnectFailureException("Connection failed", e);
            }
            finally
            {
                if (ar != null)
                {
                    ar.Close();
                }
            }
        }